# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import("//build/common.gni")
import("//build/config/c++/c++.gni")
import("//build/config/clang/clang.gni")
import("//build/config/compiler/compiler.gni")
import("//build/config/coverage/coverage.gni")
import("//build/config/sanitizers/sanitizers.gni")
import("//build/ohos_var.gni")
import("//build/toolchain/cc_wrapper.gni")
import("//build/toolchain/toolchain.gni")

import("//build/misc/overrides/build.gni")

if (current_cpu == "arm" || current_cpu == "arm64") {
  import("//build/config/arm.gni")
}
if (is_android) {
  import("//build_plugins/config/aosp/config.gni")
}
if (is_ohos) {
  import("//build/config/ohos/config.gni")
}
if (is_mac) {
  import("//build/config/mac/symbols.gni")
}
if (is_mac || is_ios) {
  import("//build/config/mac/mac_sdk.gni")
}
declare_args() {
  # Default to warnings as errors for default workflow, where we catch
  # warnings with known toolchains. Allow overriding this e.g. for Chromium
  # builds on Linux that could use a different version of the compiler.
  # With GCC, warnings in no-Chromium code are always not treated as errors.
  treat_warnings_as_errors = true

  # Whether to use the binary binutils checked into third_party/binutils.
  # These are not multi-arch so cannot be used except on x86 and x86-64 (the
  # only two architectures that are currently checked in). Turn this off when
  # you are using a custom toolchain and need to control -B in cflags.
  linux_use_bundled_binutils =
      linux_use_bundled_binutils_override && is_linux &&
      (current_cpu == "x64" || current_cpu == "x86")
  binutils_path = rebase_path("//third_party/binutils/Linux_x64/Release/bin",
                              root_build_dir)

  # Compile in such a way as to make it possible for the profiler to unwind full
  # stack frames. Setting this flag has a large effect on the performance of the
  # generated code than just setting profiling, but gives the profiler more
  # information to analyze.
  # Requires profiling to be set to true.
  enable_full_stack_frames_for_profiling = false

  # When we are going to use gold we need to find it.
  # This is initialized below, after use_gold might have been overridden.
  gold_path = false

  if (is_win) {
    # Whether the VS xtree header has been patched to disable warning 4702. If
    # it has, then we don't need to disable 4702 (unreachable code warning).
    # The patch is preapplied to the internal toolchain and hence all bots.
    msvs_xtree_patched = false
  }

  # Enable fatal linker warnings. Building Chromium with certain versions
  # of binutils can cause linker warning.
  # See: https://bugs.chromium.org/p/chromium/issues/detail?id=457359
  fatal_linker_warnings = true

  # Build with C++ RTTI enabled. Chromium builds without RTTI by default,
  # but some sanitizers are known to require it, like CFI diagnostics
  # and UBsan variants.
  use_rtti = use_cfi_diag || is_ubsan_vptr || is_ubsan_security

  # AFDO (Automatic Feedback Directed Optimizer) is a form of profile-guided
  # optimization that GCC supports. It used by ChromeOS in their official
  # builds. To use it, set auto_profile_path to the path to a file containing
  # the needed gcov profiling data.
  auto_profile_path = ""

  # Optimize symbol files for maximizing goma cache hit rate. This is on by
  # default when goma is enabled on Linux and Windows.
  # But setting this to true may make it harder to debug binaries on Linux.
  # See below reference for detail.
  strip_absolute_paths_from_debug_symbols = false

  # Allow projects that wish to stay on C++11 to override Chromium's default.
  use_cxx11 = false

  # Path to an AFDO profile to use while building with clang, if any. Empty
  # implies none.
  clang_sample_profile_path = ""

  # Some configurations have default sample profiles. If this is true and
  # clang_sample_profile_path is empty, we'll fall back to the default.
  #
  # We currently only have default profiles for Chromium in-tree, so we disable
  # this by default for all downstream projects, since these profiles are likely
  # nonsensical for said projects.
  clang_use_default_sample_profile =
      is_official_build && (is_ohos || is_android || is_desktop_linux)

  # Turn this on to have the compiler output extra timing information.
  compiler_timing = false

  # Set to true to pass --no-rosegment to lld. This is a workaround
  # for a KI issue in Valgrind,
  # https://bugs.kde.org/show_bug.cgi?id=384727
  ro_segment_workaround_for_valgrind = false

  # Turn this on to use ghash feature of lld for faster debug link on Windows.
  # http://blog.llvm.org/2018/01/improving-link-time-on-windows-with.html
  use_ghash = false

  # Whether to enable ThinLTO optimizations. Turning ThinLTO optimizations on
  # can substantially increase link time and binary size, but they generally
  # also make binaries a fair bit faster.
  thin_lto_enable_optimizations = is_chromeos

  # By default only the binaries in official builds get build IDs.
  force_local_build_id = true

  use_thinlto_cache = false
}

declare_args() {
  use_cxx11_on_ohos = use_cxx11
}

declare_args() {
  # Set to true to use icf, Identical Code Folding.
  #
  # icf=all is broken in older golds, see
  # https://sourceware.org/bugzilla/show_bug.cgi?id=17704
  # See also https://crbug.com/663886
  # `linux_use_bundled_binutils` is to avoid breaking Linux destroys which may
  # still have a buggy gold.
  # chromeos binutils has been patched with the fix, so always use icf there.
  # The bug only affects x86 and x64, so we can still use ICF when targeting
  # other architectures.
  #
  # lld doesn't have the bug.
  use_icf = is_posix && !using_sanitizer && !use_clang_coverage &&
            !((is_ohos || is_android) && use_order_profiling) &&
            (use_lld ||
             (use_gold &&
              ((!(is_ohos || is_android) && linux_use_bundled_binutils) ||
               is_chromeos || !(current_cpu == "x86" || current_cpu == "x64"))))
}

# Apply the default logic for these values if they were not set explicitly.
if (gold_path == false) {
  if (use_gold) {
    gold_path = rebase_path("//third_party/binutils/Linux_x64/Release/bin",
                            root_build_dir)
  } else {
    gold_path = ""
  }
}

if (use_debug_fission == "default") {
  use_debug_fission = is_debug && !(is_ohos || is_android) && !is_win &&
                      (use_gold || use_lld) && cc_wrapper == ""
}

# default_include_dirs ---------------------------------------------------------
#
# This is a separate config so that third_party code (which would not use the
# source root and might have conflicting versions of some headers) can remove
# this and specify their own include paths.
config("default_include_dirs") {
  include_dirs = [
    "${root_out_dir}/override/third_party",
    "//",
    root_gen_dir,
  ]
}

declare_args() {
  # set thinlto cache default size 100g
  thinlto_cache_policy = "cache_size_bytes=100g"
}

# compiler ---------------------------------------------------------------------
#
# Base compiler configuration.
#
# See also "runtime_library" below for related stuff and a discussion about
# where stuff should go. Put warning related stuff in the "warnings" config.

config("compiler") {
  asmflags = []
  cflags = []
  cflags_c = []
  cflags_cc = []
  cflags_objc = []
  cflags_objcc = []
  ldflags = []
  defines = []
  configs = []
  inputs = []

  # System-specific flags. If your compiler flags apply to one of the
  # categories here, add it to the associated file to keep this shared config
  # smaller.
  if (is_win) {
    configs += [ "//build/config/win:compiler" ]
  } else if (is_ohos) {
    configs += [ "//build/config/ohos:compiler" ]
  } else if (is_linux) {
    configs += [ "//build/config/linux:compiler" ]
  } else if (is_nacl) {
    configs += [ "//build/config/nacl:compiler" ]
  } else if (is_mac) {
    configs += [ "//build/config/mac:compiler" ]
  } else if (current_os == "aix") {
    configs += [ "//build/config/aix:compiler" ]
  } else if (is_mingw) {
    configs += [ "//build/config/mingw:compiler" ]
  } else if (is_android) {
    configs += [ "//build_plugins/config/aosp:compiler" ]
  } else if (is_ios) {
    configs += [ "//build_plugins/config/ios:compiler" ]
  }

  configs += [
    # See the definitions below.
    ":compiler_cpu_abi",
    ":compiler_codegen",
  ]

  if (is_ohos && is_standard_system && is_clang &&
      (target_cpu == "arm" || target_cpu == "arm64" ||
       target_cpu == "riscv64")) {
    ldflags += [ "-Wl,--pack-dyn-relocs=android+relr" ]
  }

  # In general, Windows is totally different, but all the other builds share
  # some common GCC configuration.
  if (!is_win) {
    # Common POSIX compiler flags setup.
    # --------------------------------
    cflags += [ "-fno-strict-aliasing" ]  # See http://crbug.com/32204

    configs += [ "//build/config/security:stack_protector_config" ]

    # Linker warnings.
    if (fatal_linker_warnings && !(is_chromeos && current_cpu == "arm") &&
        !(is_ohos && use_order_profiling) && !is_mac && current_os != "aix" &&
        !is_mingw && !is_ios) {
      ldflags += [ "-Wl,--fatal-warnings" ]
    }
  } else {
    cflags += [
      # Assume UTF-8 by default to avoid code page dependencies.
      "/utf-8",
    ]
    if (is_clang) {
      # Don't look for includes in %INCLUDE%.
      cflags += [ "/X" ]
    }
  }

  # Eliminate build metadata (__DATE__, __TIME__ and __TIMESTAMP__) for
  # deterministic build.  See https://crbug.com/314403
  if (!is_official_build) {
    if (is_win && !is_clang) {
      cflags += [
        "/wd4117",  # Trying to define or undefine a predefined macro.
        "/D__DATE__=",
        "/D__TIME__=",
        "/D__TIMESTAMP__=",
      ]
    } else {
      cflags += [
        "-Wno-builtin-macro-redefined",
        "-D__DATE__=",
        "-D__TIME__=",
        "-D__TIMESTAMP__=",
      ]
    }
  }

  if (is_posix && !is_mac) {
    if (enable_profiling) {
      if (!is_debug) {
        cflags += [ "-g" ]

        if (enable_full_stack_frames_for_profiling) {
          cflags += [
            "-fno-inline",
            "-fno-optimize-sibling-calls",
          ]
        }
      }
    }

    if (!is_mingw && !is_ios && (is_official_build || force_local_build_id)) {
      # Explicitly pass --build-id to ld. Compilers used to always pass this
      # implicitly but don't any more (in particular clang when built without
      # ENABLE_LINKER_BUILD_ID=ON). The crash infrastructure does need a build
      # id, so explicitly enable it in official builds. It's not needed in
      # unofficial builds and computing it does slow down the link, so go with
      # faster links in unofficial builds.
      ldflags += [ "-Wl,--build-id=md5" ]
    }

    if (!is_ohos && !is_ohos) {
      defines += [
        "_FILE_OFFSET_BITS=64",
        "_LARGEFILE_SOURCE",
        "_LARGEFILE64_SOURCE",
      ]
    }

    if (!is_nacl && !is_llvm_build) {
      cflags += [ "-funwind-tables" ]
    }
  }

  if (is_linux || is_android || is_ohos) {
    if (use_pic) {
      cflags += [ "-fPIC" ]
      ldflags += [ "-fPIC" ]
    }

    if (!is_clang) {
      # Use pipes for communicating between sub-processes. Faster.
      # (This flag doesn't do anything with Clang.)
      cflags += [ "-pipe" ]
    }

    ldflags += [
      "-Wl,-z,noexecstack",
      "-Wl,-z,now",
      "-Wl,-z,relro",
    ]

    # Compiler instrumentation can introduce dependencies in DSOs to symbols in
    # the executable they are loaded into, so they are unresolved at link-time.
    if (is_ohos || (!using_sanitizer && !is_safestack)) {
      ldflags += [
        "-Wl,-z,defs",
        "-Wl,--as-needed",
      ]
    }

    # Change default thread stack size to 2MB for asan.
    if (is_ohos && using_sanitizer) {
      ldflags += [ "-Wl,-z,stack-size=2097152" ]
    }
  }

  if (is_android && is_clang) {
    _rebased_aosp_toolchain_root =
        rebase_path(aosp_toolchain_root, root_build_dir)

    # Let clang find the linker in the NDK.
    ldflags += [ "--gcc-toolchain=$_rebased_aosp_toolchain_root" ]
  }

  if ((is_posix && use_lld) || (target_os == "chromeos" && is_android) ||
      (is_ohos && use_lld)) {
    # NOTE: Some Chrome OS builds globally disable LLD, but they also build some
    # targets against ohos toolchains which should use LLD. Therefore we
    # explicitly select LLD in these cases.
    ldflags += [ "-fuse-ld=lld" ]
    if (current_cpu == "arm64") {
      # Reduce the page size from 65536 in order to reduce binary size slightly
      # by shrinking the alignment gap between segments. This also causes all
      # segments to be mapped adjacently, which breakpad relies on.
      ldflags += [ "-Wl,-z,max-page-size=4096" ]
    }
  } else if (use_gold) {
    ldflags += [ "-fuse-ld=gold" ]
    if (!(is_ohos || is_android)) {
      # On ohos, this isn't needed.  gcc in the NDK knows to look next to
      # it with -fuse-ld=gold, and clang gets a --gcc-toolchain flag passed
      # above.
      ldflags += [ "-B$gold_path" ]

      if (linux_use_bundled_binutils) {
        ldflags += [
          # Experimentation found that using four linking threads
          # saved ~20% of link time.
          # Only apply this to the target linker, since the host
          # linker might not be gold, but isn't used much anyway.
          "-Wl,--threads",
          "-Wl,--thread-count=4",
        ]
      }
    }
  } else if (linux_use_bundled_binutils) {
    # Gold is the default linker for the bundled binutils so we explicitly
    # enable the bfd linker when use_gold is not set.
    ldflags += [ "-fuse-ld=bfd" ]
  }

  if (use_icf) {
    ldflags += [ "-Wl,--icf=all" ]
  }

  if (linux_use_bundled_binutils) {
    cflags += [ "-B$binutils_path" ]
  }

  if (is_linux) {
    cflags += [ "-pthread" ]
    # Do not use the -pthread ldflag here since it becomes a no-op
    # when using -nodefaultlibs, which would cause an unused argument
    # error.  "-lpthread" is added in //build/config:default_libs.
  }

  # Clang-specific compiler flags setup.
  # ------------------------------------
  if (is_clang) {
    cflags += [ "-fcolor-diagnostics" ]

    # Enable -fmerge-all-constants. This used to be the default in clang
    # for over a decade. It makes clang non-conforming, but is fairly safe
    # in practice and saves some binary size. We might want to consider
    # disabling this (https://bugs.llvm.org/show_bug.cgi?id=18538#c13),
    # but for now it looks like our build might rely on it
    # (https://crbug.com/829795).
    cflags += [ "-fmerge-all-constants" ]
  }

  if (use_lld) {
    if (is_win) {
      # On Windows, we call the linker directly, instead of calling it through
      # the driver.
      ldflags += [ "--color-diagnostics" ]
    } else {
      ldflags += [ "-Wl,--color-diagnostics" ]
    }
  }

  if (is_clang && !is_nacl && !use_xcode_clang) {
    cflags += [
      "-Xclang",
      "-mllvm",
      "-Xclang",
      "-instcombine-lower-dbg-declare=0",
    ]
  }

  # Print absolute paths in diagnostics. There is no precedent for doing this
  # on Linux/Mac (GCC doesn't support it), but MSVC does this with /FC and
  # Windows developers rely on it (crbug.com/636109) so only do this on Windows.
  if (msvc_use_absolute_paths && is_clang && is_win) {
    cflags += [ "-fdiagnostics-absolute-paths" ]
  }

  # Makes builds independent of absolute file path.
  # Currently disabled for nacl since its toolchain lacks this flag (too old).
  if (symbol_level != 0 && is_clang && !is_nacl && !is_mac &&
      strip_absolute_paths_from_debug_symbols) {
    # If debug option is given, clang includes $cwd in debug info by default.
    # For such build, this flag generates reproducible obj files even we use
    # different build directory like "out/feature_a" and "out/feature_b" if
    # we build same files with same compile flag.
    # Other paths are already given in relative, no need to normalize them.
    cflags += [
      "-Xclang",
      "-fdebug-compilation-dir",
      "-Xclang",
      ".",
    ]

    if (is_win && use_lld) {
      if (symbol_level == 2 || (is_clang && using_sanitizer)) {
        # Absolutize source file path for PDB. Pass the real build directory
        # if the pdb contains source-level debug information.
        ldflags += [ "/PDBSourcePath:" + rebase_path(root_build_dir) ]
      } else {
        # On Windows, (non-sanitizier) symbol_level 1 builds don't contain
        # debug information in obj files; the linker just creates enough
        # debug info at link time to produce symbolized stacks (without line
        # numbers). In that case, there's no downside in using a fake fixed
        # base directory for paths in the pdb. This makes the pdb output
        # fully deterministic and independent of the build directory.
        assert(symbol_level == 1 && !(is_clang && using_sanitizer))
        ldflags += [ "/PDBSourcePath:o:\fake\prefix" ]
      }
    }
  }

  # Tells the compiler not to use absolute paths when passing the default
  # paths to the tools it invokes. We don't want this because we don't
  # really need it and it can mess up the goma cache entries.
  if (is_clang && !is_nacl) {
    cflags += [ "-no-canonical-prefixes" ]
  }

  # C11/C++11 compiler flags setup.
  # ---------------------------
  if (is_linux || is_ohos || is_android || (is_nacl && is_clang) ||
      current_os == "aix") {
    if (target_os == "ohos") {
      cxx11_override = use_cxx11_on_ohos
    } else {
      cxx11_override = use_cxx11
    }

    if (is_clang) {
      standard_prefix = "c"

      # Since we build with -std=c* and not -std=gnu*, _GNU_SOURCE will not be
      # defined by the compiler.  However, lots of code relies on the
      # non-standard features that _GNU_SOURCE enables, so define it manually.
      defines += [ "_GNU_SOURCE" ]

      if (is_nacl) {
        # Undefine __STRICT_ANSI__ to get non-standard features which would
        # otherwise not be enabled by NaCl's sysroots.
        cflags += [ "-U__STRICT_ANSI__" ]
      }
    } else {
      # Gcc does not support ##__VA_ARGS__ when in standards-conforming mode,
      # but we use this feature in several places in Chromium.
      standard_prefix = "gnu"
    }

    #   cflags_c += [ "-std=${standard_prefix}11" ]
    if (cxx11_override) {
      # Override Chromium's default for projects that wish to stay on C++11.
      cflags_cc += [ "-std=${standard_prefix}++11" ]
    } else {
      cflags_cc += [ "-std=${standard_prefix}++17" ]
    }
  } else if (!is_win && !is_nacl && !is_mingw) {
    if (target_os == "ohos") {
      cxx11_override = use_cxx11_on_ohos
    } else {
      cxx11_override = use_cxx11
    }

    if (cxx11_override) {
      cflags_cc += [ "-std=c++11" ]
    } else {
      cflags_cc += [ "-std=c++17" ]
    }
  }

  if (is_mac) {
    # The system libc++ on Mac doesn't have aligned allocation in C++17.
    defines += [ "_LIBCPP_HAS_NO_ALIGNED_ALLOCATION" ]
    cflags_cc += [ "-stdlib=libc++" ]
    ldflags += [ "-stdlib=libc++" ]
  }

  # Add flags for LLD optimizations, which can be applied in FullLTO mode also.
  if (is_ohos && is_clang && use_lld && enhanced_opt && enable_enhanced_opt) {
    if (build_framework_enable_global_reordering) {
      ldflags += [ "-Wl,--reorder-affine-globals" ]
    }
  }

  # Add flags for ThinLTO optimization. These flags enable
  # optimizations/transformations that require whole-program visibility at link
  # time, so they need to be applied to all translation units, and we may end up
  # with miscompiles if only part of the program is compiled with LTO flags. For
  # that reason, we cannot allow targets to enable or disable these flags, for
  # example by disabling the optimize configuration.
  if (!is_debug && use_thin_lto &&
      (current_toolchain == default_toolchain ||
       ((is_ohos || is_android) && defined(ohoa_secondary_abi_toolchain) &&
        current_toolchain == ohos_secondary_abi_toolchain))) {
    assert(use_lld || target_os == "chromeos" || target_os == "ohos",
           "gold plugin only supported with ChromeOS")

    cflags += [ "-flto=thin" ]
    if (!use_libfuzzer) {
      cflags += [ "-fsplit-lto-unit" ]
    }

    if (thin_lto_enable_optimizations) {
      lto_opt_level = 2
    } else {
      lto_opt_level = 0
    }

    if (is_win) {
      # This is a straight translation of the non-Windows flags below,
      # except we do not use the ThinLTO cache, which leaks temporary
      # files on Windows (https://crbug.com/871962).
      ldflags += [
        "/opt:lldlto=" + lto_opt_level,
        "/opt:lldltojobs=8",
      ]
    } else {
      ldflags += [ "-flto=thin" ]

      # Limit the parallelism to avoid too aggressive competition between
      # linker jobs. This is still suboptimal to a potential dynamic
      # resource allocation scheme, but should be good enough.
      if (use_thinlto_cache) {
        cache_base = getenv("CACHE_BASE")
        thinlto_cache_dir = "$cache_base/thinlto-cache"
      } else {
        thinlto_cache_dir =
            rebase_path("$root_out_dir/thinlto-cache", root_build_dir)
      }
      if (use_lld) {
        ldflags += [
          "-Wl,--thinlto-jobs=16",
          "-Wl,--thinlto-cache-dir=$thinlto_cache_dir",
          "-Wl,--thinlto-cache-policy=$thinlto_cache_policy",
        ]
      } else {
        ldflags += [ "-Wl,-plugin-opt,jobs=16" ]
      }

      if (use_lld) {
        ldflags += [ "-Wl,--lto-O" + lto_opt_level ]
        if (thin_lto_enable_optimizations) {
          if (is_android) {
            ldflags += [
              "-Wl,-mllvm",
              "-Wl,-import-instr-limit=5",
            ]
          }
        }
        if (is_ohos && enhanced_opt && enable_enhanced_opt) {
          if (build_framework_enable_thinlto_nca) {
            ldflags += [ "-Wl,-mllvm,-enable-name-collision-analysis" ]
          }
        }
      } else {
        not_needed([ "lto_opt_level" ])
      }
    }

    if (!(is_ohos || is_android)) {
      cflags += [ "-fwhole-program-vtables" ]
      if (!is_win) {
        ldflags += [ "-fwhole-program-vtables" ]
      }
    }

    # Work-around for http://openradar.appspot.com/20356002
    if (is_mac) {
      ldflags += [ "-Wl,-all_load" ]
    }

    # This flag causes LTO to create an .ARM.attributes section with the correct
    # architecture. This is necessary because LLD will refuse to link a program
    # unless the architecture revision in .ARM.attributes is sufficiently new.
    if (current_cpu == "arm") {
      ldflags += [ "-march=$arm_arch" ]
    }
  } else if (current_cpu == "riscv64") {
    if (is_clang && !is_ohos && !is_nacl) {
      cflags += [ "--target=riscv64-linux-gnu" ]
      ldflags += [ "--target=riscv64-linux-gnu" ]
    }
    cflags += [
      "-march=rv64imafdc",
      "-mabi=lp64d",
      "-mno-relax",
    ]
    if (is_clang && is_ohos) {
      ldflags += [ "-Wl,--hash-style=gnu" ]
    }
  }

  if (compiler_timing) {
    if (is_clang) {
      if (is_win) {
        cflags += [ "-Xclang" ]
      }
      cflags += [ "-ftime-report" ]
    } else if (is_win) {
      cflags += [
        # "Documented" here:
        # http://aras-p.info/blog/2017/10/23/Best-unknown-MSVC-flag-d2cgsummary/
        "/d2cgsummary",
      ]
    }
  }

  # Pass flag to LLD to work around issue in Valgrind related to
  # location of debug symbols.
  if (use_lld && ro_segment_workaround_for_valgrind) {
    ldflags += [ "-Wl,--no-rosegment" ]
  }

  # This flag enforces that member pointer base types are complete. It helps
  # prevent us from running into problems in the Microsoft C++ ABI (see
  # https://crbug.com/847724).
  if (is_clang && !is_nacl && target_os != "chromeos" && !use_xcode_clang &&
      (is_win || use_custom_libcxx)) {
    cflags += [ "-fcomplete-member-pointers" ]
  }

  # Pass the same C/C++ flags to the objective C/C++ compiler.
  cflags_objc += cflags_c
  cflags_objcc += cflags_cc

  # Assign any flags set for the C compiler to asmflags so that they are sent
  # to the assembler. The Windows assembler takes different types of flags
  # so only do so for posix platforms.
  if (is_posix) {
    asmflags += cflags
    asmflags += cflags_c
  }
}

# This provides the basic options to select the target CPU and ABI.
# It is factored out of "compiler" so that special cases can use this
# without using everything that "compiler" brings in.  Options that
# tweak code generation for a particular CPU do not belong here!
# See "compiler_codegen", below.
config("compiler_cpu_abi") {
  cflags = []
  ldflags = []
  defines = []

  if (is_posix && !is_mac && !is_ios) {
    # CPU architecture. We may or may not be doing a cross compile now, so for
    # simplicity we always explicitly set the architecture.
    if (current_cpu == "x64") {
      cflags += [
        "-m64",
        "-march=x86-64",
      ]
      ldflags += [ "-m64" ]
    } else if (current_cpu == "x86") {
      cflags += [ "-m32" ]
      ldflags += [ "-m32" ]
      if (!is_nacl) {
        cflags += [
          "-msse2",
          "-mfpmath=sse",
          "-mmmx",
        ]
      }
    } else if (current_cpu == "arm") {
      if (is_clang && !is_android && !is_ohos && !is_nacl) {
        cflags += [ "--target=arm-linux-gnueabihf" ]
        ldflags += [ "--target=arm-linux-gnueabihf" ]
      }
      if (!is_nacl) {
        cflags += [
          "-march=$arm_arch",
          "-mfloat-abi=$arm_float_abi",
        ]
      }
      if (arm_tune != "") {
        cflags += [ "-mtune=$arm_tune" ]
      }
    } else if (current_cpu == "arm64") {
      if (is_clang && !is_android && !is_ohos && !is_nacl) {
        cflags += [ "--target=aarch64-linux-gnu" ]
        ldflags += [ "--target=aarch64-linux-gnu" ]
      }
      if (is_clang && (is_android || is_ohos)) {
        ldflags += [ "-Wl,--hash-style=gnu" ]
      }
      if (!is_android) {
        cflags += [
          "-march=$arm_arch",
          "-mfloat-abi=$arm_float_abi",
          "-mfpu=$arm_fpu",
        ]
        if (is_ohos && is_clang && target_cpu == "arm64" && enhanced_opt &&
            enable_enhanced_opt && armv8_1_lse_tuning_optimization) {
          cflags += [ "-mlse-tuned" ]
        }
      }
      if (is_linux) {
        cflags += [ "-Wno-error=unused-command-line-argument" ]
      }
      ldflags += [ "-march=$arm_arch" ]
      if (is_ohos && is_clang && target_cpu == "arm64" && enhanced_opt &&
          enable_enhanced_opt && armv8_1_lse_tuning_optimization) {
        ldflags += [ "-mlse-tuned" ]
      }
      if(is_ohos && is_clang && enhanced_opt && enable_enhanced_opt &&
         build_framework_enable_rcpc) {
        cflags += [ "-march=${arm_arch}+rcpc" ]
        ldflags += [ "-march=${arm_arch}+rcpc" ]
      }
    } else if (current_cpu == "riscv64") {
      if (is_clang && !is_android && !is_ohos && !is_nacl) {
        cflags += [ "--target=riscv64-linux-gnu" ]
        ldflags += [ "--target=riscv64-linux-gnu" ]
      }
      if (is_clang && (is_android || is_ohos)) {
        ldflags += [ "-Wl,--hash-style=gnu" ]
      }
      if (!is_android) {
        cflags += [ "-march=rv64imafdc" ]
      }
      ldflags += [ "-march=rv64imafdc" ]
    } else if (current_cpu == "mipsel" && musl_is_legacy) {
      cflags += [ "-mnan=legacy" ]
    }
  }

  asmflags = cflags
  if (current_cpu == "arm64") {
    asmflags += [ "-march=armv8.2-a+dotprod+fp16" ]
  }
}

# This provides options to tweak code generation that are necessary
# for particular Chromium code or for working around particular
# compiler bugs (or the combination of the two).
config("compiler_codegen") {
  configs = []
  cflags = []

  if (is_nacl) {
    configs += [ "//build/config/nacl:compiler_codegen" ]
  } else if (is_posix && !is_mac) {
    if (current_cpu == "x86") {
      if (is_clang) {
        cflags += [ "-momit-leaf-frame-pointer" ]
      }
    } else if (current_cpu == "arm") {
      if ((is_ohos || is_android) && !is_clang) {
        # Clang doesn't support these flags.
        cflags += [
          "-fno-tree-sra",
          "-fno-caller-saves",
        ]
      }
    }
  }

  asmflags = cflags
}

config("compiler_arm_fpu") {
  if (current_cpu == "arm" && !is_nacl) {
    cflags = [ "-mfpu=$arm_fpu" ]
    asmflags = cflags
  }
}

config("compiler_arm_thumb") {
  if (current_cpu == "arm" && arm_use_thumb && is_posix &&
      !(is_mac || is_nacl)) {
    cflags = [ "-mthumb" ]
    if ((is_ohos || is_android) && !is_clang) {
      # Clang doesn't support this option.
      cflags += [ "-mthumb-interwork" ]
    }
  }
}

# runtime_library -------------------------------------------------------------
#
# Sets the runtime library and associated options.
#
# How do you determine what should go in here vs. "compiler" above? Consider if
# a target might choose to use a different runtime library (ignore for a moment
# if this is possible or reasonable on your system). If such a target would want
# to change or remove your option, put it in the runtime_library config. If a
# target wants the option regardless, put it in the compiler config.

config("runtime_library") {
  defines = []
  configs = []

  # The order of this config is important: it must appear before
  # ohos:runtime_library.
  if (is_posix) {
    configs += [ "//build/config/posix:runtime_library" ]
  }

  # System-specific flags. If your compiler flags apply to one of the
  # categories here, add it to the associated file to keep this shared config
  # smaller.
  if (is_win) {
    configs += [ "//build/config/win:runtime_library" ]
  } else if (is_linux) {
    configs += [ "//build/config/linux:runtime_library" ]
  } else if (is_mac) {
    configs += [ "//build/config/mac:runtime_library" ]
  } else if (is_ohos) {
    configs += [ "//build/config/ohos:runtime_library" ]
  } else if (is_android) {
    configs += [ "//build_plugins/config/aosp:runtime_library" ]
  } else if (is_ios) {
    configs += [ "//build_plugins/config/ios:runtime_library" ]
  }

  if (is_component_build) {
    defines += [ "COMPONENT_BUILD" ]
  }
}

# default_warnings ------------------------------------------------------------
#
# Collects all warning flags that are used by default.  This is used as a
# subconfig of both chromium_code and no_chromium_code.  This way these
# flags are guaranteed to appear on the compile command line after -Wall.
config("default_warnings") {
  cflags = []
  cflags_cc = []
  ldflags = []

  if (is_mac && !is_nacl) {
    # When compiling Objective-C, warns if a method is used whose
    # availability is newer than the deployment target.
    cflags += [ "-Wunguarded-availability" ]
  }

  if (!is_clang) {
    cflags += [ "-Wno-deprecated-declarations" ]

    # GCC assumes 'this' is never nullptr and optimizes away code
    # like "if (this == nullptr) ...": [1].  However, some Chromium
    # code relies on these types of null pointer checks [2], so
    # disable this optimization.
    # [1] https://gcc.gnu.org/gcc-6/porting_to.html#this-cannot-be-null
    # [2] https://crbug.com/784492#c13
    cflags += [ "-fno-delete-null-pointer-checks" ]
  }

  # Common Clang and GCC warning setup.
  if (!is_win || is_clang) {
    cflags += [
      # Disables.
      "-Wno-missing-field-initializers",  # "struct foo f = {0};"
      "-Wno-unused-parameter",  # Unused function parameters.
    ]
  }

  if (is_mingw) {
    cflags += [
      "-Wno-error=c99-designator",
      "-Wno-error=implicit-fallthrough",
      "-Wno-error=reorder-init-list",
      "-Wno-error=range-loop-construct",
      "-Wno-error=deprecated-copy",
      "-Wno-error=implicit-int-float-conversion",
      "-Wno-error=inconsistent-dllimport",
      "-Wno-error=unknown-warning-option",
      "-Wno-error=sign-compare",
    ]
  }

  if (is_clang) {
    cflags += [
      # This warns on using ints as initializers for floats in
      # initializer lists (e.g. |int a = f(); CGSize s = { a, a };|),
      # which happens in several places in chrome code. Not sure if
      # this is worth fixing.
      "-Wno-c++11-narrowing",
      "-Wno-unneeded-internal-declaration",
    ]
    if (use_musl || is_host_product) {
      cflags += [
        "-Wno-error=c99-designator",
        "-Wno-error=anon-enum-enum-conversion",
        "-Wno-error=sizeof-array-div",
        "-Wno-error=implicit-fallthrough",
        "-Wno-error=reorder-init-list",
        "-Wno-error=range-loop-construct",
        "-Wno-error=deprecated-copy",
        "-Wno-error=implicit-int-float-conversion",
        "-Wno-error=inconsistent-dllimport",
        "-Wno-error=unknown-warning-option",
        "-Wno-error=sign-compare",
        "-Wno-error=int-in-bool-context",
        "-Wno-error=return-stack-address",
        "-Wno-error=dangling-gsl",
        "-Wno-unused-but-set-variable",
        "-Wno-deprecated-declarations",
        "-Wno-unused-but-set-parameter",
        "-Wno-null-pointer-subtraction",
        "-Wno-unqualified-std-cast-call",
      ]
    }

    # use_xcode_clang only refers to the iOS toolchain, host binaries use
    # chromium's clang always.
    if (!is_nacl) {
      if (current_toolchain == host_toolchain || !use_xcode_clang ||
          xcode_version_int >= 930) {
        cflags += [
          "-Wno-user-defined-warnings",
          "-Wno-unused-lambda-capture",
        ]
      }
      if (current_toolchain == host_toolchain || !use_xcode_clang ||
          xcode_version_int >= 1000) {
        cflags += [ "-Wno-null-pointer-arithmetic" ]
      }
      if (current_toolchain == host_toolchain || !use_xcode_clang) {
        # Flags NaCl (Clang 3.7) and Xcode 9.2 (Clang clang-900.0.39.2) do not
        # recognize.
        cflags += [ "-Wno-enum-compare-switch" ]
      }
    }
    if (current_cpu == "riscv64") {
      cflags += [
        "-Wno-gnu-folding-constant",
        "-Wno-error=non-c-typedef-for-linkage",
        "-Wno-extern-c-compat",
      ]
    }
  }
}

# chromium_code ---------------------------------------------------------------
#
# Toggles between higher and lower warnings for code that is (or isn't)
# part of Chromium.

config("chromium_code") {
  if (is_win) {
    cflags = [ "/W4" ]  # Warning level 4.

    if (is_clang) {
      # Opt in to additional [[nodiscard]] on standard library methods.
      defines = [ "_HAS_NODISCARD" ]
    }
  } else {
    cflags = [ "-Wall" ]
    if (treat_warnings_as_errors && !is_arkui_x) {
      cflags += [ "-Werror" ]

      # The compiler driver can sometimes (rarely) emit warnings before calling
      # the actual linker.  Make sure these warnings are treated as errors as
      # well.
      ldflags = [ "-Werror" ]
    }
    if (is_clang) {
      # Enable extra warnings for chromium_code when we control the compiler.
      cflags += [ "-Wextra" ]
    }

    # In Chromium code, we define __STDC_foo_MACROS in order to get the
    # C99 macros on Mac and Linux.
    defines = [
      "__STDC_CONSTANT_MACROS",
      "__STDC_FORMAT_MACROS",
    ]

    if (!is_debug && !using_sanitizer &&
        (!is_linux || !is_clang || is_official_build)) {
      # _FORTIFY_SOURCE isn't really supported by Clang now, see
      # http://llvm.org/bugs/show_bug.cgi?id=16821.
      # It seems to work fine with Ubuntu 12 headers though, so use it in
      # official builds.
      #
      # Non-chromium code is not guaranteed to compile cleanly with
      # _FORTIFY_SOURCE. Also, fortified build may fail when optimizations are
      # disabled, so only do that for Release build.
      #
      # Need to support fortify ability first in musl libc, so disable the option temporarily
      # defines += [ "_FORTIFY_SOURCE=2" ]
    }

    if (is_mac) {
      cflags_objc = [ "-Wobjc-missing-property-synthesis" ]
      cflags_objcc = [ "-Wobjc-missing-property-synthesis" ]
    }
  }

  if (is_clang) {
    cflags += [
      # Warn on missing break statements at the end of switch cases.
      # For intentional fallthrough, use FALLTHROUGH; from
      # base/compiler_specific.h
      "-Wimplicit-fallthrough",

      # Thread safety analysis. See base/thread_annotations.h and
      # https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
      "-Wthread-safety",
    ]
  }

  configs = [ ":default_warnings" ]
  if (is_arkui_x) {
    configs += [ "//build_plugins/config:arkui_x_warning" ]
  }
}

# rtti ------------------------------------------------------------------------
#
# Allows turning Run-Time Type Identification on or off.

config("rtti") {
  if (is_win) {
    cflags_cc = [ "/GR" ]
  } else {
    cflags_cc = [ "-frtti" ]
  }
}

config("no_rtti") {
  # Some sanitizer configs may require RTTI to be left enabled globally
  if (!use_rtti) {
    if (is_win) {
      cflags_cc = [ "/GR-" ]
    } else {
      cflags_cc = [ "-fno-rtti" ]
      cflags_objcc = cflags_cc
    }
  }
}

# export_dynamic ---------------------------------------------------------------
#
# Ensures all exported symbols are added to the dynamic symbol table.  This is
# necessary to expose Chrome's custom operator new() and operator delete() (and
# other memory-related symbols) to libraries.  Otherwise, they might
# (de)allocate memory on a different heap, which would spell trouble if pointers
# to heap-allocated memory are passed over shared library boundaries.
config("export_dynamic") {
  if (is_desktop_linux || export_libcxxabi_from_executables) {
    ldflags = [ "-rdynamic" ]
  }
}

# thin_archive -----------------------------------------------------------------
#
# Enables thin archives on posix.  Regular archives directly include the object
# files used to generate it.  Thin archives merely reference the object files.
# This makes building them faster since it requires less disk IO, but is
# inappropriate if you wish to redistribute your static library.
# This config is added to the global config, so thin archives should already be
# enabled.  If you want to make a distributable static library, you need to do 2
# things:
# 1. Set complete_static_lib so that all dependencies of the library make it
#    into the library. See `gn help complete_static_lib` for details.
# 2. Remove the thin_archive config, so that the .a file actually contains all
#    .o files, instead of just references to .o files in the build directory
config("thin_archive") {
  # Mac and iOS use the mac-specific "libtool" command, not ar, which doesn't
  # have a "thin archive" mode (it does accept -T, but it means truncating
  # archive names to 16 characters, which is not what we want).
  if (is_posix && !is_nacl && !is_mac) {
    arflags = [ "-T" ]
  }
}

# exceptions -------------------------------------------------------------------
#
# Allows turning Exceptions on or off.

config("exceptions") {
  if (is_win) {
    # Enables exceptions in the STL.
    if (!use_custom_libcxx) {
      defines = [ "_HAS_EXCEPTIONS=1" ]
    }
    cflags_cc = [ "/EHsc" ]
  } else {
    cflags_cc = [ "-fexceptions" ]
    cflags_objcc = cflags_cc
  }
}

config("no_exceptions") {
  if (is_win) {
    # Disables exceptions in the STL.
    # libc++ uses the __has_feature macro to control whether to use exceptions,
    # so defining this macro is unnecessary. Defining _HAS_EXCEPTIONS to 0 also
    # breaks libc++ because it depends on MSVC headers that only provide certain
    # declarations if _HAS_EXCEPTIONS is 1. Those MSVC headers do not use
    # exceptions, despite being conditional on _HAS_EXCEPTIONS.
    if (!use_custom_libcxx) {
      defines = [ "_HAS_EXCEPTIONS=0" ]
    }
  } else {
    cflags_cc = [ "-fno-exceptions" ]
    cflags_objcc = cflags_cc
  }
}

# Optimization -----------------------------------------------------------------
#
# The BUILDCONFIG file sets the "default_optimization" config on targets by
# default. It will be equivalent to either "optimize" (release) or
# "no_optimize" (debug) optimization configs.
#
# You can override the optimization level on a per-target basis by removing the
# default config and then adding the named one you want:
#
#   configs -= [ "//build/config/compiler:default_optimization" ]
#   configs += [ "//build/config/compiler:optimize_max" ]

# Shared settings for both "optimize" and "optimize_max" configs.
# IMPORTANT: On Windows "/O1" and "/O2" must go before the common flags.
if (is_win) {
  common_optimize_on_cflags = [
    "/Ob2",  # Both explicit and auto inlining.
    "/Oy-",  # Disable omitting frame pointers, must be after /O2.
    "/Zc:inline",  # Remove unreferenced COMDAT (faster links).
  ]
  if (!is_asan) {
    common_optimize_on_cflags += [
      # Put data in separate COMDATs. This allows the linker
      # to put bit-identical constants at the same address even if
      # they're unrelated constants, which saves binary size.
      # This optimization can't be used when ASan is enabled because
      # it is not compatible with the ASan ODR checker.
      "/Gw",
    ]
  }
  common_optimize_on_ldflags = []

  # /OPT:ICF is not desirable in Debug builds, since code-folding can result in
  # misleading symbols in stack traces. It is also incompatible with
  # incremental linking, which we enable for both Debug and component builds.
  if (!is_debug && !is_component_build) {
    common_optimize_on_ldflags += [ "/OPT:ICF" ]  # Redundant COMDAT folding.
  }

  if (is_official_build) {
    common_optimize_on_ldflags += [ "/OPT:REF" ]  # Remove unreferenced data.

    if (!use_lld && !is_clang) {
      common_optimize_on_ldflags += [
        # Set the number of LTCG code-gen threads to eight. The default is four.
        # This gives a 5-10% link speedup.
        "/cgthreads:8",
      ]
      if (use_incremental_wpo) {
        # Incremental Link-time code generation.
        common_optimize_on_ldflags += [ "/LTCG:INCREMENTAL" ]
      } else {
        common_optimize_on_ldflags += [ "/LTCG" ]  # Link-time code generation.
      }
    }
  }
} else {
  common_optimize_on_cflags = []
  common_optimize_on_ldflags = []

  if (is_ohos) {
    common_optimize_on_ldflags += [
      # Warn in case of text relocations.
      "-Wl,--warn-shared-textrel",
    ]
  }

  if (is_mac || is_ios) {
    if (symbol_level == 2) {
      # Mac dead code stripping requires symbols.
      common_optimize_on_ldflags += [ "-Wl,-dead_strip" ]
    }
  } else if (current_os != "aix") {
    # Non-Mac Posix flags.
    # Aix does not support these.

    common_optimize_on_cflags += [
      # Don't emit the GCC version ident directives, they just end up in the
      # .comment section taking up binary size.
      "-fno-ident",

      # Put data and code in their own sections, so that unused symbols
      # can be removed at link time with --gc-sections.
      "-fdata-sections",
      "-ffunction-sections",
    ]

    common_optimize_on_ldflags += [
      # Specifically tell the linker to perform optimizations.
      # See http://lwn.net/Articles/192624/ .
      # -O2 enables string tail merge optimization in gold and lld.
      "-Wl,-O2",
    ]
    if (!is_mingw) {
      common_optimize_on_ldflags += [ "-Wl,--gc-sections" ]
    }
  }
}

config("default_stack_frames") {
  if (is_posix) {
    if (enable_frame_pointers) {
      cflags = [ "-fno-omit-frame-pointer" ]
    } else {
      cflags = [ "-fomit-frame-pointer" ]
    }
  }
  # On Windows, the flag to enable framepointers "/Oy-" must always come after
  # the optimization flag [e.g. "/O2"]. The optimization flag is set by one of
  # the "optimize" configs, see rest of this file. The ordering that cflags are
  # applied is well-defined by the GN spec, and there is no way to ensure that
  # cflags set by "default_stack_frames" is applied after those set by an
  # "optimize" config. Similarly, there is no way to propagate state from this
  # config into the "optimize" config. We always apply the "/Oy-" config in the
  # definition for common_optimize_on_cflags definition, even though this may
  # not be correct.
}

# Default "optimization on" config.
config("optimize") {
  if (optimize_for_size && !is_nacl) {
    # Favor size over speed.
    if (is_clang) {
      cflags = [ build_framework_compiler_optimize_level ] +
               common_optimize_on_cflags
    } else {
      cflags = [ "-Os" ] + common_optimize_on_cflags
    }
  } else {
    cflags = [ "-O2" ] + common_optimize_on_cflags
  }
  ldflags = common_optimize_on_ldflags
}

# Turn off optimizations.
config("no_optimize") {
  if (is_win) {
    cflags = [
      "/Od",  # Disable optimization.
      "/Ob0",  # Disable all inlining (on by default).
      "/GF",  # Enable string pooling (off by default).
    ]
  } else if ((is_ohos || is_android) && !ohos_full_debug) {
    # On ohos we kind of optimize some things that don't affect debugging
    # much even when optimization is disabled to get the binary size down.
    if (is_clang) {
      cflags = [ "-Oz" ] + common_optimize_on_cflags
      ldflags = common_optimize_on_ldflags
    } else {
      cflags = [ "-Os" ] + common_optimize_on_cflags
      ldflags = common_optimize_on_ldflags
    }
  } else {
    # On ohos_full_debug mode, we close all optimization
    cflags = [ "-O0" ]
    ldflags = []
  }
}

# This config can be used to override the default settings for per-component
# and whole-program optimization, optimizing the particular target for speed
# instead of code size. This config is exactly the same as "optimize_max"
# except that we use -O3 instead of -O2 on non-win, non-IRT platforms.
config("optimize_speed") {
  if (is_nacl && is_nacl_irt) {
    # The NaCl IRT is a special case and always wants its own config.
    # Various components do:
    #   if (!is_debug) {
    #     configs -= [ "//build/config/compiler:default_optimization" ]
    #     configs += [ "//build/config/compiler:optimize_max" ]
    #   }
    # So this config has to have the selection logic just like
    # "default_optimization", below.
    configs = [ "//build/config/nacl:irt_optimize" ]
  } else {
    ldflags = common_optimize_on_ldflags
    if (is_win) {
      # Favor speed over size, /O2 must be before the common flags. The GYP
      # build also specifies /Ot, /Oi, and /GF, but these are implied by /O2.
      cflags = [ "/O2" ] + common_optimize_on_cflags

      if (is_official_build && !is_clang) {
        cflags += [
          "/GL",  # Whole program optimization.

          # Disable Warning 4702 ("Unreachable code") for the WPO/PGO builds.
          # Probably anything that this would catch that wouldn't be caught in a
          # normal build isn't going to actually be a bug, so the incremental
          # value of C4702 for PGO builds is likely very small.
          "/wd4702",
        ]
      }
    } else if (optimize_for_fuzzing) {
      cflags = [ "-O0" ] + common_optimize_on_cflags
    } else {
      cflags = [ "-O3" ] + common_optimize_on_cflags
    }
  }
}

config("optimize_fuzzing") {
  cflags = [ "-O0" ] + common_optimize_on_cflags
  ldflags = common_optimize_on_ldflags
  visibility = [ ":default_optimization" ]
}

# The default optimization applied to all targets. This will be equivalent to
# either "optimize" or "no_optimize", depending on the build flags.
config("default_optimization") {
  if (is_nacl && is_nacl_irt) {
    # The NaCl IRT is a special case and always wants its own config.
    # It gets optimized the same way regardless of the type of build.
    configs = [ "//build/config/nacl:irt_optimize" ]
  } else if (is_debug) {
    configs = [ ":no_optimize" ]
  } else if (optimize_for_fuzzing) {
    assert(!is_win, "Fuzzing optimize level not supported on Windows")

    # Coverage build is quite slow. Using "optimize_for_fuzzing" makes it even
    # slower as it uses "-O1" instead of "-O3". Prevent that from happening.
    assert(!use_clang_coverage,
           "optimize_for_fuzzing=true should not be used with " +
               "use_clang_coverage=true.")
    configs = [ ":optimize_fuzzing" ]
  } else {
    configs = [ ":optimize" ]
  }
}

_clang_sample_profile = ""
if (is_clang && current_toolchain == default_toolchain) {
  if (clang_sample_profile_path != "") {
    _clang_sample_profile = clang_sample_profile_path
  } else if (clang_use_default_sample_profile) {
    assert(build_with_chromium,
           "Our default profiles currently only apply to Chromium")
    assert(is_ohos || is_android || is_desktop_linux,
           "The current platform has no default profile")
    _clang_sample_profile = ""
  }
}

# Clang offers a way to assert that AFDO profiles are accurate, which causes it
# to optimize functions not represented in a profile more aggressively for size.
# This config can be toggled in cases where shaving off binary size hurts
# performance too much.
config("afdo_optimize_size") {
  if (_clang_sample_profile != "" && sample_profile_is_accurate) {
    cflags = [ "-fprofile-sample-accurate" ]
  }
}

# GCC and clang support a form of profile-guided optimization called AFDO.
# There are some targeted places that AFDO regresses (and an icky interaction
# between //base/allocator:tcmalloc and AFDO on GCC), so we provide a separate
# config to allow AFDO to be disabled per-target.
config("afdo") {
  if (is_clang) {
    if (_clang_sample_profile != "") {
      rebased_clang_sample_profile =
          rebase_path(_clang_sample_profile, root_build_dir)
      cflags = [ "-fprofile-sample-use=${rebased_clang_sample_profile}" ]
      inputs = [ _clang_sample_profile ]
    }
  } else if (auto_profile_path != "" &&
             current_toolchain == default_toolchain) {
    cflags = [ "-fauto-profile=${auto_profile_path}" ]
    inputs = [ auto_profile_path ]
  }
}

# Symbols ----------------------------------------------------------------------

# The BUILDCONFIG file sets the "default_symbols" config on targets by
# default. It will be equivalent to one the three specific symbol levels.
#
# You can override the symbol level on a per-target basis by removing the
# default config and then adding the named one you want:
#
#   configs -= [ "//build/config/compiler:default_symbols" ]
#   configs += [ "//build/config/compiler:symbols" ]

# A helper config that all configs passing /DEBUG to the linker should
# include as sub-config.
config("win_pdbaltpath") {
  visibility = [
    ":minimal_symbols",
    ":symbols",
  ]

  # /DEBUG causes the linker to generate a pdb file, and to write the absolute
  # path to it in the executable file it generates.  This flag turns that
  # absolute path into just the basename of the pdb file, which helps with
  # build reproducibility. Debuggers look for pdb files next to executables,
  # so there's no downside to always using this.
  ldflags = [ "/pdbaltpath:%_PDB%" ]
}

# Full symbols.
config("symbols") {
  if (is_win) {
    if (is_clang) {
      # Note that with VC++ this requires is_win_fastlink, enforced elsewhere.
      cflags = [ "/Z7" ]  # Debug information in the .obj files.
    } else {
      cflags = [ "/Zi" ]  # Produce PDB file, no edit and continue.
    }

    if (is_win_fastlink && !use_lld) {
      # Tell VS 2015+ to create a PDB that references debug
      # information in .obj and .lib files instead of copying
      # it all. This flag is incompatible with /PROFILE
      ldflags = [ "/DEBUG:FASTLINK" ]
    } else if (is_clang && use_lld && use_ghash) {
      cflags += [
        "-mllvm",
        "-emit-codeview-ghash-section",
      ]
      ldflags = [ "/DEBUG:GHASH" ]
    } else {
      ldflags = [ "/DEBUG" ]
    }

    # All configs using /DEBUG should include this:
    configs = [ ":win_pdbaltpath" ]

    if (is_clang) {
      # /DEBUG:FASTLINK requires every object file to have standalone debug
      # information.
      if (is_win_fastlink && !use_lld) {
        cflags += [ "-fstandalone-debug" ]
      } else {
        cflags += [ "-fno-standalone-debug" ]
      }
    }
  } else {
    if (is_mac) {
      cflags = [ "-gdwarf-2" ]
      if (is_mac && enable_dsyms) {
        # If generating dSYMs, specify -fno-standalone-debug. This was
        # originally specified for https://crbug.com/479841 because dsymutil
        # could not handle a 4GB dSYM file. But dsymutil from Xcodes prior to
        # version 7 also produces debug data that is incompatible with Breakpad
        # dump_syms, so this is still required (https://crbug.com/622406).
        cflags += [ "-fno-standalone-debug" ]
      }
    } else {
      cflags = []
      if (!use_debug_fission && current_cpu == "arm") {
        # dump_syms has issues with dwarf4 on arm, https://crbug.com/744956
        #
        # debug fission needs DWARF DIEs to be emitted at version 4.
        # Chrome OS emits Debug Frame in DWARF1 to make breakpad happy. [1]
        # Unless ohos needs debug fission, DWARF3 is the simplest solution.
        #
        # [1] crrev.com/a81d5ade0b043208e06ad71a38bcf9c348a1a52f
        cflags += [ "-gdwarf-3" ]
      }
      if (!ohos_full_debug) {
        cflags += [ "-g2" ]
      } else {
        # Set -g3 symbol level when ohos_full_debug is true
        cflags += [ "-g3" ]
      }
    }
    if (use_debug_fission && !is_nacl && !(is_ohos || is_android)) {
      # NOTE: Some Chrome OS builds globally set |use_debug_fission| to true,
      # but they also build some targets against ohos toolchains which aren't
      # compatible with it.
      cflags += [ "-gsplit-dwarf" ]
    }
    asmflags = cflags
    ldflags = []

    if (!is_mac && !is_nacl && current_cpu != "x86" && (use_gold || use_lld)) {
      if (is_clang) {
        # This flag enables the GNU-format pubnames and pubtypes sections,
        # which lld needs in order to generate a correct GDB index.
        cflags += [ "-ggnu-pubnames" ]
      }
      ldflags += [ "-Wl,--gdb-index" ]
    }
  }
}

# Minimal symbols.
# This config guarantees to hold symbol for stack trace which are shown to user
# when crash happens in unittests running on buildbot.
config("minimal_symbols") {
  if (is_win) {
    # Linker symbols for backtraces only.
    cflags = []
    ldflags = [ "/DEBUG" ]

    # All configs using /DEBUG should include this:
    configs = [ ":win_pdbaltpath" ]

    # For win/asan, get stack traces with full line numbers.
    # AddressSanitizerTests.TestAddressSanitizer needs this, and since
    # win/asan isn't a default cq bot the build time hit is ok.
    if (is_clang && using_sanitizer) {
      # -gline-tables-only is the same as -g1, but clang-cl only exposes the
      # former.
      cflags += [ "-gline-tables-only" ]
    }
  } else {
    cflags = []
    if (current_cpu == "arm") {
      # dump_syms has issues with dwarf4 on arm, https://crbug.com/744956
      cflags += [ "-gdwarf-3" ]
    }
    cflags += [ "-g1" ]
    ldflags = []
    if ((is_ohos || is_android) && is_clang) {
      # ohos defaults to symbol_level=1 builds in production builds
      # (https://crbug.com/648948), but clang, unlike gcc, doesn't emit
      # DW_AT_linkage_name in -g1 builds. -fdebug-info-for-profiling enables
      # that (and a bunch of other things we don't need), so that we get
      # qualified names in stacks.
      cflags += [ "-fdebug-info-for-profiling" ]
    }

    # Note: -gsplit-dwarf implicitly turns on -g2 with clang, so don't pass it.
    asmflags = cflags
  }
}

# No symbols.
config("no_symbols") {
  if (!is_win) {
    cflags = [ "-g0" ]
    asmflags = cflags
  }
}

# Default symbols.
config("default_symbols") {
  if (symbol_level == 0) {
    configs = [ ":no_symbols" ]
  } else if (symbol_level == 1) {
    configs = [ ":minimal_symbols" ]
  } else if (symbol_level == 2) {
    configs = [ ":symbols" ]
  } else {
    assert(false)
  }

  # This config is removed by base unittests app.
  if ((is_ohos || is_android) && is_clang && strip_debug_info) {
    configs += [ ":strip_debug" ]
  }
}

config("strip_debug") {
  if (!defined(ldflags)) {
    ldflags = []
  }
  ldflags += [ "-Wl,--strip-debug" ]
}

config("no_common") {
  if (is_clang) {
    cflags = [ "-fno-common" ]
    asmflags = cflags
  }
}