• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (c) 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import("//build/config/c++/c++.gni")
6import("//build/config/clang/clang.gni")
7import("//build/config/compiler/compiler.gni")
8import("//build/config/coverage/coverage.gni")
9import("//build/config/sanitizers/sanitizers.gni")
10import("//build/toolchain/cc_wrapper.gni")
11import("//build/toolchain/toolchain.gni")
12
13import("//build/misc/overrides/build.gni")
14
15if (current_cpu == "arm" || current_cpu == "arm64") {
16  import("//build/config/arm.gni")
17}
18if (is_android) {
19  import("//build_plugins/config/aosp/config.gni")
20}
21if (is_ohos) {
22  import("//build/config/ohos/config.gni")
23}
24if (is_mac) {
25  import("//build/config/mac/symbols.gni")
26}
27if (is_mac || is_ios) {
28  import("//build/config/mac/mac_sdk.gni")
29}
30declare_args() {
31  # Default to warnings as errors for default workflow, where we catch
32  # warnings with known toolchains. Allow overriding this e.g. for Chromium
33  # builds on Linux that could use a different version of the compiler.
34  # With GCC, warnings in no-Chromium code are always not treated as errors.
35  treat_warnings_as_errors = true
36
37  # Whether to use the binary binutils checked into third_party/binutils.
38  # These are not multi-arch so cannot be used except on x86 and x86-64 (the
39  # only two architectures that are currently checked in). Turn this off when
40  # you are using a custom toolchain and need to control -B in cflags.
41  linux_use_bundled_binutils =
42      linux_use_bundled_binutils_override && is_linux &&
43      (current_cpu == "x64" || current_cpu == "x86")
44  binutils_path = rebase_path("//third_party/binutils/Linux_x64/Release/bin",
45                              root_build_dir)
46
47  # Compile in such a way as to make it possible for the profiler to unwind full
48  # stack frames. Setting this flag has a large effect on the performance of the
49  # generated code than just setting profiling, but gives the profiler more
50  # information to analyze.
51  # Requires profiling to be set to true.
52  enable_full_stack_frames_for_profiling = false
53
54  # When we are going to use gold we need to find it.
55  # This is initialized below, after use_gold might have been overridden.
56  gold_path = false
57
58  if (is_win) {
59    # Whether the VS xtree header has been patched to disable warning 4702. If
60    # it has, then we don't need to disable 4702 (unreachable code warning).
61    # The patch is preapplied to the internal toolchain and hence all bots.
62    msvs_xtree_patched = false
63  }
64
65  # Enable fatal linker warnings. Building Chromium with certain versions
66  # of binutils can cause linker warning.
67  # See: https://bugs.chromium.org/p/chromium/issues/detail?id=457359
68  fatal_linker_warnings = true
69
70  # Build with C++ RTTI enabled. Chromium builds without RTTI by default,
71  # but some sanitizers are known to require it, like CFI diagnostics
72  # and UBsan variants.
73  use_rtti = use_cfi_diag || is_ubsan_vptr || is_ubsan_security
74
75  # AFDO (Automatic Feedback Directed Optimizer) is a form of profile-guided
76  # optimization that GCC supports. It used by ChromeOS in their official
77  # builds. To use it, set auto_profile_path to the path to a file containing
78  # the needed gcov profiling data.
79  auto_profile_path = ""
80
81  # Optimize symbol files for maximizing goma cache hit rate. This is on by
82  # default when goma is enabled on Linux and Windows.
83  # But setting this to true may make it harder to debug binaries on Linux.
84  # See below reference for detail.
85  strip_absolute_paths_from_debug_symbols = false
86
87  # Allow projects that wish to stay on C++11 to override Chromium's default.
88  use_cxx11 = false
89
90  # Path to an AFDO profile to use while building with clang, if any. Empty
91  # implies none.
92  clang_sample_profile_path = ""
93
94  # Some configurations have default sample profiles. If this is true and
95  # clang_sample_profile_path is empty, we'll fall back to the default.
96  #
97  # We currently only have default profiles for Chromium in-tree, so we disable
98  # this by default for all downstream projects, since these profiles are likely
99  # nonsensical for said projects.
100  clang_use_default_sample_profile =
101      is_official_build && (is_ohos || is_android || is_desktop_linux)
102
103  # Turn this on to have the compiler output extra timing information.
104  compiler_timing = false
105
106  # Set to true to pass --no-rosegment to lld. This is a workaround
107  # for a KI issue in Valgrind,
108  # https://bugs.kde.org/show_bug.cgi?id=384727
109  ro_segment_workaround_for_valgrind = false
110
111  # Turn this on to use ghash feature of lld for faster debug link on Windows.
112  # http://blog.llvm.org/2018/01/improving-link-time-on-windows-with.html
113  use_ghash = false
114
115  # Whether to enable ThinLTO optimizations. Turning ThinLTO optimizations on
116  # can substantially increase link time and binary size, but they generally
117  # also make binaries a fair bit faster.
118  thin_lto_enable_optimizations = is_chromeos
119
120  # By default only the binaries in official builds get build IDs.
121  force_local_build_id = true
122}
123
124declare_args() {
125  use_cxx11_on_ohos = use_cxx11
126}
127
128declare_args() {
129  # Set to true to use icf, Identical Code Folding.
130  #
131  # icf=all is broken in older golds, see
132  # https://sourceware.org/bugzilla/show_bug.cgi?id=17704
133  # See also https://crbug.com/663886
134  # `linux_use_bundled_binutils` is to avoid breaking Linux destroys which may
135  # still have a buggy gold.
136  # chromeos binutils has been patched with the fix, so always use icf there.
137  # The bug only affects x86 and x64, so we can still use ICF when targeting
138  # other architectures.
139  #
140  # lld doesn't have the bug.
141  use_icf = is_posix && !using_sanitizer && !use_clang_coverage &&
142            !((is_ohos || is_android) && use_order_profiling) &&
143            (use_lld ||
144             (use_gold &&
145              ((!(is_ohos || is_android) && linux_use_bundled_binutils) ||
146               is_chromeos || !(current_cpu == "x86" || current_cpu == "x64"))))
147}
148
149# Apply the default logic for these values if they were not set explicitly.
150if (gold_path == false) {
151  if (use_gold) {
152    gold_path = rebase_path("//third_party/binutils/Linux_x64/Release/bin",
153                            root_build_dir)
154  } else {
155    gold_path = ""
156  }
157}
158
159if (use_debug_fission == "default") {
160  use_debug_fission = is_debug && !(is_ohos || is_android) && !is_win &&
161                      (use_gold || use_lld) && cc_wrapper == ""
162}
163
164# default_include_dirs ---------------------------------------------------------
165#
166# This is a separate config so that third_party code (which would not use the
167# source root and might have conflicting versions of some headers) can remove
168# this and specify their own include paths.
169config("default_include_dirs") {
170  include_dirs = [
171    "${root_out_dir}/override/third_party",
172    "//",
173    root_gen_dir,
174  ]
175}
176
177# compiler ---------------------------------------------------------------------
178#
179# Base compiler configuration.
180#
181# See also "runtime_library" below for related stuff and a discussion about
182# where stuff should go. Put warning related stuff in the "warnings" config.
183
184config("compiler") {
185  asmflags = []
186  cflags = []
187  cflags_c = []
188  cflags_cc = []
189  cflags_objc = []
190  cflags_objcc = []
191  ldflags = []
192  defines = []
193  configs = []
194  inputs = []
195
196  # System-specific flags. If your compiler flags apply to one of the
197  # categories here, add it to the associated file to keep this shared config
198  # smaller.
199  if (is_win) {
200    configs += [ "//build/config/win:compiler" ]
201  } else if (is_ohos) {
202    configs += [ "//build/config/ohos:compiler" ]
203  } else if (is_linux) {
204    configs += [ "//build/config/linux:compiler" ]
205  } else if (is_nacl) {
206    configs += [ "//build/config/nacl:compiler" ]
207  } else if (is_mac) {
208    configs += [ "//build/config/mac:compiler" ]
209  } else if (current_os == "aix") {
210    configs += [ "//build/config/aix:compiler" ]
211  } else if (is_mingw) {
212    configs += [ "//build/config/mingw:compiler" ]
213  } else if (is_android) {
214    configs += [ "//build_plugins/config/aosp:compiler" ]
215  } else if (is_ios) {
216    configs += [ "//build_plugins/config/ios:compiler" ]
217  }
218
219  configs += [
220    # See the definitions below.
221    ":compiler_cpu_abi",
222    ":compiler_codegen",
223  ]
224
225  if (is_ohos && is_standard_system && is_clang &&
226      (target_cpu == "arm" || target_cpu == "arm64" ||
227       target_cpu == "riscv64")) {
228    ldflags += [ "-Wl,--pack-dyn-relocs=android+relr" ]
229  }
230
231  # In general, Windows is totally different, but all the other builds share
232  # some common GCC configuration.
233  if (!is_win) {
234    # Common POSIX compiler flags setup.
235    # --------------------------------
236    cflags += [ "-fno-strict-aliasing" ]  # See http://crbug.com/32204
237
238    configs += [ "//build/config/security:stack_protector_config" ]
239
240    # Linker warnings.
241    if (fatal_linker_warnings && !(is_chromeos && current_cpu == "arm") &&
242        !(is_ohos && use_order_profiling) && !is_mac && current_os != "aix" &&
243        !is_mingw && !is_ios) {
244      ldflags += [ "-Wl,--fatal-warnings" ]
245    }
246  } else {
247    cflags += [
248      # Assume UTF-8 by default to avoid code page dependencies.
249      "/utf-8",
250    ]
251    if (is_clang) {
252      # Don't look for includes in %INCLUDE%.
253      cflags += [ "/X" ]
254    }
255  }
256
257  # Eliminate build metadata (__DATE__, __TIME__ and __TIMESTAMP__) for
258  # deterministic build.  See https://crbug.com/314403
259  if (!is_official_build) {
260    if (is_win && !is_clang) {
261      cflags += [
262        "/wd4117",  # Trying to define or undefine a predefined macro.
263        "/D__DATE__=",
264        "/D__TIME__=",
265        "/D__TIMESTAMP__=",
266      ]
267    } else {
268      cflags += [
269        "-Wno-builtin-macro-redefined",
270        "-D__DATE__=",
271        "-D__TIME__=",
272        "-D__TIMESTAMP__=",
273      ]
274    }
275  }
276
277  if (is_posix && !is_mac) {
278    if (enable_profiling) {
279      if (!is_debug) {
280        cflags += [ "-g" ]
281
282        if (enable_full_stack_frames_for_profiling) {
283          cflags += [
284            "-fno-inline",
285            "-fno-optimize-sibling-calls",
286          ]
287        }
288      }
289    }
290
291    if (!is_mingw && !is_ios && (is_official_build || force_local_build_id)) {
292      # Explicitly pass --build-id to ld. Compilers used to always pass this
293      # implicitly but don't any more (in particular clang when built without
294      # ENABLE_LINKER_BUILD_ID=ON). The crash infrastructure does need a build
295      # id, so explicitly enable it in official builds. It's not needed in
296      # unofficial builds and computing it does slow down the link, so go with
297      # faster links in unofficial builds.
298      ldflags += [ "-Wl,--build-id=md5" ]
299    }
300
301    if (!is_ohos && !is_ohos) {
302      defines += [
303        "_FILE_OFFSET_BITS=64",
304        "_LARGEFILE_SOURCE",
305        "_LARGEFILE64_SOURCE",
306      ]
307    }
308
309    if (!is_nacl && !is_llvm_build) {
310      cflags += [ "-funwind-tables" ]
311    }
312  }
313
314  if (is_linux || is_android || is_ohos) {
315    if (use_pic) {
316      cflags += [ "-fPIC" ]
317      ldflags += [ "-fPIC" ]
318    }
319
320    if (!is_clang) {
321      # Use pipes for communicating between sub-processes. Faster.
322      # (This flag doesn't do anything with Clang.)
323      cflags += [ "-pipe" ]
324    }
325
326    ldflags += [
327      "-Wl,-z,noexecstack",
328      "-Wl,-z,now",
329      "-Wl,-z,relro",
330    ]
331
332    # Compiler instrumentation can introduce dependencies in DSOs to symbols in
333    # the executable they are loaded into, so they are unresolved at link-time.
334    if (is_ohos || (!using_sanitizer && !is_safestack)) {
335      ldflags += [
336        "-Wl,-z,defs",
337        "-Wl,--as-needed",
338      ]
339    }
340
341    # Change default thread stack size to 2MB for asan.
342    if (is_ohos && using_sanitizer) {
343      ldflags += [ "-Wl,-z,stack-size=2097152" ]
344    }
345  }
346
347  # Linux-specific compiler flags setup.
348  # ------------------------------------
349  if (is_android && is_clang) {
350    _rebased_aosp_toolchain_root =
351        rebase_path(aosp_toolchain_root, root_build_dir)
352
353    # Let clang find the linker in the NDK.
354    ldflags += [ "--gcc-toolchain=$_rebased_aosp_toolchain_root" ]
355  }
356
357  if ((is_posix && use_lld) || (target_os == "chromeos" && is_android) ||
358      (is_ohos && use_lld)) {
359    # NOTE: Some Chrome OS builds globally disable LLD, but they also build some
360    # targets against ohos toolchains which should use LLD. Therefore we
361    # explicitly select LLD in these cases.
362    ldflags += [ "-fuse-ld=lld" ]
363    if (current_cpu == "arm64") {
364      # Reduce the page size from 65536 in order to reduce binary size slightly
365      # by shrinking the alignment gap between segments. This also causes all
366      # segments to be mapped adjacently, which breakpad relies on.
367      ldflags += [ "-Wl,-z,max-page-size=4096" ]
368    }
369  } else if (use_gold) {
370    ldflags += [ "-fuse-ld=gold" ]
371    if (!(is_ohos || is_android)) {
372      # On ohos, this isn't needed.  gcc in the NDK knows to look next to
373      # it with -fuse-ld=gold, and clang gets a --gcc-toolchain flag passed
374      # above.
375      ldflags += [ "-B$gold_path" ]
376
377      if (linux_use_bundled_binutils) {
378        ldflags += [
379          # Experimentation found that using four linking threads
380          # saved ~20% of link time.
381          # Only apply this to the target linker, since the host
382          # linker might not be gold, but isn't used much anyway.
383          "-Wl,--threads",
384          "-Wl,--thread-count=4",
385        ]
386      }
387    }
388  } else if (linux_use_bundled_binutils) {
389    # Gold is the default linker for the bundled binutils so we explicitly
390    # enable the bfd linker when use_gold is not set.
391    ldflags += [ "-fuse-ld=bfd" ]
392  }
393
394  if (use_icf) {
395    ldflags += [ "-Wl,--icf=all" ]
396  }
397
398  if (linux_use_bundled_binutils) {
399    cflags += [ "-B$binutils_path" ]
400  }
401
402  if (is_linux) {
403    cflags += [ "-pthread" ]
404    # Do not use the -pthread ldflag here since it becomes a no-op
405    # when using -nodefaultlibs, which would cause an unused argument
406    # error.  "-lpthread" is added in //build/config:default_libs.
407  }
408
409  # Clang-specific compiler flags setup.
410  # ------------------------------------
411  if (is_clang) {
412    cflags += [ "-fcolor-diagnostics" ]
413
414    # Enable -fmerge-all-constants. This used to be the default in clang
415    # for over a decade. It makes clang non-conforming, but is fairly safe
416    # in practice and saves some binary size. We might want to consider
417    # disabling this (https://bugs.llvm.org/show_bug.cgi?id=18538#c13),
418    # but for now it looks like our build might rely on it
419    # (https://crbug.com/829795).
420    cflags += [ "-fmerge-all-constants" ]
421  }
422
423  if (use_lld) {
424    if (is_win) {
425      # On Windows, we call the linker directly, instead of calling it through
426      # the driver.
427      ldflags += [ "--color-diagnostics" ]
428    } else {
429      ldflags += [ "-Wl,--color-diagnostics" ]
430    }
431  }
432
433  if (is_clang && !is_nacl && !use_xcode_clang) {
434    cflags += [
435      "-Xclang",
436      "-mllvm",
437      "-Xclang",
438      "-instcombine-lower-dbg-declare=0",
439    ]
440  }
441
442  # Print absolute paths in diagnostics. There is no precedent for doing this
443  # on Linux/Mac (GCC doesn't support it), but MSVC does this with /FC and
444  # Windows developers rely on it (crbug.com/636109) so only do this on Windows.
445  if (msvc_use_absolute_paths && is_clang && is_win) {
446    cflags += [ "-fdiagnostics-absolute-paths" ]
447  }
448
449  # Makes builds independent of absolute file path.
450  # Currently disabled for nacl since its toolchain lacks this flag (too old).
451  if (symbol_level != 0 && is_clang && !is_nacl && !is_mac &&
452      strip_absolute_paths_from_debug_symbols) {
453    # If debug option is given, clang includes $cwd in debug info by default.
454    # For such build, this flag generates reproducible obj files even we use
455    # different build directory like "out/feature_a" and "out/feature_b" if
456    # we build same files with same compile flag.
457    # Other paths are already given in relative, no need to normalize them.
458    cflags += [
459      "-Xclang",
460      "-fdebug-compilation-dir",
461      "-Xclang",
462      ".",
463    ]
464
465    if (is_win && use_lld) {
466      if (symbol_level == 2 || (is_clang && using_sanitizer)) {
467        # Absolutize source file path for PDB. Pass the real build directory
468        # if the pdb contains source-level debug information.
469        ldflags += [ "/PDBSourcePath:" + rebase_path(root_build_dir) ]
470      } else {
471        # On Windows, (non-sanitizier) symbol_level 1 builds don't contain
472        # debug information in obj files; the linker just creates enough
473        # debug info at link time to produce symbolized stacks (without line
474        # numbers). In that case, there's no downside in using a fake fixed
475        # base directory for paths in the pdb. This makes the pdb output
476        # fully deterministic and independent of the build directory.
477        assert(symbol_level == 1 && !(is_clang && using_sanitizer))
478        ldflags += [ "/PDBSourcePath:o:\fake\prefix" ]
479      }
480    }
481  }
482
483  # Tells the compiler not to use absolute paths when passing the default
484  # paths to the tools it invokes. We don't want this because we don't
485  # really need it and it can mess up the goma cache entries.
486  if (is_clang && !is_nacl) {
487    cflags += [ "-no-canonical-prefixes" ]
488  }
489
490  # C11/C++11 compiler flags setup.
491  # ---------------------------
492  if (is_linux || is_ohos || is_android || (is_nacl && is_clang) ||
493      current_os == "aix") {
494    if (target_os == "ohos") {
495      cxx11_override = use_cxx11_on_ohos
496    } else {
497      cxx11_override = use_cxx11
498    }
499
500    if (is_clang) {
501      standard_prefix = "c"
502
503      # Since we build with -std=c* and not -std=gnu*, _GNU_SOURCE will not be
504      # defined by the compiler.  However, lots of code relies on the
505      # non-standard features that _GNU_SOURCE enables, so define it manually.
506      defines += [ "_GNU_SOURCE" ]
507
508      if (is_nacl) {
509        # Undefine __STRICT_ANSI__ to get non-standard features which would
510        # otherwise not be enabled by NaCl's sysroots.
511        cflags += [ "-U__STRICT_ANSI__" ]
512      }
513    } else {
514      # Gcc does not support ##__VA_ARGS__ when in standards-conforming mode,
515      # but we use this feature in several places in Chromium.
516      standard_prefix = "gnu"
517    }
518
519    #   cflags_c += [ "-std=${standard_prefix}11" ]
520    if (cxx11_override) {
521      # Override Chromium's default for projects that wish to stay on C++11.
522      cflags_cc += [ "-std=${standard_prefix}++11" ]
523    } else {
524      cflags_cc += [ "-std=${standard_prefix}++17" ]
525    }
526  } else if (!is_win && !is_nacl && !is_mingw) {
527    if (target_os == "ohos") {
528      cxx11_override = use_cxx11_on_ohos
529    } else {
530      cxx11_override = use_cxx11
531    }
532
533    if (cxx11_override) {
534      cflags_cc += [ "-std=c++11" ]
535    } else {
536      cflags_cc += [ "-std=c++17" ]
537    }
538  }
539
540  if (is_mac) {
541    # The system libc++ on Mac doesn't have aligned allocation in C++17.
542    defines += [ "_LIBCPP_HAS_NO_ALIGNED_ALLOCATION" ]
543    cflags_cc += [ "-stdlib=libc++" ]
544    ldflags += [ "-stdlib=libc++" ]
545  }
546
547  # Add flags for link-time optimization. These flags enable
548  # optimizations/transformations that require whole-program visibility at link
549  # time, so they need to be applied to all translation units, and we may end up
550  # with miscompiles if only part of the program is compiled with LTO flags. For
551  # that reason, we cannot allow targets to enable or disable these flags, for
552  # example by disabling the optimize configuration.
553  if (!is_debug && use_thin_lto &&
554      (current_toolchain == default_toolchain ||
555       ((is_ohos || is_android) && defined(ohoa_secondary_abi_toolchain) &&
556        current_toolchain == ohos_secondary_abi_toolchain))) {
557    assert(use_lld || target_os == "chromeos" || target_os == "ohos",
558           "gold plugin only supported with ChromeOS")
559
560    cflags += [ "-flto=thin" ]
561    if (!use_libfuzzer) {
562      cflags += [ "-fsplit-lto-unit" ]
563    }
564
565    if (thin_lto_enable_optimizations) {
566      lto_opt_level = 2
567    } else {
568      lto_opt_level = 0
569    }
570
571    if (is_win) {
572      # This is a straight translation of the non-Windows flags below,
573      # except we do not use the ThinLTO cache, which leaks temporary
574      # files on Windows (https://crbug.com/871962).
575      ldflags += [
576        "/opt:lldlto=" + lto_opt_level,
577        "/opt:lldltojobs=8",
578      ]
579    } else {
580      ldflags += [ "-flto=thin" ]
581
582      # Limit the parallelism to avoid too aggressive competition between
583      # linker jobs. This is still suboptimal to a potential dynamic
584      # resource allocation scheme, but should be good enough.
585      if (use_lld) {
586        ldflags += [
587          "-Wl,--thinlto-jobs=16",
588          "-Wl,--thinlto-cache-dir=" +
589              rebase_path("$root_out_dir/thinlto-cache", root_build_dir),
590        ]
591      } else {
592        ldflags += [ "-Wl,-plugin-opt,jobs=16" ]
593      }
594
595      if (use_lld) {
596        ldflags += [ "-Wl,--lto-O" + lto_opt_level ]
597        if (thin_lto_enable_optimizations) {
598          if (is_ohos || is_android) {
599            ldflags += [
600              "-Wl,-mllvm",
601              "-Wl,-import-instr-limit=5",
602            ]
603          }
604        }
605      } else {
606        not_needed([ "lto_opt_level" ])
607      }
608    }
609
610    if (!(is_ohos || is_android)) {
611      cflags += [ "-fwhole-program-vtables" ]
612      if (!is_win) {
613        ldflags += [ "-fwhole-program-vtables" ]
614      }
615    }
616
617    # Work-around for http://openradar.appspot.com/20356002
618    if (is_mac) {
619      ldflags += [ "-Wl,-all_load" ]
620    }
621
622    # This flag causes LTO to create an .ARM.attributes section with the correct
623    # architecture. This is necessary because LLD will refuse to link a program
624    # unless the architecture revision in .ARM.attributes is sufficiently new.
625    if (current_cpu == "arm") {
626      ldflags += [ "-march=$arm_arch" ]
627    }
628  } else if (current_cpu == "riscv64") {
629    if (is_clang && !is_ohos && !is_nacl) {
630      cflags += [ "--target=riscv64-linux-gnu" ]
631      ldflags += [ "--target=riscv64-linux-gnu" ]
632    }
633    cflags += [
634      "-march=rv64imafdc",
635      "-mabi=lp64d",
636      "-mno-relax",
637    ]
638    if (is_clang && is_ohos) {
639      ldflags += [ "-Wl,--hash-style=gnu" ]
640    }
641  }
642
643  if (compiler_timing) {
644    if (is_clang) {
645      if (is_win) {
646        cflags += [ "-Xclang" ]
647      }
648      cflags += [ "-ftime-report" ]
649    } else if (is_win) {
650      cflags += [
651        # "Documented" here:
652        # http://aras-p.info/blog/2017/10/23/Best-unknown-MSVC-flag-d2cgsummary/
653        "/d2cgsummary",
654      ]
655    }
656  }
657
658  # Pass flag to LLD to work around issue in Valgrind related to
659  # location of debug symbols.
660  if (use_lld && ro_segment_workaround_for_valgrind) {
661    ldflags += [ "-Wl,--no-rosegment" ]
662  }
663
664  # This flag enforces that member pointer base types are complete. It helps
665  # prevent us from running into problems in the Microsoft C++ ABI (see
666  # https://crbug.com/847724).
667  if (is_clang && !is_nacl && target_os != "chromeos" && !use_xcode_clang &&
668      (is_win || use_custom_libcxx)) {
669    cflags += [ "-fcomplete-member-pointers" ]
670  }
671
672  # Pass the same C/C++ flags to the objective C/C++ compiler.
673  cflags_objc += cflags_c
674  cflags_objcc += cflags_cc
675
676  # Assign any flags set for the C compiler to asmflags so that they are sent
677  # to the assembler. The Windows assembler takes different types of flags
678  # so only do so for posix platforms.
679  if (is_posix) {
680    asmflags += cflags
681    asmflags += cflags_c
682  }
683}
684
685# This provides the basic options to select the target CPU and ABI.
686# It is factored out of "compiler" so that special cases can use this
687# without using everything that "compiler" brings in.  Options that
688# tweak code generation for a particular CPU do not belong here!
689# See "compiler_codegen", below.
690config("compiler_cpu_abi") {
691  cflags = []
692  ldflags = []
693  defines = []
694
695  if (is_posix && !is_mac && !is_ios) {
696    # CPU architecture. We may or may not be doing a cross compile now, so for
697    # simplicity we always explicitly set the architecture.
698    if (current_cpu == "x64") {
699      cflags += [
700        "-m64",
701        "-march=x86-64",
702      ]
703      ldflags += [ "-m64" ]
704    } else if (current_cpu == "x86") {
705      cflags += [ "-m32" ]
706      ldflags += [ "-m32" ]
707      if (!is_nacl) {
708        cflags += [
709          "-msse2",
710          "-mfpmath=sse",
711          "-mmmx",
712        ]
713      }
714    } else if (current_cpu == "arm") {
715      if (is_clang && !is_android && !is_ohos && !is_nacl) {
716        cflags += [ "--target=arm-linux-gnueabihf" ]
717        ldflags += [ "--target=arm-linux-gnueabihf" ]
718      }
719      if (!is_nacl) {
720        cflags += [
721          "-march=$arm_arch",
722          "-mfloat-abi=$arm_float_abi",
723        ]
724      }
725      if (arm_tune != "") {
726        cflags += [ "-mtune=$arm_tune" ]
727      }
728    } else if (current_cpu == "arm64") {
729      if (is_clang && !is_android && !is_ohos && !is_nacl) {
730        cflags += [ "--target=aarch64-linux-gnu" ]
731        ldflags += [ "--target=aarch64-linux-gnu" ]
732      }
733      if (is_clang && (is_android || is_ohos)) {
734        ldflags += [ "-Wl,--hash-style=gnu" ]
735      }
736      if (!is_android) {
737        cflags += [
738          "-march=$arm_arch",
739          "-mfloat-abi=$arm_float_abi",
740          "-mfpu=$arm_fpu",
741        ]
742      }
743      if (is_linux) {
744        cflags += [ "-Wno-error=unused-command-line-argument" ]
745      }
746      ldflags += [ "-march=$arm_arch" ]
747    } else if (current_cpu == "riscv64") {
748      if (is_clang && !is_android && !is_ohos && !is_nacl) {
749        cflags += [ "--target=riscv64-linux-gnu" ]
750        ldflags += [ "--target=riscv64-linux-gnu" ]
751      }
752      if (is_clang && (is_android || is_ohos)) {
753        ldflags += [ "-Wl,--hash-style=gnu" ]
754      }
755      if (!is_android) {
756        cflags += [ "-march=rv64imafdc" ]
757      }
758      ldflags += [ "-march=rv64imafdc" ]
759    } else if (current_cpu == "mipsel" && musl_is_legacy) {
760      cflags += [ "-mnan=legacy" ]
761    }
762  }
763
764  asmflags = cflags
765  if (current_cpu == "arm64") {
766    asmflags += [ "-march=armv8.2-a+dotprod+fp16" ]
767  }
768}
769
770# This provides options to tweak code generation that are necessary
771# for particular Chromium code or for working around particular
772# compiler bugs (or the combination of the two).
773config("compiler_codegen") {
774  configs = []
775  cflags = []
776
777  if (is_nacl) {
778    configs += [ "//build/config/nacl:compiler_codegen" ]
779  } else if (is_posix && !is_mac) {
780    if (current_cpu == "x86") {
781      if (is_clang) {
782        cflags += [ "-momit-leaf-frame-pointer" ]
783      }
784    } else if (current_cpu == "arm") {
785      if ((is_ohos || is_android) && !is_clang) {
786        # Clang doesn't support these flags.
787        cflags += [
788          "-fno-tree-sra",
789          "-fno-caller-saves",
790        ]
791      }
792    }
793  }
794
795  asmflags = cflags
796}
797
798config("compiler_arm_fpu") {
799  if (current_cpu == "arm" && !is_nacl) {
800    cflags = [ "-mfpu=$arm_fpu" ]
801    asmflags = cflags
802  }
803}
804
805config("compiler_arm_thumb") {
806  if (current_cpu == "arm" && arm_use_thumb && is_posix &&
807      !(is_mac || is_nacl)) {
808    cflags = [ "-mthumb" ]
809    if ((is_ohos || is_android) && !is_clang) {
810      # Clang doesn't support this option.
811      cflags += [ "-mthumb-interwork" ]
812    }
813  }
814}
815
816# runtime_library -------------------------------------------------------------
817#
818# Sets the runtime library and associated options.
819#
820# How do you determine what should go in here vs. "compiler" above? Consider if
821# a target might choose to use a different runtime library (ignore for a moment
822# if this is possible or reasonable on your system). If such a target would want
823# to change or remove your option, put it in the runtime_library config. If a
824# target wants the option regardless, put it in the compiler config.
825
826config("runtime_library") {
827  defines = []
828  configs = []
829
830  # The order of this config is important: it must appear before
831  # ohos:runtime_library.
832  if (is_posix) {
833    configs += [ "//build/config/posix:runtime_library" ]
834  }
835
836  # System-specific flags. If your compiler flags apply to one of the
837  # categories here, add it to the associated file to keep this shared config
838  # smaller.
839  if (is_win) {
840    configs += [ "//build/config/win:runtime_library" ]
841  } else if (is_linux) {
842    configs += [ "//build/config/linux:runtime_library" ]
843  } else if (is_mac) {
844    configs += [ "//build/config/mac:runtime_library" ]
845  } else if (is_ohos) {
846    configs += [ "//build/config/ohos:runtime_library" ]
847  } else if (is_android) {
848    configs += [ "//build_plugins/config/aosp:runtime_library" ]
849  } else if (is_ios) {
850    configs += [ "//build_plugins/config/ios:runtime_library" ]
851  }
852
853  if (is_component_build) {
854    defines += [ "COMPONENT_BUILD" ]
855  }
856}
857
858# default_warnings ------------------------------------------------------------
859#
860# Collects all warning flags that are used by default.  This is used as a
861# subconfig of both chromium_code and no_chromium_code.  This way these
862# flags are guaranteed to appear on the compile command line after -Wall.
863config("default_warnings") {
864  cflags = []
865  cflags_cc = []
866  ldflags = []
867
868  if (is_mac && !is_nacl) {
869    # When compiling Objective-C, warns if a method is used whose
870    # availability is newer than the deployment target.
871    cflags += [ "-Wunguarded-availability" ]
872  }
873
874  if (!is_clang) {
875    cflags += [ "-Wno-deprecated-declarations" ]
876
877    # GCC assumes 'this' is never nullptr and optimizes away code
878    # like "if (this == nullptr) ...": [1].  However, some Chromium
879    # code relies on these types of null pointer checks [2], so
880    # disable this optimization.
881    # [1] https://gcc.gnu.org/gcc-6/porting_to.html#this-cannot-be-null
882    # [2] https://crbug.com/784492#c13
883    cflags += [ "-fno-delete-null-pointer-checks" ]
884  }
885
886  # Common Clang and GCC warning setup.
887  if (!is_win || is_clang) {
888    cflags += [
889      # Disables.
890      "-Wno-missing-field-initializers",  # "struct foo f = {0};"
891      "-Wno-unused-parameter",  # Unused function parameters.
892    ]
893  }
894
895  if (is_mingw) {
896    cflags += [
897      "-Wno-error=c99-designator",
898      "-Wno-error=implicit-fallthrough",
899      "-Wno-error=reorder-init-list",
900      "-Wno-error=range-loop-construct",
901      "-Wno-error=deprecated-copy",
902      "-Wno-error=implicit-int-float-conversion",
903      "-Wno-error=inconsistent-dllimport",
904      "-Wno-error=unknown-warning-option",
905      "-Wno-error=sign-compare",
906    ]
907  }
908
909  if (is_clang) {
910    cflags += [
911      # This warns on using ints as initializers for floats in
912      # initializer lists (e.g. |int a = f(); CGSize s = { a, a };|),
913      # which happens in several places in chrome code. Not sure if
914      # this is worth fixing.
915      "-Wno-c++11-narrowing",
916      "-Wno-unneeded-internal-declaration",
917    ]
918    if (use_musl) {
919      cflags += [
920        "-Wno-error=c99-designator",
921        "-Wno-error=anon-enum-enum-conversion",
922        "-Wno-error=sizeof-array-div",
923        "-Wno-error=implicit-fallthrough",
924        "-Wno-error=reorder-init-list",
925        "-Wno-error=range-loop-construct",
926        "-Wno-error=deprecated-copy",
927        "-Wno-error=implicit-int-float-conversion",
928        "-Wno-error=inconsistent-dllimport",
929        "-Wno-error=unknown-warning-option",
930        "-Wno-error=sign-compare",
931        "-Wno-error=int-in-bool-context",
932        "-Wno-error=return-stack-address",
933        "-Wno-error=dangling-gsl",
934        "-Wno-unused-but-set-variable",
935        "-Wno-deprecated-declarations",
936        "-Wno-unused-but-set-parameter",
937        "-Wno-null-pointer-subtraction",
938        "-Wno-unqualified-std-cast-call",
939      ]
940    }
941
942    # use_xcode_clang only refers to the iOS toolchain, host binaries use
943    # chromium's clang always.
944    if (!is_nacl) {
945      if (current_toolchain == host_toolchain || !use_xcode_clang ||
946          xcode_version_int >= 930) {
947        cflags += [
948          "-Wno-user-defined-warnings",
949          "-Wno-unused-lambda-capture",
950        ]
951      }
952      if (current_toolchain == host_toolchain || !use_xcode_clang ||
953          xcode_version_int >= 1000) {
954        cflags += [ "-Wno-null-pointer-arithmetic" ]
955      }
956      if (current_toolchain == host_toolchain || !use_xcode_clang) {
957        # Flags NaCl (Clang 3.7) and Xcode 9.2 (Clang clang-900.0.39.2) do not
958        # recognize.
959        cflags += [ "-Wno-enum-compare-switch" ]
960      }
961    }
962    if (current_cpu == "riscv64") {
963      cflags += [
964        "-Wno-gnu-folding-constant",
965        "-Wno-error=non-c-typedef-for-linkage",
966        "-Wno-extern-c-compat",
967      ]
968    }
969  }
970}
971
972# chromium_code ---------------------------------------------------------------
973#
974# Toggles between higher and lower warnings for code that is (or isn't)
975# part of Chromium.
976
977config("chromium_code") {
978  if (is_win) {
979    cflags = [ "/W4" ]  # Warning level 4.
980
981    if (is_clang) {
982      # Opt in to additional [[nodiscard]] on standard library methods.
983      defines = [ "_HAS_NODISCARD" ]
984    }
985  } else {
986    cflags = [ "-Wall" ]
987    if (treat_warnings_as_errors && !is_arkui_x) {
988      cflags += [ "-Werror" ]
989
990      # The compiler driver can sometimes (rarely) emit warnings before calling
991      # the actual linker.  Make sure these warnings are treated as errors as
992      # well.
993      ldflags = [ "-Werror" ]
994    }
995    if (is_clang) {
996      # Enable extra warnings for chromium_code when we control the compiler.
997      cflags += [ "-Wextra" ]
998    }
999
1000    # In Chromium code, we define __STDC_foo_MACROS in order to get the
1001    # C99 macros on Mac and Linux.
1002    defines = [
1003      "__STDC_CONSTANT_MACROS",
1004      "__STDC_FORMAT_MACROS",
1005    ]
1006
1007    if (!is_debug && !using_sanitizer &&
1008        (!is_linux || !is_clang || is_official_build)) {
1009      # _FORTIFY_SOURCE isn't really supported by Clang now, see
1010      # http://llvm.org/bugs/show_bug.cgi?id=16821.
1011      # It seems to work fine with Ubuntu 12 headers though, so use it in
1012      # official builds.
1013      #
1014      # Non-chromium code is not guaranteed to compile cleanly with
1015      # _FORTIFY_SOURCE. Also, fortified build may fail when optimizations are
1016      # disabled, so only do that for Release build.
1017      #
1018      # Need to support fortify ability first in musl libc, so disable the option temporarily
1019      # defines += [ "_FORTIFY_SOURCE=2" ]
1020    }
1021
1022    if (is_mac) {
1023      cflags_objc = [ "-Wobjc-missing-property-synthesis" ]
1024      cflags_objcc = [ "-Wobjc-missing-property-synthesis" ]
1025    }
1026  }
1027
1028  if (is_clang) {
1029    cflags += [
1030      # Warn on missing break statements at the end of switch cases.
1031      # For intentional fallthrough, use FALLTHROUGH; from
1032      # base/compiler_specific.h
1033      "-Wimplicit-fallthrough",
1034
1035      # Thread safety analysis. See base/thread_annotations.h and
1036      # https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
1037      "-Wthread-safety",
1038    ]
1039  }
1040
1041  configs = [ ":default_warnings" ]
1042  if (is_arkui_x) {
1043    configs += [ "//build_plugins/config:arkui_x_warning" ]
1044  }
1045}
1046
1047# rtti ------------------------------------------------------------------------
1048#
1049# Allows turning Run-Time Type Identification on or off.
1050
1051config("rtti") {
1052  if (is_win) {
1053    cflags_cc = [ "/GR" ]
1054  } else {
1055    cflags_cc = [ "-frtti" ]
1056  }
1057}
1058
1059config("no_rtti") {
1060  # Some sanitizer configs may require RTTI to be left enabled globally
1061  if (!use_rtti) {
1062    if (is_win) {
1063      cflags_cc = [ "/GR-" ]
1064    } else {
1065      cflags_cc = [ "-fno-rtti" ]
1066      cflags_objcc = cflags_cc
1067    }
1068  }
1069}
1070
1071# export_dynamic ---------------------------------------------------------------
1072#
1073# Ensures all exported symbols are added to the dynamic symbol table.  This is
1074# necessary to expose Chrome's custom operator new() and operator delete() (and
1075# other memory-related symbols) to libraries.  Otherwise, they might
1076# (de)allocate memory on a different heap, which would spell trouble if pointers
1077# to heap-allocated memory are passed over shared library boundaries.
1078config("export_dynamic") {
1079  if (is_desktop_linux || export_libcxxabi_from_executables) {
1080    ldflags = [ "-rdynamic" ]
1081  }
1082}
1083
1084# thin_archive -----------------------------------------------------------------
1085#
1086# Enables thin archives on posix.  Regular archives directly include the object
1087# files used to generate it.  Thin archives merely reference the object files.
1088# This makes building them faster since it requires less disk IO, but is
1089# inappropriate if you wish to redistribute your static library.
1090# This config is added to the global config, so thin archives should already be
1091# enabled.  If you want to make a distributable static library, you need to do 2
1092# things:
1093# 1. Set complete_static_lib so that all dependencies of the library make it
1094#    into the library. See `gn help complete_static_lib` for details.
1095# 2. Remove the thin_archive config, so that the .a file actually contains all
1096#    .o files, instead of just references to .o files in the build directory
1097config("thin_archive") {
1098  # Mac and iOS use the mac-specific "libtool" command, not ar, which doesn't
1099  # have a "thin archive" mode (it does accept -T, but it means truncating
1100  # archive names to 16 characters, which is not what we want).
1101  if (is_posix && !is_nacl && !is_mac) {
1102    arflags = [ "-T" ]
1103  }
1104}
1105
1106# exceptions -------------------------------------------------------------------
1107#
1108# Allows turning Exceptions on or off.
1109
1110config("exceptions") {
1111  if (is_win) {
1112    # Enables exceptions in the STL.
1113    if (!use_custom_libcxx) {
1114      defines = [ "_HAS_EXCEPTIONS=1" ]
1115    }
1116    cflags_cc = [ "/EHsc" ]
1117  } else {
1118    cflags_cc = [ "-fexceptions" ]
1119    cflags_objcc = cflags_cc
1120  }
1121}
1122
1123config("no_exceptions") {
1124  if (is_win) {
1125    # Disables exceptions in the STL.
1126    # libc++ uses the __has_feature macro to control whether to use exceptions,
1127    # so defining this macro is unnecessary. Defining _HAS_EXCEPTIONS to 0 also
1128    # breaks libc++ because it depends on MSVC headers that only provide certain
1129    # declarations if _HAS_EXCEPTIONS is 1. Those MSVC headers do not use
1130    # exceptions, despite being conditional on _HAS_EXCEPTIONS.
1131    if (!use_custom_libcxx) {
1132      defines = [ "_HAS_EXCEPTIONS=0" ]
1133    }
1134  } else {
1135    cflags_cc = [ "-fno-exceptions" ]
1136    cflags_objcc = cflags_cc
1137  }
1138}
1139
1140# Optimization -----------------------------------------------------------------
1141#
1142# The BUILDCONFIG file sets the "default_optimization" config on targets by
1143# default. It will be equivalent to either "optimize" (release) or
1144# "no_optimize" (debug) optimization configs.
1145#
1146# You can override the optimization level on a per-target basis by removing the
1147# default config and then adding the named one you want:
1148#
1149#   configs -= [ "//build/config/compiler:default_optimization" ]
1150#   configs += [ "//build/config/compiler:optimize_max" ]
1151
1152# Shared settings for both "optimize" and "optimize_max" configs.
1153# IMPORTANT: On Windows "/O1" and "/O2" must go before the common flags.
1154if (is_win) {
1155  common_optimize_on_cflags = [
1156    "/Ob2",  # Both explicit and auto inlining.
1157    "/Oy-",  # Disable omitting frame pointers, must be after /O2.
1158    "/Zc:inline",  # Remove unreferenced COMDAT (faster links).
1159  ]
1160  if (!is_asan) {
1161    common_optimize_on_cflags += [
1162      # Put data in separate COMDATs. This allows the linker
1163      # to put bit-identical constants at the same address even if
1164      # they're unrelated constants, which saves binary size.
1165      # This optimization can't be used when ASan is enabled because
1166      # it is not compatible with the ASan ODR checker.
1167      "/Gw",
1168    ]
1169  }
1170  common_optimize_on_ldflags = []
1171
1172  # /OPT:ICF is not desirable in Debug builds, since code-folding can result in
1173  # misleading symbols in stack traces. It is also incompatible with
1174  # incremental linking, which we enable for both Debug and component builds.
1175  if (!is_debug && !is_component_build) {
1176    common_optimize_on_ldflags += [ "/OPT:ICF" ]  # Redundant COMDAT folding.
1177  }
1178
1179  if (is_official_build) {
1180    common_optimize_on_ldflags += [ "/OPT:REF" ]  # Remove unreferenced data.
1181
1182    if (!use_lld && !is_clang) {
1183      common_optimize_on_ldflags += [
1184        # Set the number of LTCG code-gen threads to eight. The default is four.
1185        # This gives a 5-10% link speedup.
1186        "/cgthreads:8",
1187      ]
1188      if (use_incremental_wpo) {
1189        # Incremental Link-time code generation.
1190        common_optimize_on_ldflags += [ "/LTCG:INCREMENTAL" ]
1191      } else {
1192        common_optimize_on_ldflags += [ "/LTCG" ]  # Link-time code generation.
1193      }
1194    }
1195  }
1196} else {
1197  common_optimize_on_cflags = []
1198  common_optimize_on_ldflags = []
1199
1200  if (is_ohos) {
1201    common_optimize_on_ldflags += [
1202      # Warn in case of text relocations.
1203      "-Wl,--warn-shared-textrel",
1204    ]
1205  }
1206
1207  if (is_mac || is_ios) {
1208    if (symbol_level == 2) {
1209      # Mac dead code stripping requires symbols.
1210      common_optimize_on_ldflags += [ "-Wl,-dead_strip" ]
1211    }
1212  } else if (current_os != "aix") {
1213    # Non-Mac Posix flags.
1214    # Aix does not support these.
1215
1216    common_optimize_on_cflags += [
1217      # Don't emit the GCC version ident directives, they just end up in the
1218      # .comment section taking up binary size.
1219      "-fno-ident",
1220
1221      # Put data and code in their own sections, so that unused symbols
1222      # can be removed at link time with --gc-sections.
1223      "-fdata-sections",
1224      "-ffunction-sections",
1225    ]
1226
1227    common_optimize_on_ldflags += [
1228      # Specifically tell the linker to perform optimizations.
1229      # See http://lwn.net/Articles/192624/ .
1230      # -O2 enables string tail merge optimization in gold and lld.
1231      "-Wl,-O2",
1232    ]
1233    if (!is_mingw) {
1234      common_optimize_on_ldflags += [ "-Wl,--gc-sections" ]
1235    }
1236  }
1237}
1238
1239config("default_stack_frames") {
1240  if (is_posix) {
1241    if (enable_frame_pointers) {
1242      cflags = [ "-fno-omit-frame-pointer" ]
1243    } else {
1244      cflags = [ "-fomit-frame-pointer" ]
1245    }
1246  }
1247  # On Windows, the flag to enable framepointers "/Oy-" must always come after
1248  # the optimization flag [e.g. "/O2"]. The optimization flag is set by one of
1249  # the "optimize" configs, see rest of this file. The ordering that cflags are
1250  # applied is well-defined by the GN spec, and there is no way to ensure that
1251  # cflags set by "default_stack_frames" is applied after those set by an
1252  # "optimize" config. Similarly, there is no way to propagate state from this
1253  # config into the "optimize" config. We always apply the "/Oy-" config in the
1254  # definition for common_optimize_on_cflags definition, even though this may
1255  # not be correct.
1256}
1257
1258# Default "optimization on" config.
1259config("optimize") {
1260  if (optimize_for_size && !is_nacl) {
1261    # Favor size over speed.
1262    if (is_clang) {
1263      cflags = [ "-O2" ] + common_optimize_on_cflags
1264    } else {
1265      cflags = [ "-Os" ] + common_optimize_on_cflags
1266    }
1267  } else {
1268    cflags = [ "-O2" ] + common_optimize_on_cflags
1269  }
1270  ldflags = common_optimize_on_ldflags
1271}
1272
1273# Turn off optimizations.
1274config("no_optimize") {
1275  if (is_win) {
1276    cflags = [
1277      "/Od",  # Disable optimization.
1278      "/Ob0",  # Disable all inlining (on by default).
1279      "/GF",  # Enable string pooling (off by default).
1280    ]
1281  } else if ((is_ohos || is_android) && !ohos_full_debug) {
1282    # On ohos we kind of optimize some things that don't affect debugging
1283    # much even when optimization is disabled to get the binary size down.
1284    if (is_clang) {
1285      cflags = [ "-Oz" ] + common_optimize_on_cflags
1286      ldflags = common_optimize_on_ldflags
1287    } else {
1288      cflags = [ "-Os" ] + common_optimize_on_cflags
1289      ldflags = common_optimize_on_ldflags
1290    }
1291  } else {
1292    # On ohos_full_debug mode, we close all optimization
1293    cflags = [ "-O0" ]
1294    ldflags = []
1295  }
1296}
1297
1298# This config can be used to override the default settings for per-component
1299# and whole-program optimization, optimizing the particular target for speed
1300# instead of code size. This config is exactly the same as "optimize_max"
1301# except that we use -O3 instead of -O2 on non-win, non-IRT platforms.
1302config("optimize_speed") {
1303  if (is_nacl && is_nacl_irt) {
1304    # The NaCl IRT is a special case and always wants its own config.
1305    # Various components do:
1306    #   if (!is_debug) {
1307    #     configs -= [ "//build/config/compiler:default_optimization" ]
1308    #     configs += [ "//build/config/compiler:optimize_max" ]
1309    #   }
1310    # So this config has to have the selection logic just like
1311    # "default_optimization", below.
1312    configs = [ "//build/config/nacl:irt_optimize" ]
1313  } else {
1314    ldflags = common_optimize_on_ldflags
1315    if (is_win) {
1316      # Favor speed over size, /O2 must be before the common flags. The GYP
1317      # build also specifies /Ot, /Oi, and /GF, but these are implied by /O2.
1318      cflags = [ "/O2" ] + common_optimize_on_cflags
1319
1320      if (is_official_build && !is_clang) {
1321        cflags += [
1322          "/GL",  # Whole program optimization.
1323
1324          # Disable Warning 4702 ("Unreachable code") for the WPO/PGO builds.
1325          # Probably anything that this would catch that wouldn't be caught in a
1326          # normal build isn't going to actually be a bug, so the incremental
1327          # value of C4702 for PGO builds is likely very small.
1328          "/wd4702",
1329        ]
1330      }
1331    } else if (optimize_for_fuzzing) {
1332      cflags = [ "-O0" ] + common_optimize_on_cflags
1333    } else {
1334      cflags = [ "-O3" ] + common_optimize_on_cflags
1335    }
1336  }
1337}
1338
1339config("optimize_fuzzing") {
1340  cflags = [ "-O0" ] + common_optimize_on_cflags
1341  ldflags = common_optimize_on_ldflags
1342  visibility = [ ":default_optimization" ]
1343}
1344
1345# The default optimization applied to all targets. This will be equivalent to
1346# either "optimize" or "no_optimize", depending on the build flags.
1347config("default_optimization") {
1348  if (is_nacl && is_nacl_irt) {
1349    # The NaCl IRT is a special case and always wants its own config.
1350    # It gets optimized the same way regardless of the type of build.
1351    configs = [ "//build/config/nacl:irt_optimize" ]
1352  } else if (is_debug) {
1353    configs = [ ":no_optimize" ]
1354  } else if (optimize_for_fuzzing) {
1355    assert(!is_win, "Fuzzing optimize level not supported on Windows")
1356
1357    # Coverage build is quite slow. Using "optimize_for_fuzzing" makes it even
1358    # slower as it uses "-O1" instead of "-O3". Prevent that from happening.
1359    assert(!use_clang_coverage,
1360           "optimize_for_fuzzing=true should not be used with " +
1361               "use_clang_coverage=true.")
1362    configs = [ ":optimize_fuzzing" ]
1363  } else {
1364    configs = [ ":optimize" ]
1365  }
1366}
1367
1368_clang_sample_profile = ""
1369if (is_clang && current_toolchain == default_toolchain) {
1370  if (clang_sample_profile_path != "") {
1371    _clang_sample_profile = clang_sample_profile_path
1372  } else if (clang_use_default_sample_profile) {
1373    assert(build_with_chromium,
1374           "Our default profiles currently only apply to Chromium")
1375    assert(is_ohos || is_android || is_desktop_linux,
1376           "The current platform has no default profile")
1377    _clang_sample_profile = ""
1378  }
1379}
1380
1381# Clang offers a way to assert that AFDO profiles are accurate, which causes it
1382# to optimize functions not represented in a profile more aggressively for size.
1383# This config can be toggled in cases where shaving off binary size hurts
1384# performance too much.
1385config("afdo_optimize_size") {
1386  if (_clang_sample_profile != "" && sample_profile_is_accurate) {
1387    cflags = [ "-fprofile-sample-accurate" ]
1388  }
1389}
1390
1391# GCC and clang support a form of profile-guided optimization called AFDO.
1392# There are some targeted places that AFDO regresses (and an icky interaction
1393# between //base/allocator:tcmalloc and AFDO on GCC), so we provide a separate
1394# config to allow AFDO to be disabled per-target.
1395config("afdo") {
1396  if (is_clang) {
1397    if (_clang_sample_profile != "") {
1398      rebased_clang_sample_profile =
1399          rebase_path(_clang_sample_profile, root_build_dir)
1400      cflags = [ "-fprofile-sample-use=${rebased_clang_sample_profile}" ]
1401      inputs = [ _clang_sample_profile ]
1402    }
1403  } else if (auto_profile_path != "" &&
1404             current_toolchain == default_toolchain) {
1405    cflags = [ "-fauto-profile=${auto_profile_path}" ]
1406    inputs = [ auto_profile_path ]
1407  }
1408}
1409
1410# Symbols ----------------------------------------------------------------------
1411
1412# The BUILDCONFIG file sets the "default_symbols" config on targets by
1413# default. It will be equivalent to one the three specific symbol levels.
1414#
1415# You can override the symbol level on a per-target basis by removing the
1416# default config and then adding the named one you want:
1417#
1418#   configs -= [ "//build/config/compiler:default_symbols" ]
1419#   configs += [ "//build/config/compiler:symbols" ]
1420
1421# A helper config that all configs passing /DEBUG to the linker should
1422# include as sub-config.
1423config("win_pdbaltpath") {
1424  visibility = [
1425    ":minimal_symbols",
1426    ":symbols",
1427  ]
1428
1429  # /DEBUG causes the linker to generate a pdb file, and to write the absolute
1430  # path to it in the executable file it generates.  This flag turns that
1431  # absolute path into just the basename of the pdb file, which helps with
1432  # build reproducibility. Debuggers look for pdb files next to executables,
1433  # so there's no downside to always using this.
1434  ldflags = [ "/pdbaltpath:%_PDB%" ]
1435}
1436
1437# Full symbols.
1438config("symbols") {
1439  if (is_win) {
1440    if (is_clang) {
1441      # Note that with VC++ this requires is_win_fastlink, enforced elsewhere.
1442      cflags = [ "/Z7" ]  # Debug information in the .obj files.
1443    } else {
1444      cflags = [ "/Zi" ]  # Produce PDB file, no edit and continue.
1445    }
1446
1447    if (is_win_fastlink && !use_lld) {
1448      # Tell VS 2015+ to create a PDB that references debug
1449      # information in .obj and .lib files instead of copying
1450      # it all. This flag is incompatible with /PROFILE
1451      ldflags = [ "/DEBUG:FASTLINK" ]
1452    } else if (is_clang && use_lld && use_ghash) {
1453      cflags += [
1454        "-mllvm",
1455        "-emit-codeview-ghash-section",
1456      ]
1457      ldflags = [ "/DEBUG:GHASH" ]
1458    } else {
1459      ldflags = [ "/DEBUG" ]
1460    }
1461
1462    # All configs using /DEBUG should include this:
1463    configs = [ ":win_pdbaltpath" ]
1464
1465    if (is_clang) {
1466      # /DEBUG:FASTLINK requires every object file to have standalone debug
1467      # information.
1468      if (is_win_fastlink && !use_lld) {
1469        cflags += [ "-fstandalone-debug" ]
1470      } else {
1471        cflags += [ "-fno-standalone-debug" ]
1472      }
1473    }
1474  } else {
1475    if (is_mac) {
1476      cflags = [ "-gdwarf-2" ]
1477      if (is_mac && enable_dsyms) {
1478        # If generating dSYMs, specify -fno-standalone-debug. This was
1479        # originally specified for https://crbug.com/479841 because dsymutil
1480        # could not handle a 4GB dSYM file. But dsymutil from Xcodes prior to
1481        # version 7 also produces debug data that is incompatible with Breakpad
1482        # dump_syms, so this is still required (https://crbug.com/622406).
1483        cflags += [ "-fno-standalone-debug" ]
1484      }
1485    } else {
1486      cflags = []
1487      if (!use_debug_fission && current_cpu == "arm") {
1488        # dump_syms has issues with dwarf4 on arm, https://crbug.com/744956
1489        #
1490        # debug fission needs DWARF DIEs to be emitted at version 4.
1491        # Chrome OS emits Debug Frame in DWARF1 to make breakpad happy. [1]
1492        # Unless ohos needs debug fission, DWARF3 is the simplest solution.
1493        #
1494        # [1] crrev.com/a81d5ade0b043208e06ad71a38bcf9c348a1a52f
1495        cflags += [ "-gdwarf-3" ]
1496      }
1497      if (!ohos_full_debug) {
1498        cflags += [ "-g2" ]
1499      } else {
1500        # Set -g3 symbol level when ohos_full_debug is true
1501        cflags += [ "-g3" ]
1502      }
1503    }
1504    if (use_debug_fission && !is_nacl && !(is_ohos || is_android)) {
1505      # NOTE: Some Chrome OS builds globally set |use_debug_fission| to true,
1506      # but they also build some targets against ohos toolchains which aren't
1507      # compatible with it.
1508      cflags += [ "-gsplit-dwarf" ]
1509    }
1510    asmflags = cflags
1511    ldflags = []
1512
1513    if (!is_mac && !is_nacl && current_cpu != "x86" && (use_gold || use_lld)) {
1514      if (is_clang) {
1515        # This flag enables the GNU-format pubnames and pubtypes sections,
1516        # which lld needs in order to generate a correct GDB index.
1517        cflags += [ "-ggnu-pubnames" ]
1518      }
1519      ldflags += [ "-Wl,--gdb-index" ]
1520    }
1521  }
1522}
1523
1524# Minimal symbols.
1525# This config guarantees to hold symbol for stack trace which are shown to user
1526# when crash happens in unittests running on buildbot.
1527config("minimal_symbols") {
1528  if (is_win) {
1529    # Linker symbols for backtraces only.
1530    cflags = []
1531    ldflags = [ "/DEBUG" ]
1532
1533    # All configs using /DEBUG should include this:
1534    configs = [ ":win_pdbaltpath" ]
1535
1536    # For win/asan, get stack traces with full line numbers.
1537    # AddressSanitizerTests.TestAddressSanitizer needs this, and since
1538    # win/asan isn't a default cq bot the build time hit is ok.
1539    if (is_clang && using_sanitizer) {
1540      # -gline-tables-only is the same as -g1, but clang-cl only exposes the
1541      # former.
1542      cflags += [ "-gline-tables-only" ]
1543    }
1544  } else {
1545    cflags = []
1546    if (current_cpu == "arm") {
1547      # dump_syms has issues with dwarf4 on arm, https://crbug.com/744956
1548      cflags += [ "-gdwarf-3" ]
1549    }
1550    cflags += [ "-g1" ]
1551    ldflags = []
1552    if ((is_ohos || is_android) && is_clang) {
1553      # ohos defaults to symbol_level=1 builds in production builds
1554      # (https://crbug.com/648948), but clang, unlike gcc, doesn't emit
1555      # DW_AT_linkage_name in -g1 builds. -fdebug-info-for-profiling enables
1556      # that (and a bunch of other things we don't need), so that we get
1557      # qualified names in stacks.
1558      cflags += [ "-fdebug-info-for-profiling" ]
1559    }
1560
1561    # Note: -gsplit-dwarf implicitly turns on -g2 with clang, so don't pass it.
1562    asmflags = cflags
1563  }
1564}
1565
1566# No symbols.
1567config("no_symbols") {
1568  if (!is_win) {
1569    cflags = [ "-g0" ]
1570    asmflags = cflags
1571  }
1572}
1573
1574# Default symbols.
1575config("default_symbols") {
1576  if (symbol_level == 0) {
1577    configs = [ ":no_symbols" ]
1578  } else if (symbol_level == 1) {
1579    configs = [ ":minimal_symbols" ]
1580  } else if (symbol_level == 2) {
1581    configs = [ ":symbols" ]
1582  } else {
1583    assert(false)
1584  }
1585
1586  # This config is removed by base unittests app.
1587  if ((is_ohos || is_android) && is_clang && strip_debug_info) {
1588    configs += [ ":strip_debug" ]
1589  }
1590}
1591
1592config("strip_debug") {
1593  if (!defined(ldflags)) {
1594    ldflags = []
1595  }
1596  ldflags += [ "-Wl,--strip-debug" ]
1597}
1598
1599config("no_common") {
1600  if (is_clang) {
1601    cflags = [ "-fno-common" ]
1602    asmflags = cflags
1603  }
1604}
1605