1 ============================
2 Clang Compiler User's Manual
3 ============================
5 .. include:: <isonum.txt>
13 The Clang Compiler is an open-source compiler for the C family of
14 programming languages, aiming to be the best in class implementation of
15 these languages. Clang builds on the LLVM optimizer and code generator,
16 allowing it to provide high-quality optimization and code generation
17 support for many targets. For more general information, please see the
18 `Clang Web Site <https://clang.llvm.org>`_ or the `LLVM Web
19 Site <https://llvm.org>`_.
21 This document describes important notes about using Clang as a compiler
22 for an end-user, documenting the supported features, command line
23 options, etc. If you are interested in using Clang to build a tool that
24 processes code, please see :doc:`InternalsManual`. If you are interested in the
25 `Clang Static Analyzer <https://clang-analyzer.llvm.org>`_, please see its web
28 Clang is one component in a complete toolchain for C family languages.
29 A separate document describes the other pieces necessary to
30 :doc:`assemble a complete toolchain <Toolchain>`.
32 Clang is designed to support the C family of programming languages,
33 which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
34 :ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
35 language-specific information, please see the corresponding language
38 - :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
40 - :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
41 variants depending on base language.
42 - :ref:`C++ Language <cxx>`
43 - :ref:`Objective C++ Language <objcxx>`
44 - :ref:`OpenCL Kernel Language <opencl>`: OpenCL C 1.0, 1.1, 1.2, 2.0, 3.0,
45 and C++ for OpenCL 1.0 and 2021.
47 In addition to these base languages and their dialects, Clang supports a
48 broad variety of language extensions, which are documented in the
49 corresponding language section. These extensions are provided to be
50 compatible with the GCC, Microsoft, and other popular compilers as well
51 as to improve functionality through Clang-specific features. The Clang
52 driver and language features are intentionally designed to be as
53 compatible with the GNU GCC compiler as reasonably possible, easing
54 migration from GCC to Clang. In most cases, code "just works".
55 Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
56 to be compatible with the Visual C++ compiler, cl.exe.
58 In addition to language specific features, Clang has a variety of
59 features that depend on what CPU architecture or operating system is
60 being compiled for. Please see the :ref:`Target-Specific Features and
61 Limitations <target_features>` section for more details.
63 The rest of the introduction introduces some basic :ref:`compiler
64 terminology <terminology>` that is used throughout this manual and
65 contains a basic :ref:`introduction to using Clang <basicusage>` as a
66 command line compiler.
73 Front end, parser, backend, preprocessor, undefined behavior,
81 Intro to how to use a C compiler for newbies.
83 compile + link compile then link debug info enabling optimizations
84 picking a language to use, defaults to C17 by default. Autosenses based
85 on extension. using a makefile
90 This section is generally an index into other sections. It does not go
91 into depth on the ones that are covered by other sections. However, the
92 first part introduces the language selection and other high level
93 options like :option:`-c`, :option:`-g`, etc.
95 Options to Control Error and Warning Messages
96 ---------------------------------------------
100 Turn warnings into errors.
102 .. This is in plain monospaced font because it generates the same label as
103 .. -Werror, and Sphinx complains.
107 Turn warning "foo" into an error.
109 .. option:: -Wno-error=foo
111 Turn warning "foo" into a warning even if :option:`-Werror` is specified.
115 Enable warning "foo".
116 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
117 list of the warning flags that can be specified in this way.
121 Disable warning "foo".
125 Disable all diagnostics.
127 .. option:: -Weverything
129 :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
131 .. option:: -pedantic
133 Warn on language extensions.
135 .. option:: -pedantic-errors
137 Error on language extensions.
139 .. option:: -Wsystem-headers
141 Enable warnings from system headers.
143 .. option:: -ferror-limit=123
145 Stop emitting diagnostics after 123 errors have been produced. The default is
146 20, and the error limit can be disabled with `-ferror-limit=0`.
148 .. option:: -ftemplate-backtrace-limit=123
150 Only emit up to 123 template instantiation notes within the template
151 instantiation backtrace for a single warning or error. The default is 10, and
152 the limit can be disabled with `-ftemplate-backtrace-limit=0`.
154 .. _cl_diag_formatting:
156 Formatting of Diagnostics
157 ^^^^^^^^^^^^^^^^^^^^^^^^^
159 Clang aims to produce beautiful diagnostics by default, particularly for
160 new users that first come to Clang. However, different people have
161 different preferences, and sometimes Clang is driven not by a human,
162 but by a program that wants consistent and easily parsable output. For
163 these cases, Clang provides a wide range of options to control the exact
164 output format of the diagnostics that it generates.
166 .. _opt_fshow-column:
168 .. option:: -f[no-]show-column
170 Print column number in diagnostic.
172 This option, which defaults to on, controls whether or not Clang
173 prints the column number of a diagnostic. For example, when this is
174 enabled, Clang will print something like:
178 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
183 When this is disabled, Clang will print "test.c:28: warning..." with
186 The printed column numbers count bytes from the beginning of the
187 line; take care if your source contains multibyte characters.
189 .. _opt_fshow-source-location:
191 .. option:: -f[no-]show-source-location
193 Print source file/line/column information in diagnostic.
195 This option, which defaults to on, controls whether or not Clang
196 prints the filename, line number and column number of a diagnostic.
197 For example, when this is enabled, Clang will print something like:
201 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
206 When this is disabled, Clang will not print the "test.c:28:8: "
209 .. _opt_fcaret-diagnostics:
211 .. option:: -f[no-]caret-diagnostics
213 Print source line and ranges from source code in diagnostic.
214 This option, which defaults to on, controls whether or not Clang
215 prints the source line, source ranges, and caret when emitting a
216 diagnostic. For example, when this is enabled, Clang will print
221 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
226 .. option:: -f[no-]color-diagnostics
228 This option, which defaults to on when a color-capable terminal is
229 detected, controls whether or not Clang prints diagnostics in color.
231 When this option is enabled, Clang will use colors to highlight
232 specific parts of the diagnostic, e.g.,
234 .. nasty hack to not lose our dignity
239 <b><span style="color:black">test.c:28:8: <span style="color:magenta">warning</span>: extra tokens at end of #endif directive [-Wextra-tokens]</span></b>
241 <span style="color:green">^</span>
242 <span style="color:green">//</span>
245 When this is disabled, Clang will just print:
249 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
254 If the ``NO_COLOR`` environment variable is defined and not empty
255 (regardless of value), color diagnostics are disabled. If ``NO_COLOR`` is
256 defined and ``-fcolor-diagnostics`` is passed on the command line, Clang
257 will honor the command line argument.
259 .. option:: -fansi-escape-codes
261 Controls whether ANSI escape codes are used instead of the Windows Console
262 API to output colored diagnostics. This option is only used on Windows and
265 .. option:: -fdiagnostics-format=clang/msvc/vi
267 Changes diagnostic output format to better match IDEs and command line tools.
269 This option controls the output format of the filename, line number,
270 and column printed in diagnostic messages. The options, and their
271 affect on formatting a simple conversion diagnostic, follow:
276 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
281 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
286 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
288 .. _opt_fdiagnostics-show-option:
290 .. option:: -f[no-]diagnostics-show-option
292 Enable ``[-Woption]`` information in diagnostic line.
294 This option, which defaults to on, controls whether or not Clang
295 prints the associated :ref:`warning group <cl_diag_warning_groups>`
296 option name when outputting a warning diagnostic. For example, in
301 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
306 Passing **-fno-diagnostics-show-option** will prevent Clang from
307 printing the [:option:`-Wextra-tokens`] information in
308 the diagnostic. This information tells you the flag needed to enable
309 or disable the diagnostic, either from the command line or through
310 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
312 .. option:: -fdiagnostics-show-category=none/id/name
314 Enable printing category information in diagnostic line.
316 This option, which defaults to "none", controls whether or not Clang
317 prints the category associated with a diagnostic when emitting it.
318 Each diagnostic may or many not have an associated category, if it
319 has one, it is listed in the diagnostic categorization field of the
320 diagnostic line (in the []'s).
322 For example, a format string warning will produce these three
323 renditions based on the setting of this option:
327 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
328 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
329 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
331 This category can be used by clients that want to group diagnostics
332 by category, so it should be a high level category. We want dozens
333 of these, not hundreds or thousands of them.
335 .. _opt_fsave-optimization-record:
337 .. option:: -f[no-]save-optimization-record[=<format>]
339 Enable optimization remarks during compilation and write them to a separate
342 This option, which defaults to off, controls whether Clang writes
343 optimization reports to a separate file. By recording diagnostics in a file,
344 users can parse or sort the remarks in a convenient way.
346 By default, the serialization format is YAML.
348 The supported serialization formats are:
350 - .. _opt_fsave_optimization_record_yaml:
352 ``-fsave-optimization-record=yaml``: A structured YAML format.
354 - .. _opt_fsave_optimization_record_bitstream:
356 ``-fsave-optimization-record=bitstream``: A binary format based on LLVM
359 The output file is controlled by :option:`-foptimization-record-file`.
361 In the absence of an explicit output file, the file is chosen using the
364 ``<base>.opt.<format>``
366 where ``<base>`` is based on the output file of the compilation (whether
367 it's explicitly specified through `-o` or not) when used with `-c` or `-S`.
370 * ``clang -fsave-optimization-record -c in.c -o out.o`` will generate
373 * ``clang -fsave-optimization-record -c in.c`` will generate
376 When targeting (Thin)LTO, the base is derived from the output filename, and
377 the extension is not dropped.
379 When targeting ThinLTO, the following scheme is used:
381 ``<base>.opt.<format>.thin.<num>.<format>``
383 Darwin-only: when used for generating a linked binary from a source file
384 (through an intermediate object file), the driver will invoke `cc1` to
385 generate a temporary object file. The temporary remark file will be emitted
386 next to the object file, which will then be picked up by `dsymutil` and
387 emitted in the .dSYM bundle. This is available for all formats except YAML.
391 ``clang -fsave-optimization-record=bitstream in.c -o out`` will generate
393 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.o``
395 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.opt.bitstream``
399 * ``out.dSYM/Contents/Resources/Remarks/out``
401 Darwin-only: compiling for multiple architectures will use the following
404 ``<base>-<arch>.opt.<format>``
406 Note that this is incompatible with passing the
407 :option:`-foptimization-record-file` option.
409 .. option:: -foptimization-record-file
411 Control the file to which optimization reports are written. This implies
412 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`.
414 On Darwin platforms, this is incompatible with passing multiple
415 ``-arch <arch>`` options.
417 .. option:: -foptimization-record-passes
419 Only include passes which match a specified regular expression.
421 When optimization reports are being output (see
422 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
423 option controls the passes that will be included in the final report.
425 If this option is not used, all the passes are included in the optimization
428 .. _opt_fdiagnostics-show-hotness:
430 .. option:: -f[no-]diagnostics-show-hotness
432 Enable profile hotness information in diagnostic line.
434 This option controls whether Clang prints the profile hotness associated
435 with diagnostics in the presence of profile-guided optimization information.
436 This is currently supported with optimization remarks (see
437 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
438 allows users to focus on the hot optimization remarks that are likely to be
439 more relevant for run-time performance.
441 For example, in this output, the block containing the callsite of `foo` was
442 executed 3000 times according to the profile data:
446 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
447 sum += foo(x, x - 2);
450 This option is implied when
451 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
452 Otherwise, it defaults to off.
454 .. option:: -fdiagnostics-hotness-threshold
456 Prevent optimization remarks from being output if they do not have at least
459 This option, which defaults to zero, controls the minimum hotness an
460 optimization remark would need in order to be output by Clang. This is
461 currently supported with optimization remarks (see :ref:`Options to Emit
462 Optimization Reports <rpass>`) when profile hotness information in
463 diagnostics is enabled (see
464 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
466 .. _opt_fdiagnostics-fixit-info:
468 .. option:: -f[no-]diagnostics-fixit-info
470 Enable "FixIt" information in the diagnostics output.
472 This option, which defaults to on, controls whether or not Clang
473 prints the information on how to fix a specific diagnostic
474 underneath it when it knows. For example, in this output:
478 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
483 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
484 printing the "//" line at the end of the message. This information
485 is useful for users who may not understand what is wrong, but can be
486 confusing for machine parsing.
488 .. _opt_fdiagnostics-print-source-range-info:
490 .. option:: -fdiagnostics-print-source-range-info
492 Print machine parsable information about source ranges.
493 This option makes Clang print information about source ranges in a machine
494 parsable format after the file/line/column number information. The
495 information is a simple sequence of brace enclosed ranges, where each range
496 lists the start and end line/column locations. For example, in this output:
500 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
501 P = (P-42) + Gamma*4;
504 The {}'s are generated by -fdiagnostics-print-source-range-info.
506 The printed column numbers count bytes from the beginning of the
507 line; take care if your source contains multibyte characters.
509 .. option:: -fdiagnostics-parseable-fixits
511 Print Fix-Its in a machine parseable form.
513 This option makes Clang print available Fix-Its in a machine
514 parseable format at the end of diagnostics. The following example
515 illustrates the format:
519 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
521 The range printed is a half-open range, so in this example the
522 characters at column 25 up to but not including column 29 on line 7
523 in t.cpp should be replaced with the string "Gamma". Either the
524 range or the replacement string may be empty (representing strict
525 insertions and strict erasures, respectively). Both the file name
526 and the insertion string escape backslash (as "\\\\"), tabs (as
527 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
528 non-printable characters (as octal "\\xxx").
530 The printed column numbers count bytes from the beginning of the
531 line; take care if your source contains multibyte characters.
533 .. option:: -fno-elide-type
535 Turns off elision in template type printing.
537 The default for template type printing is to elide as many template
538 arguments as possible, removing those which are the same in both
539 template types, leaving only the differences. Adding this flag will
540 print all the template arguments. If supported by the terminal,
541 highlighting will still appear on differing arguments.
547 t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], map<float, [...]>>>' to 'vector<map<[...], map<double, [...]>>>' for 1st argument;
553 t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<int, map<float, int>>>' to 'vector<map<int, map<double, int>>>' for 1st argument;
555 .. option:: -fdiagnostics-show-template-tree
557 Template type diffing prints a text tree.
559 For diffing large templated types, this option will cause Clang to
560 display the templates as an indented text tree, one argument per
561 line, with differences marked inline. This is compatible with
568 t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], map<float, [...]>>>' to 'vector<map<[...], map<double, [...]>>>' for 1st argument;
570 With :option:`-fdiagnostics-show-template-tree`:
574 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
583 .. option:: -fcaret-diagnostics-max-lines:
585 Controls how many lines of code clang prints for diagnostics. By default,
586 clang prints a maximum of 16 lines of code.
589 .. option:: -fdiagnostics-show-line-numbers:
591 Controls whether clang will print a margin containing the line number on
592 the left of each line of code it prints for diagnostics.
598 test.cpp:5:1: error: 'main' must return 'int'
604 With -fno-diagnostics-show-line-numbers:
608 test.cpp:5:1: error: 'main' must return 'int'
615 .. _cl_diag_warning_groups:
617 Individual Warning Groups
618 ^^^^^^^^^^^^^^^^^^^^^^^^^
620 TODO: Generate this from tblgen. Define one anchor per warning group.
622 .. option:: -Wextra-tokens
624 Warn about excess tokens at the end of a preprocessor directive.
626 This option, which defaults to on, enables warnings about extra
627 tokens at the end of preprocessor directives. For example:
631 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
635 These extra tokens are not strictly conforming, and are usually best
636 handled by commenting them out.
638 .. option:: -Wambiguous-member-template
640 Warn about unqualified uses of a member template whose name resolves to
641 another template at the location of the use.
643 This option, which defaults to on, enables a warning in the
648 template<typename T> struct set{};
649 template<typename T> struct trait { typedef const T& type; };
651 template<typename T> void set(typename trait<T>::type value) {}
658 C++ [basic.lookup.classref] requires this to be an error, but,
659 because it's hard to work around, Clang downgrades it to a warning
662 .. option:: -Wbind-to-temporary-copy
664 Warn about an unusable copy constructor when binding a reference to a
667 This option enables warnings about binding a
668 reference to a temporary when the temporary doesn't have a usable
669 copy constructor. For example:
676 NonCopyable(const NonCopyable&);
678 void foo(const NonCopyable&);
680 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
685 struct NonCopyable2 {
687 NonCopyable2(NonCopyable2&);
689 void foo(const NonCopyable2&);
691 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
694 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
695 whose instantiation produces a compile error, that error will still
696 be a hard error in C++98 mode even if this warning is turned off.
698 Options to Control Clang Crash Diagnostics
699 ------------------------------------------
701 As unbelievable as it may sound, Clang does crash from time to time.
702 Generally, this only occurs to those living on the `bleeding
703 edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great
704 lengths to assist you in filing a bug report. Specifically, Clang
705 generates preprocessed source file(s) and associated run script(s) upon
706 a crash. These files should be attached to a bug report to ease
707 reproducibility of the failure. Below are the command line options to
708 control the crash diagnostics.
710 .. option:: -fcrash-diagnostics=<val>
714 * ``off`` (Disable auto-generation of preprocessed source files during a clang crash.)
715 * ``compiler`` (Generate diagnostics for compiler crashes (default))
716 * ``all`` (Generate diagnostics for all tools which support it)
718 .. option:: -fno-crash-diagnostics
720 Disable auto-generation of preprocessed source files during a clang crash.
722 The -fno-crash-diagnostics flag can be helpful for speeding the process
723 of generating a delta reduced test case.
725 .. option:: -fcrash-diagnostics-dir=<dir>
727 Specify where to write the crash diagnostics files; defaults to the
728 usual location for temporary files.
730 .. envvar:: CLANG_CRASH_DIAGNOSTICS_DIR=<dir>
732 Like ``-fcrash-diagnostics-dir=<dir>``, specifies where to write the
733 crash diagnostics files, but with lower precedence than the option.
735 Clang is also capable of generating preprocessed source file(s) and associated
736 run script(s) even without a crash. This is specially useful when trying to
737 generate a reproducer for warnings or errors while using modules.
739 .. option:: -gen-reproducer
741 Generates preprocessed source files, a reproducer script and if relevant, a
742 cache containing: built module pcm's and all headers needed to rebuild the
747 Options to Emit Optimization Reports
748 ------------------------------------
750 Optimization reports trace, at a high-level, all the major decisions
751 done by compiler transformations. For instance, when the inliner
752 decides to inline function ``foo()`` into ``bar()``, or the loop unroller
753 decides to unroll a loop N times, or the vectorizer decides to
754 vectorize a loop body.
756 Clang offers a family of flags which the optimizers can use to emit
757 a diagnostic in three cases:
759 1. When the pass makes a transformation (`-Rpass`).
761 2. When the pass fails to make a transformation (`-Rpass-missed`).
763 3. When the pass determines whether or not to make a transformation
766 NOTE: Although the discussion below focuses on `-Rpass`, the exact
767 same options apply to `-Rpass-missed` and `-Rpass-analysis`.
769 Since there are dozens of passes inside the compiler, each of these flags
770 take a regular expression that identifies the name of the pass which should
771 emit the associated diagnostic. For example, to get a report from the inliner,
772 compile the code with:
774 .. code-block:: console
776 $ clang -O2 -Rpass=inline code.cc -o code
777 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
778 int bar(int j) { return foo(j, j - 2); }
781 Note that remarks from the inliner are identified with `[-Rpass=inline]`.
782 To request a report from every optimization pass, you should use
783 `-Rpass=.*` (in fact, you can use any valid POSIX regular
784 expression). However, do not expect a report from every transformation
785 made by the compiler. Optimization remarks do not really make sense
786 outside of the major transformations (e.g., inlining, vectorization,
787 loop optimizations) and not every optimization pass supports this
790 Note that when using profile-guided optimization information, profile hotness
791 information can be included in the remarks (see
792 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
797 1. Optimization remarks that refer to function names will display the
798 mangled name of the function. Since these remarks are emitted by the
799 back end of the compiler, it does not know anything about the input
800 language, nor its mangling rules.
802 2. Some source locations are not displayed correctly. The front end has
803 a more detailed source location tracking than the locations included
804 in the debug info (e.g., the front end can locate code inside macro
805 expansions). However, the locations used by `-Rpass` are
806 translated from debug annotations. That translation can be lossy,
807 which results in some remarks having no location information.
809 Options to Emit Resource Consumption Reports
810 --------------------------------------------
812 These are options that report execution time and consumed memory of different
815 .. option:: -fproc-stat-report=
817 This option requests driver to print used memory and execution time of each
818 compilation step. The ``clang`` driver during execution calls different tools,
819 like compiler, assembler, linker etc. With this option the driver reports
820 total execution time, the execution time spent in user mode and peak memory
821 usage of each the called tool. Value of the option specifies where the report
822 is sent to. If it specifies a regular file, the data are saved to this file in
825 .. code-block:: console
827 $ clang -fproc-stat-report=abc foo.c
829 clang-11,"/tmp/foo-123456.o",92000,84000,87536
830 ld,"a.out",900,8000,53568
832 The data on each row represent:
834 * file name of the tool executable,
835 * output file name in quotes,
836 * total execution time in microseconds,
837 * execution time in user mode in microseconds,
838 * peak memory usage in Kb.
840 It is possible to specify this option without any value. In this case statistics
841 are printed on standard output in human readable format:
843 .. code-block:: console
845 $ clang -fproc-stat-report foo.c
846 clang-11: output=/tmp/foo-855a8e.o, total=68.000 ms, user=60.000 ms, mem=86920 Kb
847 ld: output=a.out, total=8.000 ms, user=4.000 ms, mem=52320 Kb
849 The report file specified in the option is locked for write, so this option
850 can be used to collect statistics in parallel builds. The report file is not
851 cleared, new data is appended to it, thus making possible to accumulate build
854 You can also use environment variables to control the process statistics reporting.
855 Setting ``CC_PRINT_PROC_STAT`` to ``1`` enables the feature, the report goes to
856 stdout in human readable format.
857 Setting ``CC_PRINT_PROC_STAT_FILE`` to a fully qualified file path makes it report
858 process statistics to the given file in the CSV format. Specifying a relative
859 path will likely lead to multiple files with the same name created in different
860 directories, since the path is relative to a changing working directory.
862 These environment variables are handy when you need to request the statistics
863 report without changing your build scripts or alter the existing set of compiler
864 options. Note that ``-fproc-stat-report`` take precedence over ``CC_PRINT_PROC_STAT``
865 and ``CC_PRINT_PROC_STAT_FILE``.
867 .. code-block:: console
869 $ export CC_PRINT_PROC_STAT=1
870 $ export CC_PRINT_PROC_STAT_FILE=~/project-build-proc-stat.csv
875 Clang options that don't fit neatly into other categories.
877 .. option:: -fgnuc-version=
879 This flag controls the value of ``__GNUC__`` and related macros. This flag
880 does not enable or disable any GCC extensions implemented in Clang. Setting
881 the version to zero causes Clang to leave ``__GNUC__`` and other
882 GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined.
886 When emitting a dependency file, use formatting conventions appropriate
887 for NMake or Jom. Ignored unless another option causes Clang to emit a
890 When Clang emits a dependency file (e.g., you supplied the -M option)
891 most filenames can be written to the file without any special formatting.
892 Different Make tools will treat different sets of characters as "special"
893 and use different conventions for telling the Make tool that the character
894 is actually part of the filename. Normally Clang uses backslash to "escape"
895 a special character, which is the convention used by GNU Make. The -MV
896 option tells Clang to put double-quotes around the entire filename, which
897 is the convention used by NMake and Jom.
899 .. option:: -femit-dwarf-unwind=<value>
901 When to emit DWARF unwind (EH frame) info. This is a Mach-O-specific option.
905 * ``no-compact-unwind`` - Only emit DWARF unwind when compact unwind encodings
906 aren't available. This is the default for arm64.
907 * ``always`` - Always emit DWARF unwind regardless.
908 * ``default`` - Use the platform-specific default (``always`` for all
909 non-arm64-platforms).
911 ``no-compact-unwind`` is a performance optimization -- Clang will emit smaller
912 object files that are more quickly processed by the linker. This may cause
913 binary compatibility issues on older x86_64 targets, however, so use it with
916 .. _configuration-files:
921 Configuration files group command-line options and allow all of them to be
922 specified just by referencing the configuration file. They may be used, for
923 example, to collect options required to tune compilation for particular
924 target, such as ``-L``, ``-I``, ``-l``, ``--sysroot``, codegen options, etc.
926 Configuration files can be either specified on the command line or loaded
927 from default locations. If both variants are present, the default configuration
928 files are loaded first.
930 The command line option ``--config=`` can be used to specify explicit
931 configuration files in a Clang invocation. If the option is used multiple times,
932 all specified files are loaded, in order. For example:
936 clang --config=/home/user/cfgs/testing.txt
937 clang --config=debug.cfg --config=runtimes.cfg
939 If the provided argument contains a directory separator, it is considered as
940 a file path, and options are read from that file. Otherwise the argument is
941 treated as a file name and is searched for sequentially in the directories:
945 - the directory where Clang executable resides.
947 Both user and system directories for configuration files are specified during
948 clang build using CMake parameters, ``CLANG_CONFIG_FILE_USER_DIR`` and
949 ``CLANG_CONFIG_FILE_SYSTEM_DIR`` respectively. The first file found is used.
950 It is an error if the required file cannot be found.
952 The default configuration files are searched for in the same directories
953 following the rules described in the next paragraphs. Loading default
954 configuration files can be disabled entirely via passing
955 the ``--no-default-config`` flag.
957 First, the algorithm searches for a configuration file named
958 ``<triple>-<driver>.cfg`` where `triple` is the triple for the target being
959 built for, and `driver` is the name of the currently used driver. The algorithm
960 first attempts to use the canonical name for the driver used, then falls back
961 to the one found in the executable name.
963 The following canonical driver names are used:
965 - ``clang`` for the ``gcc`` driver (used to compile C programs)
966 - ``clang++`` for the ``gxx`` driver (used to compile C++ programs)
967 - ``clang-cpp`` for the ``cpp`` driver (pure preprocessor)
968 - ``clang-cl`` for the ``cl`` driver
969 - ``flang`` for the ``flang`` driver
970 - ``clang-dxc`` for the ``dxc`` driver
972 For example, when calling ``x86_64-pc-linux-gnu-clang-g++``,
973 the driver will first attempt to use the configuration file named::
975 x86_64-pc-linux-gnu-clang++.cfg
977 If this file is not found, it will attempt to use the name found
978 in the executable instead::
980 x86_64-pc-linux-gnu-clang-g++.cfg
982 Note that options such as ``--driver-mode=``, ``--target=``, ``-m32`` affect
983 the search algorithm. For example, the aforementioned executable called with
984 ``-m32`` argument will instead search for::
986 i386-pc-linux-gnu-clang++.cfg
988 If none of the aforementioned files are found, the driver will instead search
989 for separate driver and target configuration files and attempt to load both.
990 The former is named ``<driver>.cfg`` while the latter is named
991 ``<triple>.cfg``. Similarly to the previous variants, the canonical driver name
992 will be preferred, and the compiler will fall back to the actual name.
994 For example, ``x86_64-pc-linux-gnu-clang-g++`` will attempt to load two
995 configuration files named respectively::
998 x86_64-pc-linux-gnu.cfg
1000 with fallback to trying::
1003 x86_64-pc-linux-gnu.cfg
1005 It is not an error if either of these files is not found.
1007 The configuration file consists of command-line options specified on one or
1008 more lines. Lines composed of whitespace characters only are ignored as well as
1009 lines in which the first non-blank character is ``#``. Long options may be split
1010 between several lines by a trailing backslash. Here is example of a
1015 # Several options on line
1016 -c --target=x86_64-unknown-linux-gnu
1018 # Long option split between lines
1019 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\
1022 # other config files may be included
1025 Files included by ``@file`` directives in configuration files are resolved
1026 relative to the including file. For example, if a configuration file
1027 ``~/.llvm/target.cfg`` contains the directive ``@os/linux.opts``, the file
1028 ``linux.opts`` is searched for in the directory ``~/.llvm/os``. Another way to
1029 include a file content is using the command line option ``--config=``. It works
1030 similarly but the included file is searched for using the rules for configuration
1033 To generate paths relative to the configuration file, the ``<CFGDIR>`` token may
1034 be used. This will expand to the absolute path of the directory containing the
1037 In cases where a configuration file is deployed alongside SDK contents, the
1038 SDK directory can remain fully portable by using ``<CFGDIR>`` prefixed paths.
1039 In this way, the user may only need to specify a root configuration file with
1040 ``--config=`` to establish every aspect of the SDK with the compiler:
1045 -isystem <CFGDIR>/include
1047 -T <CFGDIR>/ldscripts/link.ld
1049 Language and Target-Independent Features
1050 ========================================
1052 Controlling Errors and Warnings
1053 -------------------------------
1055 Clang provides a number of ways to control which code constructs cause
1056 it to emit errors and warning messages, and how they are displayed to
1059 Controlling How Clang Displays Diagnostics
1060 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1062 When Clang emits a diagnostic, it includes rich information in the
1063 output, and gives you fine-grain control over which information is
1064 printed. Clang has the ability to print this information, and these are
1065 the options that control it:
1067 #. A file/line/column indicator that shows exactly where the diagnostic
1068 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
1069 :ref:`-fshow-source-location <opt_fshow-source-location>`].
1070 #. A categorization of the diagnostic as a note, warning, error, or
1072 #. A text string that describes what the problem is.
1073 #. An option that indicates how to control the diagnostic (for
1074 diagnostics that support it)
1075 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
1076 #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
1077 for clients that want to group diagnostics by class (for diagnostics
1079 [:option:`-fdiagnostics-show-category`].
1080 #. The line of source code that the issue occurs on, along with a caret
1081 and ranges that indicate the important locations
1082 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
1083 #. "FixIt" information, which is a concise explanation of how to fix the
1084 problem (when Clang is certain it knows)
1085 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
1086 #. A machine-parsable representation of the ranges involved (off by
1088 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
1090 For more information please see :ref:`Formatting of
1091 Diagnostics <cl_diag_formatting>`.
1096 All diagnostics are mapped into one of these 6 classes:
1105 .. _diagnostics_categories:
1107 Diagnostic Categories
1108 ^^^^^^^^^^^^^^^^^^^^^
1110 Though not shown by default, diagnostics may each be associated with a
1111 high-level category. This category is intended to make it possible to
1112 triage builds that produce a large number of errors or warnings in a
1115 Categories are not shown by default, but they can be turned on with the
1116 :option:`-fdiagnostics-show-category` option.
1117 When set to "``name``", the category is printed textually in the
1118 diagnostic output. When it is set to "``id``", a category number is
1119 printed. The mapping of category names to category id's can be obtained
1120 by running '``clang --print-diagnostic-categories``'.
1122 Controlling Diagnostics via Command Line Flags
1123 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1125 TODO: -W flags, -pedantic, etc
1127 .. _pragma_gcc_diagnostic:
1129 Controlling Diagnostics via Pragmas
1130 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1132 Clang can also control what diagnostics are enabled through the use of
1133 pragmas in the source code. This is useful for turning off specific
1134 warnings in a section of source code. Clang supports GCC's pragma for
1135 compatibility with existing source code, as well as several extensions.
1137 The pragma may control any warning that can be used from the command
1138 line. Warnings may be set to ignored, warning, error, or fatal. The
1139 following example code will tell Clang or GCC to ignore the -Wall
1144 #pragma GCC diagnostic ignored "-Wall"
1146 In addition to all of the functionality provided by GCC's pragma, Clang
1147 also allows you to push and pop the current warning state. This is
1148 particularly useful when writing a header file that will be compiled by
1149 other people, because you don't know what warning flags they build with.
1151 In the below example :option:`-Wextra-tokens` is ignored for only a single line
1152 of code, after which the diagnostics return to whatever state had previously
1158 #endif foo // warning: extra tokens at end of #endif directive
1160 #pragma clang diagnostic push
1161 #pragma clang diagnostic ignored "-Wextra-tokens"
1164 #endif foo // no warning
1166 #pragma clang diagnostic pop
1168 The push and pop pragmas will save and restore the full diagnostic state
1169 of the compiler, regardless of how it was set. That means that it is
1170 possible to use push and pop around GCC compatible diagnostics and Clang
1171 will push and pop them appropriately, while GCC will ignore the pushes
1172 and pops as unknown pragmas. It should be noted that while Clang
1173 supports the GCC pragma, Clang and GCC do not support the exact same set
1174 of warnings, so even when using GCC compatible #pragmas there is no
1175 guarantee that they will have identical behaviour on both compilers.
1177 In addition to controlling warnings and errors generated by the compiler, it is
1178 possible to generate custom warning and error messages through the following
1183 // The following will produce warning messages
1184 #pragma message "some diagnostic message"
1185 #pragma GCC warning "TODO: replace deprecated feature"
1187 // The following will produce an error message
1188 #pragma GCC error "Not supported"
1190 These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
1191 directives, except that they may also be embedded into preprocessor macros via
1192 the C99 ``_Pragma`` operator, for example:
1197 #define DEFER(M,...) M(__VA_ARGS__)
1198 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
1200 CUSTOM_ERROR("Feature not available");
1202 Controlling Diagnostics in System Headers
1203 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1205 Warnings are suppressed when they occur in system headers. By default,
1206 an included file is treated as a system header if it is found in an
1207 include path specified by ``-isystem``, but this can be overridden in
1210 The ``system_header`` pragma can be used to mark the current file as
1211 being a system header. No warnings will be produced from the location of
1212 the pragma onwards within the same file.
1217 #endif foo // warning: extra tokens at end of #endif directive
1219 #pragma clang system_header
1222 #endif foo // no warning
1224 The `--system-header-prefix=` and `--no-system-header-prefix=`
1225 command-line arguments can be used to override whether subsets of an include
1226 path are treated as system headers. When the name in a ``#include`` directive
1227 is found within a header search path and starts with a system prefix, the
1228 header is treated as a system header. The last prefix on the
1229 command-line which matches the specified header name takes precedence.
1232 .. code-block:: console
1234 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
1235 --no-system-header-prefix=x/y/
1237 Here, ``#include "x/a.h"`` is treated as including a system header, even
1238 if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
1239 as not including a system header, even if the header is found in
1242 A ``#include`` directive which finds a file relative to the current
1243 directory is treated as including a system header if the including file
1244 is treated as a system header.
1246 Controlling Deprecation Diagnostics in Clang-Provided C Runtime Headers
1247 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1249 Clang is responsible for providing some of the C runtime headers that cannot be
1250 provided by a platform CRT, such as implementation limits or when compiling in
1251 freestanding mode. Define the ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro
1252 prior to including such a C runtime header to disable the deprecation warnings.
1253 Note that the C Standard Library headers are allowed to transitively include
1254 other standard library headers (see 7.1.2p5), and so the most appropriate use
1255 of this macro is to set it within the build system using ``-D`` or before any
1256 include directives in the translation unit.
1260 #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
1261 #include <stdint.h> // Clang CRT deprecation warnings are disabled.
1262 #include <stdatomic.h> // Clang CRT deprecation warnings are disabled.
1264 .. _diagnostics_enable_everything:
1266 Enabling All Diagnostics
1267 ^^^^^^^^^^^^^^^^^^^^^^^^
1269 In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
1270 by passing :option:`-Weverything`. This works as expected with
1271 :option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some
1272 diagnostics contradict each other, therefore, users of :option:`-Weverything`
1273 often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat`
1274 because they contradict recent C++ standards.
1276 Since :option:`-Weverything` enables every diagnostic, we generally don't
1277 recommend using it. `-Wall` `-Wextra` are a better choice for most projects.
1278 Using :option:`-Weverything` means that updating your compiler is more difficult
1279 because you're exposed to experimental diagnostics which might be of lower
1280 quality than the default ones. If you do use :option:`-Weverything` then we
1281 advise that you address all new compiler diagnostics as they get added to Clang,
1282 either by fixing everything they find or explicitly disabling that diagnostic
1283 with its corresponding `Wno-` option.
1285 Note that when combined with :option:`-w` (which disables all warnings),
1286 disabling all warnings wins.
1288 Controlling Static Analyzer Diagnostics
1289 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1291 While not strictly part of the compiler, the diagnostics from Clang's
1292 `static analyzer <https://clang-analyzer.llvm.org>`_ can also be
1293 influenced by the user via changes to the source code. See the available
1294 `annotations <https://clang-analyzer.llvm.org/annotations.html>`_ and the
1296 page <https://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
1299 .. _usersmanual-precompiled-headers:
1304 `Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_
1305 are a general approach employed by many compilers to reduce compilation
1306 time. The underlying motivation of the approach is that it is common for
1307 the same (and often large) header files to be included by multiple
1308 source files. Consequently, compile times can often be greatly improved
1309 by caching some of the (redundant) work done by a compiler to process
1310 headers. Precompiled header files, which represent one of many ways to
1311 implement this optimization, are literally files that represent an
1312 on-disk cache that contains the vital information necessary to reduce
1313 some of the work needed to process a corresponding header file. While
1314 details of precompiled headers vary between compilers, precompiled
1315 headers have been shown to be highly effective at speeding up program
1316 compilation on systems with very large system headers (e.g., macOS).
1318 Generating a PCH File
1319 ^^^^^^^^^^^^^^^^^^^^^
1321 To generate a PCH file using Clang, one invokes Clang with the
1322 `-x <language>-header` option. This mirrors the interface in GCC
1323 for generating PCH files:
1325 .. code-block:: console
1327 $ gcc -x c-header test.h -o test.h.gch
1328 $ clang -x c-header test.h -o test.h.pch
1333 A PCH file can then be used as a prefix header when a ``-include-pch``
1334 option is passed to ``clang``:
1336 .. code-block:: console
1338 $ clang -include-pch test.h.pch test.c -o test
1340 The ``clang`` driver will check if the PCH file ``test.h.pch`` is
1341 available; if so, the contents of ``test.h`` (and the files it includes)
1342 will be processed from the PCH file. Otherwise, Clang will report an error.
1346 Clang does *not* automatically use PCH files for headers that are directly
1347 included within a source file or indirectly via :option:`-include`.
1350 .. code-block:: console
1352 $ clang -x c-header test.h -o test.h.pch
1355 $ clang test.c -o test
1357 In this example, ``clang`` will not automatically use the PCH file for
1358 ``test.h`` since ``test.h`` was included directly in the source file and not
1359 specified on the command line using ``-include-pch``.
1361 Relocatable PCH Files
1362 ^^^^^^^^^^^^^^^^^^^^^
1364 It is sometimes necessary to build a precompiled header from headers
1365 that are not yet in their final, installed locations. For example, one
1366 might build a precompiled header within the build tree that is then
1367 meant to be installed alongside the headers. Clang permits the creation
1368 of "relocatable" precompiled headers, which are built with a given path
1369 (into the build directory) and can later be used from an installed
1372 To build a relocatable precompiled header, place your headers into a
1373 subdirectory whose structure mimics the installed location. For example,
1374 if you want to build a precompiled header for the header ``mylib.h``
1375 that will be installed into ``/usr/include``, create a subdirectory
1376 ``build/usr/include`` and place the header ``mylib.h`` into that
1377 subdirectory. If ``mylib.h`` depends on other headers, then they can be
1378 stored within ``build/usr/include`` in a way that mimics the installed
1381 Building a relocatable precompiled header requires two additional
1382 arguments. First, pass the ``--relocatable-pch`` flag to indicate that
1383 the resulting PCH file should be relocatable. Second, pass
1384 ``-isysroot /path/to/build``, which makes all includes for your library
1385 relative to the build directory. For example:
1387 .. code-block:: console
1389 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
1391 When loading the relocatable PCH file, the various headers used in the
1392 PCH file are found from the system header root. For example, ``mylib.h``
1393 can be found in ``/usr/include/mylib.h``. If the headers are installed
1394 in some other system root, the ``-isysroot`` option can be used provide
1395 a different system root from which the headers will be based. For
1396 example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
1397 ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
1399 Relocatable precompiled headers are intended to be used in a limited
1400 number of cases where the compilation environment is tightly controlled
1401 and the precompiled header cannot be generated after headers have been
1404 .. _controlling-fp-behavior:
1406 Controlling Floating Point Behavior
1407 -----------------------------------
1409 Clang provides a number of ways to control floating point behavior, including
1410 with command line options and source pragmas. This section
1411 describes the various floating point semantic modes and the corresponding options.
1413 .. csv-table:: Floating Point Semantic Modes
1414 :header: "Mode", "Values"
1417 "ffp-exception-behavior", "{ignore, strict, maytrap}",
1418 "fenv_access", "{off, on}", "(none)"
1419 "frounding-math", "{dynamic, tonearest, downward, upward, towardzero}"
1420 "ffp-contract", "{on, off, fast, fast-honor-pragmas}"
1421 "fdenormal-fp-math", "{IEEE, PreserveSign, PositiveZero}"
1422 "fdenormal-fp-math-fp32", "{IEEE, PreserveSign, PositiveZero}"
1423 "fmath-errno", "{on, off}"
1424 "fhonor-nans", "{on, off}"
1425 "fhonor-infinities", "{on, off}"
1426 "fsigned-zeros", "{on, off}"
1427 "freciprocal-math", "{on, off}"
1428 "allow_approximate_fns", "{on, off}"
1429 "fassociative-math", "{on, off}"
1431 This table describes the option settings that correspond to the three
1432 floating point semantic models: precise (the default), strict, and fast.
1435 .. csv-table:: Floating Point Models
1436 :header: "Mode", "Precise", "Strict", "Fast"
1437 :widths: 25, 15, 15, 15
1439 "except_behavior", "ignore", "strict", "ignore"
1440 "fenv_access", "off", "on", "off"
1441 "rounding_mode", "tonearest", "dynamic", "tonearest"
1442 "contract", "on", "off", "fast"
1443 "denormal_fp_math", "IEEE", "IEEE", "IEEE"
1444 "denormal_fp32_math", "IEEE","IEEE", "IEEE"
1445 "support_math_errno", "on", "on", "off"
1446 "no_honor_nans", "off", "off", "on"
1447 "no_honor_infinities", "off", "off", "on"
1448 "no_signed_zeros", "off", "off", "on"
1449 "allow_reciprocal", "off", "off", "on"
1450 "allow_approximate_fns", "off", "off", "on"
1451 "allow_reassociation", "off", "off", "on"
1453 .. option:: -ffast-math
1455 Enable fast-math mode. This option lets the
1456 compiler make aggressive, potentially-lossy assumptions about
1457 floating-point math. These include:
1459 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1460 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1461 ``(a + b) * c == a * c + b * c``),
1462 * Operands to floating-point operations are not equal to ``NaN`` and
1464 * ``+0`` and ``-0`` are interchangeable.
1466 ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor
1467 macro. Some math libraries recognize this macro and change their behavior.
1468 With the exception of ``-ffp-contract=fast``, using any of the options
1469 below to disable any of the individual optimizations in ``-ffast-math``
1470 will cause ``__FAST_MATH__`` to no longer be set.
1472 This option implies:
1474 * ``-fno-honor-infinities``
1476 * ``-fno-honor-nans``
1480 * ``-fno-math-errno``
1482 * ``-ffinite-math-only``
1484 * ``-fassociative-math``
1486 * ``-freciprocal-math``
1488 * ``-fno-signed-zeros``
1490 * ``-fno-trapping-math``
1492 * ``-fno-rounding-math``
1494 * ``-ffp-contract=fast``
1496 Note: ``-ffast-math`` causes ``crtfastmath.o`` to be linked with code. See
1497 :ref:`crtfastmath.o` for more details.
1499 .. option:: -fno-fast-math
1501 Disable fast-math mode. This options disables unsafe floating-point
1502 optimizations by preventing the compiler from making any transformations that
1503 could affect the results.
1505 This option implies:
1507 * ``-fhonor-infinities``
1511 * ``-fno-approx-func``
1513 * ``-fno-finite-math-only``
1515 * ``-fno-associative-math``
1517 * ``-fno-reciprocal-math``
1519 * ``-fsigned-zeros``
1521 * ``-ffp-contract=on``
1523 Also, this option resets following options to their target-dependent defaults.
1525 * ``-f[no-]math-errno``
1526 * ``-fdenormal-fp-math=<value>``
1528 There is ambiguity about how ``-ffp-contract``, ``-ffast-math``,
1529 and ``-fno-fast-math`` behave when combined. To keep the value of
1530 ``-ffp-contract`` consistent, we define this set of rules:
1532 * ``-ffast-math`` sets ``ffp-contract`` to ``fast``.
1534 * ``-fno-fast-math`` sets ``-ffp-contract`` to ``on`` (``fast`` for CUDA and
1537 * If ``-ffast-math`` and ``-ffp-contract`` are both seen, but
1538 ``-ffast-math`` is not followed by ``-fno-fast-math``, ``ffp-contract``
1539 will be given the value of whichever option was last seen.
1541 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has been seen at least
1542 once, the ``ffp-contract`` will get the value of the last seen value of
1545 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has not been seen, the
1546 ``-ffp-contract`` setting is determined by the default value of
1549 Note: ``-fno-fast-math`` implies ``-fdenormal-fp-math=ieee``.
1550 ``-fno-fast-math`` causes ``crtfastmath.o`` to not be linked with code.
1552 .. option:: -fdenormal-fp-math=<value>
1554 Select which denormal numbers the code is permitted to require.
1558 * ``ieee`` - IEEE 754 denormal numbers
1559 * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 0
1560 * ``positive-zero`` - denormals are flushed to positive zero
1562 The default value depends on the target. For most targets, defaults to
1565 .. option:: -f[no-]strict-float-cast-overflow
1567 When a floating-point value is not representable in a destination integer
1568 type, the code has undefined behavior according to the language standard.
1569 By default, Clang will not guarantee any particular result in that case.
1570 With the 'no-strict' option, Clang will saturate towards the smallest and
1571 largest representable integer values instead. NaNs will be converted to zero.
1572 Defaults to ``-fstrict-float-cast-overflow``.
1574 .. option:: -f[no-]math-errno
1576 Require math functions to indicate errors by setting errno.
1577 The default varies by ToolChain. ``-fno-math-errno`` allows optimizations
1578 that might cause standard C math functions to not set ``errno``.
1579 For example, on some systems, the math function ``sqrt`` is specified
1580 as setting ``errno`` to ``EDOM`` when the input is negative. On these
1581 systems, the compiler cannot normally optimize a call to ``sqrt`` to use
1582 inline code (e.g. the x86 ``sqrtsd`` instruction) without additional
1583 checking to ensure that ``errno`` is set appropriately.
1584 ``-fno-math-errno`` permits these transformations.
1586 On some targets, math library functions never set ``errno``, and so
1587 ``-fno-math-errno`` is the default. This includes most BSD-derived
1588 systems, including Darwin.
1590 .. option:: -f[no-]trapping-math
1592 Control floating point exception behavior. ``-fno-trapping-math`` allows optimizations that assume that floating point operations cannot generate traps such as divide-by-zero, overflow and underflow.
1594 - The option ``-ftrapping-math`` behaves identically to ``-ffp-exception-behavior=strict``.
1595 - The option ``-fno-trapping-math`` behaves identically to ``-ffp-exception-behavior=ignore``. This is the default.
1597 .. option:: -ffp-contract=<value>
1599 Specify when the compiler is permitted to form fused floating-point
1600 operations, such as fused multiply-add (FMA). Fused operations are
1601 permitted to produce more precise results than performing the same
1602 operations separately.
1604 The C standard permits intermediate floating-point results within an
1605 expression to be computed with more precision than their type would
1606 normally allow. This permits operation fusing, and Clang takes advantage
1607 of this by default. This behavior can be controlled with the ``FP_CONTRACT``
1608 and ``clang fp contract`` pragmas. Please refer to the pragma documentation
1609 for a description of how the pragmas interact with this option.
1613 * ``fast`` (fuse across statements disregarding pragmas, default for CUDA)
1614 * ``on`` (fuse in the same statement unless dictated by pragmas, default for languages other than CUDA/HIP)
1615 * ``off`` (never fuse)
1616 * ``fast-honor-pragmas`` (fuse across statements unless dictated by pragmas, default for HIP)
1618 .. option:: -f[no-]honor-infinities
1620 Allow floating-point optimizations that assume arguments and results are
1622 Defaults to ``-fhonor-infinities``.
1624 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1625 has the same effect as specifying ``-ffinite-math-only``.
1627 .. option:: -f[no-]honor-nans
1629 Allow floating-point optimizations that assume arguments and results are
1631 Defaults to ``-fhonor-nans``.
1633 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1634 has the same effect as specifying ``-ffinite-math-only``.
1636 .. option:: -f[no-]approx-func
1638 Allow certain math function calls (such as ``log``, ``sqrt``, ``pow``, etc)
1639 to be replaced with an approximately equivalent set of instructions
1640 or alternative math function calls. For example, a ``pow(x, 0.25)``
1641 may be replaced with ``sqrt(sqrt(x))``, despite being an inexact result
1642 in cases where ``x`` is ``-0.0`` or ``-inf``.
1643 Defaults to ``-fno-approx-func``.
1645 .. option:: -f[no-]signed-zeros
1647 Allow optimizations that ignore the sign of floating point zeros.
1648 Defaults to ``-fsigned-zeros``.
1650 .. option:: -f[no-]associative-math
1652 Allow floating point operations to be reassociated.
1653 Defaults to ``-fno-associative-math``.
1655 .. option:: -f[no-]reciprocal-math
1657 Allow division operations to be transformed into multiplication by a
1658 reciprocal. This can be significantly faster than an ordinary division
1659 but can also have significantly less precision. Defaults to
1660 ``-fno-reciprocal-math``.
1662 .. option:: -f[no-]unsafe-math-optimizations
1664 Allow unsafe floating-point optimizations.
1665 ``-funsafe-math-optimizations`` also implies:
1668 * ``-fassociative-math``
1669 * ``-freciprocal-math``
1670 * ``-fno-signed-zeros``
1671 * ``-fno-trapping-math``
1672 * ``-ffp-contract=fast``
1674 ``-fno-unsafe-math-optimizations`` implies:
1676 * ``-fno-approx-func``
1677 * ``-fno-associative-math``
1678 * ``-fno-reciprocal-math``
1679 * ``-fsigned-zeros``
1680 * ``-ftrapping-math``
1681 * ``-ffp-contract=on``
1682 * ``-fdenormal-fp-math=ieee``
1684 There is ambiguity about how ``-ffp-contract``,
1685 ``-funsafe-math-optimizations``, and ``-fno-unsafe-math-optimizations``
1686 behave when combined. Explanation in :option:`-fno-fast-math` also applies
1689 Defaults to ``-fno-unsafe-math-optimizations``.
1691 .. option:: -f[no-]finite-math-only
1693 Allow floating-point optimizations that assume arguments and results are
1694 not NaNs or +-Inf. ``-ffinite-math-only`` defines the
1695 ``__FINITE_MATH_ONLY__`` preprocessor macro.
1696 ``-ffinite-math-only`` implies:
1698 * ``-fno-honor-infinities``
1699 * ``-fno-honor-nans``
1701 ``-ffno-inite-math-only`` implies:
1703 * ``-fhonor-infinities``
1706 Defaults to ``-fno-finite-math-only``.
1708 .. option:: -f[no-]rounding-math
1710 Force floating-point operations to honor the dynamically-set rounding mode by default.
1712 The result of a floating-point operation often cannot be exactly represented in the result type and therefore must be rounded. IEEE 754 describes different rounding modes that control how to perform this rounding, not all of which are supported by all implementations. C provides interfaces (``fesetround`` and ``fesetenv``) for dynamically controlling the rounding mode, and while it also recommends certain conventions for changing the rounding mode, these conventions are not typically enforced in the ABI. Since the rounding mode changes the numerical result of operations, the compiler must understand something about it in order to optimize floating point operations.
1714 Note that floating-point operations performed as part of constant initialization are formally performed prior to the start of the program and are therefore not subject to the current rounding mode. This includes the initialization of global variables and local ``static`` variables. Floating-point operations in these contexts will be rounded using ``FE_TONEAREST``.
1716 - The option ``-fno-rounding-math`` allows the compiler to assume that the rounding mode is set to ``FE_TONEAREST``. This is the default.
1717 - The option ``-frounding-math`` forces the compiler to honor the dynamically-set rounding mode. This prevents optimizations which might affect results if the rounding mode changes or is different from the default; for example, it prevents floating-point operations from being reordered across most calls and prevents constant-folding when the result is not exactly representable.
1719 .. option:: -ffp-model=<value>
1721 Specify floating point behavior. ``-ffp-model`` is an umbrella
1722 option that encompasses functionality provided by other, single
1723 purpose, floating point options. Valid values are: ``precise``, ``strict``,
1727 * ``precise`` Disables optimizations that are not value-safe on floating-point data, although FP contraction (FMA) is enabled (``-ffp-contract=on``). This is the default behavior.
1728 * ``strict`` Enables ``-frounding-math`` and ``-ffp-exception-behavior=strict``, and disables contractions (FMA). All of the ``-ffast-math`` enablements are disabled. Enables ``STDC FENV_ACCESS``: by default ``FENV_ACCESS`` is disabled. This option setting behaves as though ``#pragma STDC FENV_ACCESS ON`` appeared at the top of the source file.
1729 * ``fast`` Behaves identically to specifying both ``-ffast-math`` and ``ffp-contract=fast``
1731 Note: If your command line specifies multiple instances
1732 of the ``-ffp-model`` option, or if your command line option specifies
1733 ``-ffp-model`` and later on the command line selects a floating point
1734 option that has the effect of negating part of the ``ffp-model`` that
1735 has been selected, then the compiler will issue a diagnostic warning
1736 that the override has occurred.
1738 .. option:: -ffp-exception-behavior=<value>
1740 Specify the floating-point exception behavior.
1742 Valid values are: ``ignore``, ``maytrap``, and ``strict``.
1743 The default value is ``ignore``. Details:
1745 * ``ignore`` The compiler assumes that the exception status flags will not be read and that floating point exceptions will be masked.
1746 * ``maytrap`` The compiler avoids transformations that may raise exceptions that would not have been raised by the original code. Constant folding performed by the compiler is exempt from this option.
1747 * ``strict`` The compiler ensures that all transformations strictly preserve the floating point exception semantics of the original code.
1749 .. option:: -ffp-eval-method=<value>
1751 Specify the floating-point evaluation method for intermediate results within
1752 a single expression of the code.
1754 Valid values are: ``source``, ``double``, and ``extended``.
1755 For 64-bit targets, the default value is ``source``. For 32-bit x86 targets
1756 however, in the case of NETBSD 6.99.26 and under, the default value is
1757 ``double``; in the case of NETBSD greater than 6.99.26, with NoSSE, the
1758 default value is ``extended``, with SSE the default value is ``source``.
1761 * ``source`` The compiler uses the floating-point type declared in the source program as the evaluation method.
1762 * ``double`` The compiler uses ``double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``double``.
1763 * ``extended`` The compiler uses ``long double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``long double``.
1765 .. option:: -f[no-]protect-parens
1767 This option pertains to floating-point types, complex types with
1768 floating-point components, and vectors of these types. Some arithmetic
1769 expression transformations that are mathematically correct and permissible
1770 according to the C and C++ language standards may be incorrect when dealing
1771 with floating-point types, such as reassociation and distribution. Further,
1772 the optimizer may ignore parentheses when computing arithmetic expressions
1773 in circumstances where the parenthesized and unparenthesized expression
1774 express the same mathematical value. For example (a+b)+c is the same
1775 mathematical value as a+(b+c), but the optimizer is free to evaluate the
1776 additions in any order regardless of the parentheses. When enabled, this
1777 option forces the optimizer to honor the order of operations with respect
1778 to parentheses in all circumstances.
1779 Defaults to ``-fno-protect-parens``.
1781 Note that floating-point contraction (option `-ffp-contract=`) is disabled
1782 when `-fprotect-parens` is enabled. Also note that in safe floating-point
1783 modes, such as `-ffp-model=precise` or `-ffp-model=strict`, this option
1784 has no effect because the optimizer is prohibited from making unsafe
1787 .. option:: -fexcess-precision:
1789 The C and C++ standards allow floating-point expressions to be computed as if
1790 intermediate results had more precision (and/or a wider range) than the type
1791 of the expression strictly allows. This is called excess precision
1793 Excess precision arithmetic can improve the accuracy of results (although not
1794 always), and it can make computation significantly faster if the target lacks
1795 direct hardware support for arithmetic in a particular type. However, it can
1796 also undermine strict floating-point reproducibility.
1798 Under the standards, assignments and explicit casts force the operand to be
1799 converted to its formal type, discarding any excess precision. Because data
1800 can only flow between statements via an assignment, this means that the use
1801 of excess precision arithmetic is a reliable local property of a single
1802 statement, and results do not change based on optimization. However, when
1803 excess precision arithmetic is in use, Clang does not guarantee strict
1804 reproducibility, and future compiler releases may recognize more
1805 opportunities to use excess precision arithmetic, e.g. with floating-point
1808 Clang does not use excess precision arithmetic for most types or on most
1809 targets. For example, even on pre-SSE X86 targets where ``float`` and
1810 ``double`` computations must be performed in the 80-bit X87 format, Clang
1811 rounds all intermediate results correctly for their type. Clang currently
1812 uses excess precision arithmetic by default only for the following types and
1815 * ``_Float16`` on X86 targets without ``AVX512-FP16``.
1817 The ``-fexcess-precision=<value>`` option can be used to control the use of
1818 excess precision arithmetic. Valid values are:
1820 * ``standard`` - The default. Allow the use of excess precision arithmetic
1821 under the constraints of the C and C++ standards. Has no effect except on
1822 the types and targets listed above.
1823 * ``fast`` - Accepted for GCC compatibility, but currently treated as an
1824 alias for ``standard``.
1825 * ``16`` - Forces ``_Float16`` operations to be emitted without using excess
1826 precision arithmetic.
1828 .. _floating-point-environment:
1830 Accessing the floating point environment
1831 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1832 Many targets allow floating point operations to be configured to control things
1833 such as how inexact results should be rounded and how exceptional conditions
1834 should be handled. This configuration is called the floating point environment.
1835 C and C++ restrict access to the floating point environment by default, and the
1836 compiler is allowed to assume that all operations are performed in the default
1837 environment. When code is compiled in this default mode, operations that depend
1838 on the environment (such as floating-point arithmetic and `FLT_ROUNDS`) may have
1839 undefined behavior if the dynamic environment is not the default environment; for
1840 example, `FLT_ROUNDS` may or may not simply return its default value for the target
1841 instead of reading the dynamic environment, and floating-point operations may be
1842 optimized as if the dynamic environment were the default. Similarly, it is undefined
1843 behavior to change the floating point environment in this default mode, for example
1844 by calling the `fesetround` function.
1845 C provides two pragmas to allow code to dynamically modify the floating point environment:
1847 - ``#pragma STDC FENV_ACCESS ON`` allows dynamic changes to the entire floating
1850 - ``#pragma STDC FENV_ROUND FE_DYNAMIC`` allows dynamic changes to just the floating
1851 point rounding mode. This may be more optimizable than ``FENV_ACCESS ON`` because
1852 the compiler can still ignore the possibility of floating-point exceptions by default.
1854 Both of these can be used either at the start of a block scope, in which case
1855 they cover all code in that scope (unless they're turned off in a child scope),
1856 or at the top level in a file, in which case they cover all subsequent function
1857 bodies until they're turned off. Note that it is undefined behavior to enter
1858 code that is *not* covered by one of these pragmas from code that *is* covered
1859 by one of these pragmas unless the floating point environment has been restored
1860 to its default state. See the C standard for more information about these pragmas.
1862 The command line option ``-frounding-math`` behaves as if the translation unit
1863 began with ``#pragma STDC FENV_ROUND FE_DYNAMIC``. The command line option
1864 ``-ffp-model=strict`` behaves as if the translation unit began with ``#pragma STDC FENV_ACCESS ON``.
1866 Code that just wants to use a specific rounding mode for specific floating point
1867 operations can avoid most of the hazards of the dynamic floating point environment
1868 by using ``#pragma STDC FENV_ROUND`` with a value other than ``FE_DYNAMIC``.
1872 A note about ``crtfastmath.o``
1873 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1874 ``-ffast-math`` and ``-funsafe-math-optimizations`` cause ``crtfastmath.o`` to be
1875 automatically linked, which adds a static constructor that sets the FTZ/DAZ
1876 bits in MXCSR, affecting not only the current compilation unit but all static
1877 and shared libraries included in the program.
1879 .. _FLT_EVAL_METHOD:
1881 A note about ``__FLT_EVAL_METHOD__``
1882 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1883 The ``__FLT_EVAL_METHOD__`` is not defined as a traditional macro, and so it
1884 will not appear when dumping preprocessor macros. Instead, the value
1885 ``__FLT_EVAL_METHOD__`` expands to is determined at the point of expansion
1886 either from the value set by the ``-ffp-eval-method`` command line option or
1887 from the target. This is because the ``__FLT_EVAL_METHOD__`` macro
1888 cannot expand to the correct evaluation method in the presence of a ``#pragma``
1889 which alters the evaluation method. An error is issued if
1890 ``__FLT_EVAL_METHOD__`` is expanded inside a scope modified by
1891 ``#pragma clang fp eval_method``.
1893 .. _fp-constant-eval:
1895 A note about Floating Point Constant Evaluation
1896 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1898 In C, the only place floating point operations are guaranteed to be evaluated
1899 during translation is in the initializers of variables of static storage
1900 duration, which are all notionally initialized before the program begins
1901 executing (and thus before a non-default floating point environment can be
1902 entered). But C++ has many more contexts where floating point constant
1903 evaluation occurs. Specifically: for static/thread-local variables,
1904 first try evaluating the initializer in a constant context, including in the
1905 constant floating point environment (just like in C), and then, if that fails,
1906 fall back to emitting runtime code to perform the initialization (which might
1907 in general be in a different floating point environment).
1909 Consider this example when compiled with ``-frounding-math``
1911 .. code-block:: console
1913 constexpr float func_01(float x, float y) {
1916 float V1 = func_01(1.0F, 0x0.000001p0F);
1918 The C++ rule is that initializers for static storage duration variables are
1919 first evaluated during translation (therefore, in the default rounding mode),
1920 and only evaluated at runtime (and therefore in the runtime rounding mode) if
1921 the compile-time evaluation fails. This is in line with the C rules;
1922 C11 F.8.5 says: *All computation for automatic initialization is done (as if)
1923 at execution time; thus, it is affected by any operative modes and raises
1924 floating-point exceptions as required by IEC 60559 (provided the state for the
1925 FENV_ACCESS pragma is ‘‘on’’). All computation for initialization of objects
1926 that have static or thread storage duration is done (as if) at translation
1927 time.* C++ generalizes this by adding another phase of initialization
1928 (at runtime) if the translation-time initialization fails, but the
1929 translation-time evaluation of the initializer of succeeds, it will be
1930 treated as a constant initializer.
1933 .. _controlling-code-generation:
1935 Controlling Code Generation
1936 ---------------------------
1938 Clang provides a number of ways to control code generation. The options
1941 .. option:: -f[no-]sanitize=check1,check2,...
1943 Turn on runtime checks for various forms of undefined or suspicious
1946 This option controls whether Clang adds runtime checks for various
1947 forms of undefined or suspicious behavior, and is disabled by
1948 default. If a check fails, a diagnostic message is produced at
1949 runtime explaining the problem. The main checks are:
1951 - .. _opt_fsanitize_address:
1953 ``-fsanitize=address``:
1954 :doc:`AddressSanitizer`, a memory error
1956 - .. _opt_fsanitize_thread:
1958 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
1959 - .. _opt_fsanitize_memory:
1961 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
1962 a detector of uninitialized reads. Requires instrumentation of all
1964 - .. _opt_fsanitize_undefined:
1966 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
1967 a fast and compatible undefined behavior checker.
1969 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
1971 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
1972 checks. Requires ``-flto``.
1973 - ``-fsanitize=kcfi``: kernel indirect call forward-edge control flow
1975 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
1976 protection against stack-based memory corruption errors.
1978 There are more fine-grained checks available: see
1979 the :ref:`list <ubsan-checks>` of specific kinds of
1980 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
1981 of control flow integrity schemes.
1983 The ``-fsanitize=`` argument must also be provided when linking, in
1984 order to link to the appropriate runtime library.
1986 It is not possible to combine more than one of the ``-fsanitize=address``,
1987 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
1990 .. option:: -f[no-]sanitize-recover=check1,check2,...
1992 .. option:: -f[no-]sanitize-recover[=all]
1994 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
1995 If the check is fatal, program will halt after the first error
1996 of this kind is detected and error report is printed.
1998 By default, non-fatal checks are those enabled by
1999 :doc:`UndefinedBehaviorSanitizer`,
2000 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
2001 sanitizers may not support recovery (or not support it by default
2002 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
2005 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
2006 This means that if a check has been configured to trap elsewhere on the
2007 command line, or if the check traps by default, this flag will not have
2008 any effect unless that sanitizer's trapping behavior is disabled with
2009 ``-fno-sanitize-trap``.
2011 For example, if a command line contains the flags ``-fsanitize=undefined
2012 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
2013 will have no effect on its own; it will need to be accompanied by
2014 ``-fno-sanitize-trap=alignment``.
2016 .. option:: -f[no-]sanitize-trap=check1,check2,...
2018 .. option:: -f[no-]sanitize-trap[=all]
2020 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
2021 option is intended for use in cases where the sanitizer runtime cannot
2022 be used (for instance, when building libc or a kernel module), or where
2023 the binary size increase caused by the sanitizer runtime is a concern.
2025 This flag is only compatible with :doc:`control flow integrity
2026 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
2027 checks other than ``vptr``.
2029 This flag is enabled by default for sanitizers in the ``cfi`` group.
2031 .. option:: -fsanitize-ignorelist=/path/to/ignorelist/file
2033 Disable or modify sanitizer checks for objects (source files, functions,
2034 variables, types) listed in the file. See
2035 :doc:`SanitizerSpecialCaseList` for file format description.
2037 .. option:: -fno-sanitize-ignorelist
2039 Don't use ignorelist file, if it was specified earlier in the command line.
2041 .. option:: -f[no-]sanitize-coverage=[type,features,...]
2043 Enable simple code coverage in addition to certain sanitizers.
2044 See :doc:`SanitizerCoverage` for more details.
2046 .. option:: -f[no-]sanitize-address-outline-instrumentation
2048 Controls how address sanitizer code is generated. If enabled will always use
2049 a function call instead of inlining the code. Turning this option on could
2050 reduce the binary size, but might result in a worse run-time performance.
2052 See :doc: `AddressSanitizer` for more details.
2054 .. option:: -f[no-]sanitize-stats
2056 Enable simple statistics gathering for the enabled sanitizers.
2057 See :doc:`SanitizerStats` for more details.
2059 .. option:: -fsanitize-undefined-trap-on-error
2061 Deprecated alias for ``-fsanitize-trap=undefined``.
2063 .. option:: -fsanitize-cfi-cross-dso
2065 Enable cross-DSO control flow integrity checks. This flag modifies
2066 the behavior of sanitizers in the ``cfi`` group to allow checking
2067 of cross-DSO virtual and indirect calls.
2069 .. option:: -fsanitize-cfi-icall-generalize-pointers
2071 Generalize pointers in return and argument types in function type signatures
2072 checked by Control Flow Integrity indirect call checking. See
2073 :doc:`ControlFlowIntegrity` for more details.
2075 .. option:: -fsanitize-cfi-icall-experimental-normalize-integers
2077 Normalize integers in return and argument types in function type signatures
2078 checked by Control Flow Integrity indirect call checking. See
2079 :doc:`ControlFlowIntegrity` for more details.
2081 This option is currently experimental.
2083 .. option:: -fstrict-vtable-pointers
2085 Enable optimizations based on the strict rules for overwriting polymorphic
2086 C++ objects, i.e. the vptr is invariant during an object's lifetime.
2087 This enables better devirtualization. Turned off by default, because it is
2090 .. option:: -fwhole-program-vtables
2092 Enable whole-program vtable optimizations, such as single-implementation
2093 devirtualization and virtual constant propagation, for classes with
2094 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
2096 .. option:: -f[no]split-lto-unit
2098 Controls splitting the :doc:`LTO unit <LTOVisibility>` into regular LTO and
2099 :doc:`ThinLTO` portions, when compiling with -flto=thin. Defaults to false
2100 unless ``-fsanitize=cfi`` or ``-fwhole-program-vtables`` are specified, in
2101 which case it defaults to true. Splitting is required with ``fsanitize=cfi``,
2102 and it is an error to disable via ``-fno-split-lto-unit``. Splitting is
2103 optional with ``-fwhole-program-vtables``, however, it enables more
2104 aggressive whole program vtable optimizations (specifically virtual constant
2107 When enabled, vtable definitions and select virtual functions are placed
2108 in the split regular LTO module, enabling more aggressive whole program
2109 vtable optimizations required for CFI and virtual constant propagation.
2110 However, this can increase the LTO link time and memory requirements over
2111 pure ThinLTO, as all split regular LTO modules are merged and LTO linked
2114 .. option:: -fforce-emit-vtables
2116 In order to improve devirtualization, forces emitting of vtables even in
2117 modules where it isn't necessary. It causes more inline virtual functions
2120 .. option:: -fno-assume-sane-operator-new
2122 Don't assume that the C++'s new operator is sane.
2124 This option tells the compiler to do not assume that C++'s global
2125 new operator will always return a pointer that does not alias any
2126 other pointer when the function returns.
2128 .. option:: -ftrap-function=[name]
2130 Instruct code generator to emit a function call to the specified
2131 function name for ``__builtin_trap()``.
2133 LLVM code generator translates ``__builtin_trap()`` to a trap
2134 instruction if it is supported by the target ISA. Otherwise, the
2135 builtin is translated into a call to ``abort``. If this option is
2136 set, then the code generator will always lower the builtin to a call
2137 to the specified function regardless of whether the target ISA has a
2138 trap instruction. This option is useful for environments (e.g.
2139 deeply embedded) where a trap cannot be properly handled, or when
2140 some custom behavior is desired.
2142 .. option:: -ftls-model=[model]
2144 Select which TLS model to use.
2146 Valid values are: ``global-dynamic``, ``local-dynamic``,
2147 ``initial-exec`` and ``local-exec``. The default value is
2148 ``global-dynamic``. The compiler may use a different model if the
2149 selected model is not supported by the target, or if a more
2150 efficient model can be used. The TLS model can be overridden per
2151 variable using the ``tls_model`` attribute.
2153 .. option:: -femulated-tls
2155 Select emulated TLS model, which overrides all -ftls-model choices.
2157 In emulated TLS mode, all access to TLS variables are converted to
2158 calls to __emutls_get_address in the runtime library.
2160 .. option:: -mhwdiv=[values]
2162 Select the ARM modes (arm or thumb) that support hardware division
2165 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
2166 This option is used to indicate which mode (arm or thumb) supports
2167 hardware division instructions. This only applies to the ARM
2170 .. option:: -m[no-]crc
2172 Enable or disable CRC instructions.
2174 This option is used to indicate whether CRC instructions are to
2175 be generated. This only applies to the ARM architecture.
2177 CRC instructions are enabled by default on ARMv8.
2179 .. option:: -mgeneral-regs-only
2181 Generate code which only uses the general purpose registers.
2183 This option restricts the generated code to use general registers
2184 only. This only applies to the AArch64 architecture.
2186 .. option:: -mcompact-branches=[values]
2188 Control the usage of compact branches for MIPSR6.
2190 Valid values are: ``never``, ``optimal`` and ``always``.
2191 The default value is ``optimal`` which generates compact branches
2192 when a delay slot cannot be filled. ``never`` disables the usage of
2193 compact branches and ``always`` generates compact branches whenever
2196 .. option:: -f[no-]max-type-align=[number]
2198 Instruct the code generator to not enforce a higher alignment than the given
2199 number (of bytes) when accessing memory via an opaque pointer or reference.
2200 This cap is ignored when directly accessing a variable or when the pointee
2201 type has an explicit “aligned” attribute.
2203 The value should usually be determined by the properties of the system allocator.
2204 Some builtin types, especially vector types, have very high natural alignments;
2205 when working with values of those types, Clang usually wants to use instructions
2206 that take advantage of that alignment. However, many system allocators do
2207 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
2208 this option to limit the alignment that the compiler can assume for an arbitrary
2209 pointer, which may point onto the heap.
2211 This option does not affect the ABI alignment of types; the layout of structs and
2212 unions and the value returned by the alignof operator remain the same.
2214 This option can be overridden on a case-by-case basis by putting an explicit
2215 “aligned” alignment on a struct, union, or typedef. For example:
2217 .. code-block:: console
2219 #include <immintrin.h>
2220 // Make an aligned typedef of the AVX-512 16-int vector type.
2221 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
2223 void initialize_vector(__aligned_v16si *v) {
2224 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
2225 // value of -fmax-type-align.
2228 .. option:: -faddrsig, -fno-addrsig
2230 Controls whether Clang emits an address-significance table into the object
2231 file. Address-significance tables allow linkers to implement `safe ICF
2232 <https://research.google.com/pubs/archive/36912.pdf>`_ without the false
2233 positives that can result from other implementation techniques such as
2234 relocation scanning. Address-significance tables are enabled by default
2235 on ELF targets when using the integrated assembler. This flag currently
2236 only has an effect on ELF targets.
2238 .. option:: -f[no]-unique-internal-linkage-names
2240 Controls whether Clang emits a unique (best-effort) symbol name for internal
2241 linkage symbols. When this option is set, compiler hashes the main source
2242 file path from the command line and appends it to all internal symbols. If a
2243 program contains multiple objects compiled with the same command-line source
2244 file path, the symbols are not guaranteed to be unique. This option is
2245 particularly useful in attributing profile information to the correct
2246 function when multiple functions with the same private linkage name exist
2249 It should be noted that this option cannot guarantee uniqueness and the
2250 following is an example where it is not unique when two modules contain
2251 symbols with the same private linkage name:
2253 .. code-block:: console
2255 $ cd $P/foo && clang -c -funique-internal-linkage-names name_conflict.c
2256 $ cd $P/bar && clang -c -funique-internal-linkage-names name_conflict.c
2257 $ cd $P && clang foo/name_conflict.o && bar/name_conflict.o
2259 .. option:: -fbasic-block-sections=[labels, all, list=<arg>, none]
2261 Controls how Clang emits text sections for basic blocks. With values ``all``
2262 and ``list=<arg>``, each basic block or a subset of basic blocks can be placed
2263 in its own unique section. With the "labels" value, normal text sections are
2264 emitted, but a ``.bb_addr_map`` section is emitted which includes address
2265 offsets for each basic block in the program, relative to the parent function
2268 With the ``list=<arg>`` option, a file containing the subset of basic blocks
2269 that need to placed in unique sections can be specified. The format of the
2270 file is as follows. For example, ``list=spec.txt`` where ``spec.txt`` is the
2279 will place the machine basic block with ``id 2`` in function ``foo`` in a
2280 unique section. It will also place all basic blocks of functions ``bar``
2283 Further, section clusters can also be specified using the ``list=<arg>``
2284 option. For example, ``list=spec.txt`` where ``spec.txt`` contains:
2292 will create two unique sections for function ``foo`` with the first
2293 containing the odd numbered basic blocks and the second containing the
2294 even numbered basic blocks.
2296 Basic block sections allow the linker to reorder basic blocks and enables
2297 link-time optimizations like whole program inter-procedural basic block
2300 Profile Guided Optimization
2301 ---------------------------
2303 Profile information enables better optimization. For example, knowing that a
2304 branch is taken very frequently helps the compiler make better decisions when
2305 ordering basic blocks. Knowing that a function ``foo`` is called more
2306 frequently than another function ``bar`` helps the inliner. Optimization
2307 levels ``-O2`` and above are recommended for use of profile guided optimization.
2309 Clang supports profile guided optimization with two different kinds of
2310 profiling. A sampling profiler can generate a profile with very low runtime
2311 overhead, or you can build an instrumented version of the code that collects
2312 more detailed profile information. Both kinds of profiles can provide execution
2313 counts for instructions in the code and information on branches taken and
2314 function invocation.
2316 Regardless of which kind of profiling you use, be careful to collect profiles
2317 by running your code with inputs that are representative of the typical
2318 behavior. Code that is not exercised in the profile will be optimized as if it
2319 is unimportant, and the compiler may make poor optimization choices for code
2320 that is disproportionately used while profiling.
2322 Differences Between Sampling and Instrumentation
2323 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2325 Although both techniques are used for similar purposes, there are important
2326 differences between the two:
2328 1. Profile data generated with one cannot be used by the other, and there is no
2329 conversion tool that can convert one to the other. So, a profile generated
2330 via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
2331 Similarly, sampling profiles generated by external profilers must be
2332 converted and used with ``-fprofile-sample-use``.
2334 2. Instrumentation profile data can be used for code coverage analysis and
2337 3. Sampling profiles can only be used for optimization. They cannot be used for
2338 code coverage analysis. Although it would be technically possible to use
2339 sampling profiles for code coverage, sample-based profiles are too
2340 coarse-grained for code coverage purposes; it would yield poor results.
2342 4. Sampling profiles must be generated by an external tool. The profile
2343 generated by that tool must then be converted into a format that can be read
2344 by LLVM. The section on sampling profilers describes one of the supported
2345 sampling profile formats.
2348 Using Sampling Profilers
2349 ^^^^^^^^^^^^^^^^^^^^^^^^
2351 Sampling profilers are used to collect runtime information, such as
2352 hardware counters, while your application executes. They are typically
2353 very efficient and do not incur a large runtime overhead. The
2354 sample data collected by the profiler can be used during compilation
2355 to determine what the most executed areas of the code are.
2357 Using the data from a sample profiler requires some changes in the way
2358 a program is built. Before the compiler can use profiling information,
2359 the code needs to execute under the profiler. The following is the
2360 usual build cycle when using sample profilers for optimization:
2362 1. Build the code with source line table information. You can use all the
2363 usual build flags that you always build your application with. The only
2364 requirement is that you add ``-gline-tables-only`` or ``-g`` to the
2365 command line. This is important for the profiler to be able to map
2366 instructions back to source line locations.
2368 .. code-block:: console
2370 $ clang++ -O2 -gline-tables-only code.cc -o code
2372 2. Run the executable under a sampling profiler. The specific profiler
2373 you use does not really matter, as long as its output can be converted
2374 into the format that the LLVM optimizer understands. Currently, there
2375 exists a conversion tool for the Linux Perf profiler
2376 (https://perf.wiki.kernel.org/), so these examples assume that you
2377 are using Linux Perf to profile your code.
2379 .. code-block:: console
2381 $ perf record -b ./code
2383 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
2384 Record (LBR) to record call chains. While this is not strictly required,
2385 it provides better call information, which improves the accuracy of
2388 3. Convert the collected profile data to LLVM's sample profile format.
2389 This is currently supported via the AutoFDO converter ``create_llvm_prof``.
2390 It is available at https://github.com/google/autofdo. Once built and
2391 installed, you can convert the ``perf.data`` file to LLVM using
2394 .. code-block:: console
2396 $ create_llvm_prof --binary=./code --out=code.prof
2398 This will read ``perf.data`` and the binary file ``./code`` and emit
2399 the profile data in ``code.prof``. Note that if you ran ``perf``
2400 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
2401 calling ``create_llvm_prof``.
2403 4. Build the code again using the collected profile. This step feeds
2404 the profile back to the optimizers. This should result in a binary
2405 that executes faster than the original one. Note that you are not
2406 required to build the code with the exact same arguments that you
2407 used in the first step. The only requirement is that you build the code
2408 with ``-gline-tables-only`` and ``-fprofile-sample-use``.
2410 .. code-block:: console
2412 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
2414 [OPTIONAL] Sampling-based profiles can have inaccuracies or missing block/
2415 edge counters. The profile inference algorithm (profi) can be used to infer
2416 missing blocks and edge counts, and improve the quality of profile data.
2417 Enable it with ``-fsample-profile-use-profi``.
2419 .. code-block:: console
2421 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof \
2422 -fsample-profile-use-profi code.cc -o code
2424 Sample Profile Formats
2425 """"""""""""""""""""""
2427 Since external profilers generate profile data in a variety of custom formats,
2428 the data generated by the profiler must be converted into a format that can be
2429 read by the backend. LLVM supports three different sample profile formats:
2431 1. ASCII text. This is the easiest one to generate. The file is divided into
2432 sections, which correspond to each of the functions with profile
2433 information. The format is described below. It can also be generated from
2434 the binary or gcov formats using the ``llvm-profdata`` tool.
2436 2. Binary encoding. This uses a more efficient encoding that yields smaller
2437 profile files. This is the format generated by the ``create_llvm_prof`` tool
2438 in https://github.com/google/autofdo.
2440 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
2441 is only interesting in environments where GCC and Clang co-exist. This
2442 encoding is only generated by the ``create_gcov`` tool in
2443 https://github.com/google/autofdo. It can be read by LLVM and
2444 ``llvm-profdata``, but it cannot be generated by either.
2446 If you are using Linux Perf to generate sampling profiles, you can use the
2447 conversion tool ``create_llvm_prof`` described in the previous section.
2448 Otherwise, you will need to write a conversion tool that converts your
2449 profiler's native format into one of these three.
2452 Sample Profile Text Format
2453 """"""""""""""""""""""""""
2455 This section describes the ASCII text format for sampling profiles. It is,
2456 arguably, the easiest one to generate. If you are interested in generating any
2457 of the other two, consult the ``ProfileData`` library in LLVM's source tree
2458 (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
2460 .. code-block:: console
2462 function1:total_samples:total_head_samples
2463 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
2464 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
2466 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
2467 offsetA[.discriminator]: fnA:num_of_total_samples
2468 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
2469 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
2470 offsetB[.discriminator]: fnB:num_of_total_samples
2471 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
2473 This is a nested tree in which the indentation represents the nesting level
2474 of the inline stack. There are no blank lines in the file. And the spacing
2475 within a single line is fixed. Additional spaces will result in an error
2476 while reading the file.
2478 Any line starting with the '#' character is completely ignored.
2480 Inlined calls are represented with indentation. The Inline stack is a
2481 stack of source locations in which the top of the stack represents the
2482 leaf function, and the bottom of the stack represents the actual
2483 symbol to which the instruction belongs.
2485 Function names must be mangled in order for the profile loader to
2486 match them in the current translation unit. The two numbers in the
2487 function header specify how many total samples were accumulated in the
2488 function (first number), and the total number of samples accumulated
2489 in the prologue of the function (second number). This head sample
2490 count provides an indicator of how frequently the function is invoked.
2492 There are two types of lines in the function body.
2494 - Sampled line represents the profile information of a source location.
2495 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
2497 - Callsite line represents the profile information of an inlined callsite.
2498 ``offsetA[.discriminator]: fnA:num_of_total_samples``
2500 Each sampled line may contain several items. Some are optional (marked
2503 a. Source line offset. This number represents the line number
2504 in the function where the sample was collected. The line number is
2505 always relative to the line where symbol of the function is
2506 defined. So, if the function has its header at line 280, the offset
2507 13 is at line 293 in the file.
2509 Note that this offset should never be a negative number. This could
2510 happen in cases like macros. The debug machinery will register the
2511 line number at the point of macro expansion. So, if the macro was
2512 expanded in a line before the start of the function, the profile
2513 converter should emit a 0 as the offset (this means that the optimizers
2514 will not be able to associate a meaningful weight to the instructions
2517 b. [OPTIONAL] Discriminator. This is used if the sampled program
2518 was compiled with DWARF discriminator support
2519 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
2520 DWARF discriminators are unsigned integer values that allow the
2521 compiler to distinguish between multiple execution paths on the
2522 same source line location.
2524 For example, consider the line of code ``if (cond) foo(); else bar();``.
2525 If the predicate ``cond`` is true 80% of the time, then the edge
2526 into function ``foo`` should be considered to be taken most of the
2527 time. But both calls to ``foo`` and ``bar`` are at the same source
2528 line, so a sample count at that line is not sufficient. The
2529 compiler needs to know which part of that line is taken more
2532 This is what discriminators provide. In this case, the calls to
2533 ``foo`` and ``bar`` will be at the same line, but will have
2534 different discriminator values. This allows the compiler to correctly
2535 set edge weights into ``foo`` and ``bar``.
2537 c. Number of samples. This is an integer quantity representing the
2538 number of samples collected by the profiler at this source
2541 d. [OPTIONAL] Potential call targets and samples. If present, this
2542 line contains a call instruction. This models both direct and
2543 number of samples. For example,
2545 .. code-block:: console
2547 130: 7 foo:3 bar:2 baz:7
2549 The above means that at relative line offset 130 there is a call
2550 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
2551 with ``baz()`` being the relatively more frequently called target.
2553 As an example, consider a program with the call chain ``main -> foo -> bar``.
2554 When built with optimizations enabled, the compiler may inline the
2555 calls to ``bar`` and ``foo`` inside ``main``. The generated profile
2556 could then be something like this:
2558 .. code-block:: console
2566 This profile indicates that there were a total of 35,504 samples
2567 collected in main. All of those were at line 1 (the call to ``foo``).
2568 Of those, 31,977 were spent inside the body of ``bar``. The last line
2569 of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
2570 samples were collected there.
2572 Profiling with Instrumentation
2573 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2575 Clang also supports profiling via instrumentation. This requires building a
2576 special instrumented version of the code and has some runtime
2577 overhead during the profiling, but it provides more detailed results than a
2578 sampling profiler. It also provides reproducible results, at least to the
2579 extent that the code behaves consistently across runs.
2581 Here are the steps for using profile guided optimization with
2584 1. Build an instrumented version of the code by compiling and linking with the
2585 ``-fprofile-instr-generate`` option.
2587 .. code-block:: console
2589 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
2591 2. Run the instrumented executable with inputs that reflect the typical usage.
2592 By default, the profile data will be written to a ``default.profraw`` file
2593 in the current directory. You can override that default by using option
2594 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
2595 environment variable to specify an alternate file. If non-default file name
2596 is specified by both the environment variable and the command line option,
2597 the environment variable takes precedence. The file name pattern specified
2598 can include different modifiers: ``%p``, ``%h``, and ``%m``.
2600 Any instance of ``%p`` in that file name will be replaced by the process
2601 ID, so that you can easily distinguish the profile output from multiple
2604 .. code-block:: console
2606 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
2608 The modifier ``%h`` can be used in scenarios where the same instrumented
2609 binary is run in multiple different host machines dumping profile data
2610 to a shared network based storage. The ``%h`` specifier will be substituted
2611 with the hostname so that profiles collected from different hosts do not
2614 While the use of ``%p`` specifier can reduce the likelihood for the profiles
2615 dumped from different processes to clobber each other, such clobbering can still
2616 happen because of the ``pid`` re-use by the OS. Another side-effect of using
2617 ``%p`` is that the storage requirement for raw profile data files is greatly
2618 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
2619 name. When this specifier is used, the profiler runtime will substitute ``%m``
2620 with a unique integer identifier associated with the instrumented binary. Additionally,
2621 multiple raw profiles dumped from different processes that share a file system (can be
2622 on different hosts) will be automatically merged by the profiler runtime during the
2623 dumping. If the program links in multiple instrumented shared libraries, each library
2624 will dump the profile data into its own profile data file (with its unique integer
2625 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
2626 profile data generated by profiler runtime. The resulting merged "raw" profile data
2627 file still needs to be converted to a different format expected by the compiler (
2630 .. code-block:: console
2632 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
2635 3. Combine profiles from multiple runs and convert the "raw" profile format to
2636 the input expected by clang. Use the ``merge`` command of the
2637 ``llvm-profdata`` tool to do this.
2639 .. code-block:: console
2641 $ llvm-profdata merge -output=code.profdata code-*.profraw
2643 Note that this step is necessary even when there is only one "raw" profile,
2644 since the merge operation also changes the file format.
2646 4. Build the code again using the ``-fprofile-instr-use`` option to specify the
2647 collected profile data.
2649 .. code-block:: console
2651 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
2653 You can repeat step 4 as often as you like without regenerating the
2654 profile. As you make changes to your code, clang may no longer be able to
2655 use the profile data. It will warn you when this happens.
2657 Profile generation using an alternative instrumentation method can be
2658 controlled by the GCC-compatible flags ``-fprofile-generate`` and
2659 ``-fprofile-use``. Although these flags are semantically equivalent to
2660 their GCC counterparts, they *do not* handle GCC-compatible profiles.
2661 They are only meant to implement GCC's semantics with respect to
2662 profile creation and use. Flag ``-fcs-profile-generate`` also instruments
2663 programs using the same instrumentation method as ``-fprofile-generate``.
2665 .. option:: -fprofile-generate[=<dirname>]
2667 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
2668 an alternative instrumentation method for profile generation. When
2669 given a directory name, it generates the profile file
2670 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
2671 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
2672 will be substituted with a unique id documented in step 2 above. In other words,
2673 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
2674 merging is turned on by default, so there will no longer any risk of profile
2675 clobbering from different running processes. For example,
2677 .. code-block:: console
2679 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
2681 When ``code`` is executed, the profile will be written to the file
2682 ``yyy/zzz/default_xxxx.profraw``.
2684 To generate the profile data file with the compiler readable format, the
2685 ``llvm-profdata`` tool can be used with the profile directory as the input:
2687 .. code-block:: console
2689 $ llvm-profdata merge -output=code.profdata yyy/zzz/
2691 If the user wants to turn off the auto-merging feature, or simply override the
2692 the profile dumping path specified at command line, the environment variable
2693 ``LLVM_PROFILE_FILE`` can still be used to override
2694 the directory and filename for the profile file at runtime.
2696 .. option:: -fcs-profile-generate[=<dirname>]
2698 The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use
2699 the same instrumentation method, and generate the same profile as in the
2700 ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is
2701 that the instrumentation is performed after inlining so that the resulted
2702 profile has a better context sensitive information. They cannot be used
2703 together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags.
2704 They are typically used in conjunction with ``-fprofile-use`` flag.
2705 The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate``
2706 can be merged by llvm-profdata. A use example:
2708 .. code-block:: console
2710 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
2712 $ llvm-profdata merge -output=code.profdata yyy/zzz/
2714 The first few steps are the same as that in ``-fprofile-generate``
2715 compilation. Then perform a second round of instrumentation.
2717 .. code-block:: console
2719 $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \
2722 $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata
2724 The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile
2725 generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by
2726 ``-fprofile-use`` compilation.
2728 .. code-block:: console
2730 $ clang++ -O2 -fprofile-use=cs_code.profdata
2732 The above command will read both profiles to the compiler at the identical
2733 point of instrumentations.
2735 .. option:: -fprofile-use[=<pathname>]
2737 Without any other arguments, ``-fprofile-use`` behaves identically to
2738 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
2739 profile file, it reads from that file. If ``pathname`` is a directory name,
2740 it reads from ``pathname/default.profdata``.
2742 .. option:: -fprofile-update[=<method>]
2744 Unless ``-fsanitize=thread`` is specified, the default is ``single``, which
2745 uses non-atomic increments. The counters can be inaccurate under thread
2746 contention. ``atomic`` uses atomic increments which is accurate but has
2747 overhead. ``prefer-atomic`` will be transformed to ``atomic`` when supported
2748 by the target, or ``single`` otherwise.
2750 This option currently works with ``-fprofile-arcs`` and ``-fprofile-instr-generate``,
2751 but not with ``-fprofile-generate``.
2753 Disabling Instrumentation
2754 ^^^^^^^^^^^^^^^^^^^^^^^^^
2756 In certain situations, it may be useful to disable profile generation or use
2757 for specific files in a build, without affecting the main compilation flags
2758 used for the other files in the project.
2760 In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
2761 ``-fno-profile-generate``) to disable profile generation, and
2762 ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
2764 Note that these flags should appear after the corresponding profile
2765 flags to have an effect.
2769 When none of the translation units inside a binary is instrumented, in the
2770 case of Fuchsia the profile runtime will not be linked into the binary and
2771 no profile will be produced, while on other platforms the profile runtime
2772 will be linked and profile will be produced but there will not be any
2775 Instrumenting only selected files or functions
2776 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2778 Sometimes it's useful to only instrument certain files or functions. For
2779 example in automated testing infrastructure, it may be desirable to only
2780 instrument files or functions that were modified by a patch to reduce the
2781 overhead of instrumenting a full system.
2783 This can be done using the ``-fprofile-list`` option.
2785 .. option:: -fprofile-list=<pathname>
2787 This option can be used to apply profile instrumentation only to selected
2788 files or functions. ``pathname`` should point to a file in the
2789 :doc:`SanitizerSpecialCaseList` format which selects which files and
2790 functions to instrument.
2792 .. code-block:: console
2794 $ clang++ -O2 -fprofile-instr-generate -fprofile-list=fun.list code.cc -o code
2796 The option can be specified multiple times to pass multiple files.
2798 .. code-block:: console
2800 $ clang++ -O2 -fprofile-instr-generate -fcoverage-mapping -fprofile-list=fun.list -fprofile-list=code.list code.cc -o code
2802 Supported sections are ``[clang]``, ``[llvm]``, and ``[csllvm]`` representing
2803 clang PGO, IRPGO, and CSIRPGO, respectively. Supported prefixes are ``function``
2804 and ``source``. Supported categories are ``allow``, ``skip``, and ``forbid``.
2805 ``skip`` adds the ``skipprofile`` attribute while ``forbid`` adds the
2806 ``noprofile`` attribute to the appropriate function. Use
2807 ``default:<allow|skip|forbid>`` to specify the default category.
2809 .. code-block:: console
2812 # The following cases are for clang instrumentation.
2815 # We might not want to profile functions that are inlined in many places.
2816 function:inlinedLots=skip
2818 # We want to forbid profiling where it might be dangerous.
2819 source:lib/unsafe/*.cc=forbid
2821 # Otherwise we allow profiling.
2826 An older format is also supported, but it is only able to add the
2827 ``noprofile`` attribute.
2828 To filter individual functions or entire source files use ``fun:<name>`` or
2829 ``src:<file>`` respectively. To exclude a function or a source file, use
2830 ``!fun:<name>`` or ``!src:<file>`` respectively. The format also supports
2831 wildcard expansion. The compiler generated functions are assumed to be located
2832 in the main source file. It is also possible to restrict the filter to a
2833 particular instrumentation type by using a named section.
2835 .. code-block:: none
2837 # all functions whose name starts with foo will be instrumented.
2840 # except for foo1 which will be excluded from instrumentation.
2843 # every function in path/to/foo.cc will be instrumented.
2846 # bar will be instrumented only when using backend instrumentation.
2847 # Recognized section names are clang, llvm and csllvm.
2851 When the file contains only excludes, all files and functions except for the
2852 excluded ones will be instrumented. Otherwise, only the files and functions
2853 specified will be instrumented.
2855 Instrument function groups
2856 ^^^^^^^^^^^^^^^^^^^^^^^^^^
2858 Sometimes it is desirable to minimize the size overhead of instrumented
2859 binaries. One way to do this is to partition functions into groups and only
2860 instrument functions in a specified group. This can be done using the
2861 `-fprofile-function-groups` and `-fprofile-selected-function-group` options.
2863 .. option:: -fprofile-function-groups=<N>, -fprofile-selected-function-group=<i>
2865 The following uses 3 groups
2867 .. code-block:: console
2869 $ clang++ -Oz -fprofile-generate=group_0/ -fprofile-function-groups=3 -fprofile-selected-function-group=0 code.cc -o code.0
2870 $ clang++ -Oz -fprofile-generate=group_1/ -fprofile-function-groups=3 -fprofile-selected-function-group=1 code.cc -o code.1
2871 $ clang++ -Oz -fprofile-generate=group_2/ -fprofile-function-groups=3 -fprofile-selected-function-group=2 code.cc -o code.2
2873 After collecting raw profiles from the three binaries, they can be merged into
2874 a single profile like normal.
2876 .. code-block:: console
2878 $ llvm-profdata merge -output=code.profdata group_*/*.profraw
2884 When the program is compiled after a change that affects many symbol names,
2885 pre-existing profile data may no longer match the program. For example:
2887 * switching from libstdc++ to libc++ will result in the mangled names of all
2888 functions taking standard library types to change
2889 * renaming a widely-used type in C++ will result in the mangled names of all
2890 functions that have parameters involving that type to change
2891 * moving from a 32-bit compilation to a 64-bit compilation may change the
2892 underlying type of ``size_t`` and similar types, resulting in changes to
2895 Clang allows use of a profile remapping file to specify that such differences
2896 in mangled names should be ignored when matching the profile data against the
2899 .. option:: -fprofile-remapping-file=<file>
2901 Specifies a file containing profile remapping information, that will be
2902 used to match mangled names in the profile data to mangled names in the
2905 The profile remapping file is a text file containing lines of the form
2907 .. code-block:: text
2909 fragmentkind fragment1 fragment2
2911 where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``,
2912 indicating whether the following mangled name fragments are
2913 <`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s,
2914 <`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or
2915 <`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s,
2917 Blank lines and lines starting with ``#`` are ignored.
2919 For convenience, built-in <substitution>s such as ``St`` and ``Ss``
2920 are accepted as <name>s (even though they technically are not <name>s).
2922 For example, to specify that ``absl::string_view`` and ``std::string_view``
2923 should be treated as equivalent when matching profile data, the following
2924 remapping file could be used:
2926 .. code-block:: text
2928 # absl::string_view is considered equivalent to std::string_view
2929 type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE
2931 # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++
2933 name 3std St7__cxx11
2935 Matching profile data using a profile remapping file is supported on a
2936 best-effort basis. For example, information regarding indirect call targets is
2937 currently not remapped. For best results, you are encouraged to generate new
2938 profile data matching the updated program, or to remap the profile data
2939 using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools.
2943 Profile data remapping is currently only supported for C++ mangled names
2944 following the Itanium C++ ABI mangling scheme. This covers all C++ targets
2945 supported by Clang other than Windows.
2947 GCOV-based Profiling
2948 --------------------
2950 GCOV is a test coverage program, it helps to know how often a line of code
2951 is executed. When instrumenting the code with ``--coverage`` option, some
2952 counters are added for each edge linking basic blocks.
2954 At compile time, gcno files are generated containing information about
2955 blocks and edges between them. At runtime the counters are incremented and at
2956 exit the counters are dumped in gcda files.
2958 The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate
2959 a report ``.c.gcov``.
2961 .. option:: -fprofile-filter-files=[regexes]
2963 Define a list of regexes separated by a semi-colon.
2964 If a file name matches any of the regexes then the file is instrumented.
2966 .. code-block:: console
2968 $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c
2970 For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files.
2972 .. option:: -fprofile-exclude-files=[regexes]
2974 Define a list of regexes separated by a semi-colon.
2975 If a file name doesn't match all the regexes then the file is instrumented.
2977 .. code-block:: console
2979 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c
2981 For example, this will instrument all the files except the ones in ``/usr/include``.
2983 If both options are used then a file is instrumented if its name matches any
2984 of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes
2985 from ``-fprofile-exclude-list``.
2987 .. code-block:: console
2989 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \
2990 -fprofile-filter-files="^/usr/.*$"
2992 In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and
2993 doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches
2996 Controlling Debug Information
2997 -----------------------------
2999 Controlling Size of Debug Information
3000 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3002 Debug info kind generated by Clang can be set by one of the flags listed
3003 below. If multiple flags are present, the last one is used.
3007 Don't generate any debug info (default).
3009 .. option:: -gline-tables-only
3011 Generate line number tables only.
3013 This kind of debug info allows to obtain stack traces with function names,
3014 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
3015 doesn't contain any other data (e.g. description of local variables or
3016 function parameters).
3018 .. option:: -fstandalone-debug
3020 Clang supports a number of optimizations to reduce the size of debug
3021 information in the binary. They work based on the assumption that
3022 the debug type information can be spread out over multiple
3023 compilation units. Specifically, the optimizations are:
3025 - will not emit type definitions for types that are not needed by a
3026 module and could be replaced with a forward declaration.
3027 - will only emit type info for a dynamic C++ class in the module that
3028 contains the vtable for the class.
3029 - will only emit type info for a C++ class (non-trivial, non-aggregate)
3030 in the modules that contain a definition for one of its constructors.
3031 - will only emit type definitions for types that are the subject of explicit
3032 template instantiation declarations in the presence of an explicit
3033 instantiation definition for the type.
3035 The **-fstandalone-debug** option turns off these optimizations.
3036 This is useful when working with 3rd-party libraries that don't come
3037 with debug information. Note that Clang will never emit type
3038 information for types that are not referenced at all by the program.
3040 .. option:: -fno-standalone-debug
3042 On Darwin **-fstandalone-debug** is enabled by default. The
3043 **-fno-standalone-debug** option can be used to get to turn on the
3044 vtable-based optimization described above.
3048 Generate complete debug info.
3050 .. option:: -feliminate-unused-debug-types
3052 By default, Clang does not emit type information for types that are defined
3053 but not used in a program. To retain the debug info for these unused types,
3054 the negation **-fno-eliminate-unused-debug-types** can be used.
3056 Controlling Macro Debug Info Generation
3057 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3059 Debug info for C preprocessor macros increases the size of debug information in
3060 the binary. Macro debug info generated by Clang can be controlled by the flags
3063 .. option:: -fdebug-macro
3065 Generate debug info for preprocessor macros. This flag is discarded when
3068 .. option:: -fno-debug-macro
3070 Do not generate debug info for preprocessor macros (default).
3072 Controlling Debugger "Tuning"
3073 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3075 While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
3076 different debuggers may know how to take advantage of different specific DWARF
3077 features. You can "tune" the debug info for one of several different debuggers.
3079 .. option:: -ggdb, -glldb, -gsce, -gdbx
3081 Tune the debug info for the ``gdb``, ``lldb``, Sony PlayStation\ |reg|
3082 debugger, or ``dbx``, respectively. Each of these options implies **-g**.
3083 (Therefore, if you want both **-gline-tables-only** and debugger tuning, the
3084 tuning option must come first.)
3086 Controlling LLVM IR Output
3087 --------------------------
3089 Controlling Value Names in LLVM IR
3090 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3092 Emitting value names in LLVM IR increases the size and verbosity of the IR.
3093 By default, value names are only emitted in assertion-enabled builds of Clang.
3094 However, when reading IR it can be useful to re-enable the emission of value
3095 names to improve readability.
3097 .. option:: -fdiscard-value-names
3099 Discard value names when generating LLVM IR.
3101 .. option:: -fno-discard-value-names
3103 Do not discard value names when generating LLVM IR. This option can be used
3104 to re-enable names for release builds of Clang.
3107 Comment Parsing Options
3108 -----------------------
3110 Clang parses Doxygen and non-Doxygen style documentation comments and attaches
3111 them to the appropriate declaration nodes. By default, it only parses
3112 Doxygen-style comments and ignores ordinary comments starting with ``//`` and
3115 .. option:: -Wdocumentation
3117 Emit warnings about use of documentation comments. This warning group is off
3120 This includes checking that ``\param`` commands name parameters that actually
3121 present in the function signature, checking that ``\returns`` is used only on
3122 functions that actually return a value etc.
3124 .. option:: -Wno-documentation-unknown-command
3126 Don't warn when encountering an unknown Doxygen command.
3128 .. option:: -fparse-all-comments
3130 Parse all comments as documentation comments (including ordinary comments
3131 starting with ``//`` and ``/*``).
3133 .. option:: -fcomment-block-commands=[commands]
3135 Define custom documentation commands as block commands. This allows Clang to
3136 construct the correct AST for these custom commands, and silences warnings
3137 about unknown commands. Several commands must be separated by a comma
3138 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
3139 custom commands ``\foo`` and ``\bar``.
3141 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
3142 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
3150 The support for standard C in clang is feature-complete except for the
3151 C99 floating-point pragmas.
3153 Extensions supported by clang
3154 -----------------------------
3156 See :doc:`LanguageExtensions`.
3158 Differences between various standard modes
3159 ------------------------------------------
3161 clang supports the -std option, which changes what language mode clang uses.
3162 The supported modes for C are c89, gnu89, c94, c99, gnu99, c11, gnu11, c17,
3163 gnu17, c2x, gnu2x, and various aliases for those modes. If no -std option is
3164 specified, clang defaults to gnu17 mode. Many C99 and C11 features are
3165 supported in earlier modes as a conforming extension, with a warning. Use
3166 ``-pedantic-errors`` to request an error if a feature from a later standard
3167 revision is used in an earlier mode.
3169 Differences between all ``c*`` and ``gnu*`` modes:
3171 - ``c*`` modes define "``__STRICT_ANSI__``".
3172 - Target-specific defines not prefixed by underscores, like ``linux``,
3173 are defined in ``gnu*`` modes.
3174 - Trigraphs default to being off in ``gnu*`` modes; they can be enabled
3175 by the ``-trigraphs`` option.
3176 - The parser recognizes ``asm`` and ``typeof`` as keywords in ``gnu*`` modes;
3177 the variants ``__asm__`` and ``__typeof__`` are recognized in all modes.
3178 - The parser recognizes ``inline`` as a keyword in ``gnu*`` mode, in
3179 addition to recognizing it in the ``*99`` and later modes for which it is
3180 part of the ISO C standard. The variant ``__inline__`` is recognized in all
3182 - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
3183 on some platforms; it can be enabled in any mode with the ``-fblocks``
3186 Differences between ``*89`` and ``*94`` modes:
3188 - Digraphs are not recognized in c89 mode.
3190 Differences between ``*94`` and ``*99`` modes:
3192 - The ``*99`` modes default to implementing ``inline`` / ``__inline__``
3193 as specified in C99, while the ``*89`` modes implement the GNU version.
3194 This can be overridden for individual functions with the ``__gnu_inline__``
3196 - The scope of names defined inside a ``for``, ``if``, ``switch``, ``while``,
3197 or ``do`` statement is different. (example: ``if ((struct x {int x;}*)0) {}``.)
3198 - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
3199 - ``inline`` is not recognized as a keyword in ``c89`` mode.
3200 - ``restrict`` is not recognized as a keyword in ``*89`` modes.
3201 - Commas are allowed in integer constant expressions in ``*99`` modes.
3202 - Arrays which are not lvalues are not implicitly promoted to pointers
3204 - Some warnings are different.
3206 Differences between ``*99`` and ``*11`` modes:
3208 - Warnings for use of C11 features are disabled.
3209 - ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
3211 Differences between ``*11`` and ``*17`` modes:
3213 - ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.
3215 GCC extensions not implemented yet
3216 ----------------------------------
3218 clang tries to be compatible with gcc as much as possible, but some gcc
3219 extensions are not implemented yet:
3221 - clang does not support decimal floating point types (``_Decimal32`` and
3223 - clang does not support nested functions; this is a complex feature
3224 which is infrequently used, so it is unlikely to be implemented
3225 anytime soon. In C++11 it can be emulated by assigning lambda
3226 functions to local variables, e.g:
3230 auto const local_function = [&](int parameter) {
3236 - clang only supports global register variables when the register specified
3237 is non-allocatable (e.g. the stack pointer). Support for general global
3238 register variables is unlikely to be implemented soon because it requires
3239 additional LLVM backend support.
3240 - clang does not support static initialization of flexible array
3241 members. This appears to be a rarely used extension, but could be
3242 implemented pending user demand.
3243 - clang does not support
3244 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
3245 used rarely, but in some potentially interesting places, like the
3246 glibc headers, so it may be implemented pending user demand. Note
3247 that because clang pretends to be like GCC 4.2, and this extension
3248 was introduced in 4.3, the glibc headers will not try to use this
3249 extension with clang at the moment.
3250 - clang does not support the gcc extension for forward-declaring
3251 function parameters; this has not shown up in any real-world code
3252 yet, though, so it might never be implemented.
3254 This is not a complete list; if you find an unsupported extension
3255 missing from this list, please send an e-mail to cfe-dev. This list
3256 currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
3257 list does not include bugs in mostly-implemented features; please see
3259 tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
3260 for known existing bugs (FIXME: Is there a section for bug-reporting
3261 guidelines somewhere?).
3263 Intentionally unsupported GCC extensions
3264 ----------------------------------------
3266 - clang does not support the gcc extension that allows variable-length
3267 arrays in structures. This is for a few reasons: one, it is tricky to
3268 implement, two, the extension is completely undocumented, and three,
3269 the extension appears to be rarely used. Note that clang *does*
3270 support flexible array members (arrays with a zero or unspecified
3271 size at the end of a structure).
3272 - GCC accepts many expression forms that are not valid integer constant
3273 expressions in bit-field widths, enumerator constants, case labels,
3274 and in array bounds at global scope. Clang also accepts additional
3275 expression forms in these contexts, but constructs that GCC accepts due to
3276 simplifications GCC performs while parsing, such as ``x - x`` (where ``x`` is a
3277 variable) will likely never be accepted by Clang.
3278 - clang does not support ``__builtin_apply`` and friends; this extension
3279 is extremely obscure and difficult to implement reliably.
3283 Microsoft extensions
3284 --------------------
3286 clang has support for many extensions from Microsoft Visual C++. To enable these
3287 extensions, use the ``-fms-extensions`` command-line option. This is the default
3288 for Windows targets. Clang does not implement every pragma or declspec provided
3289 by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
3290 comment(lib)`` are well supported.
3292 clang has a ``-fms-compatibility`` flag that makes clang accept enough
3293 invalid C++ to be able to parse most Microsoft headers. For example, it
3294 allows `unqualified lookup of dependent base class members
3295 <https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
3296 a common compatibility issue with clang. This flag is enabled by default
3297 for Windows targets.
3299 ``-fdelayed-template-parsing`` lets clang delay parsing of function template
3300 definitions until the end of a translation unit. This flag is enabled by
3301 default for Windows targets.
3303 For compatibility with existing code that compiles with MSVC, clang defines the
3304 ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. When on Windows, these default to
3305 either the same value as the currently installed version of cl.exe, or ``1920``
3306 and ``192000000`` (respectively). The ``-fms-compatibility-version=`` flag
3307 overrides these values. It accepts a dotted version tuple, such as 19.00.23506.
3308 Changing the MSVC compatibility version makes clang behave more like that
3309 version of MSVC. For example, ``-fms-compatibility-version=19`` will enable
3310 C++14 features and define ``char16_t`` and ``char32_t`` as builtin types.
3314 C++ Language Features
3315 =====================
3317 clang fully implements all of standard C++98 except for exported
3318 templates (which were removed in C++11), all of standard C++11,
3319 C++14, and C++17, and most of C++20.
3321 See the `C++ support in Clang <https://clang.llvm.org/cxx_status.html>`_ page
3322 for detailed information on C++ feature support across Clang versions.
3324 Controlling implementation limits
3325 ---------------------------------
3327 .. option:: -fbracket-depth=N
3329 Sets the limit for nested parentheses, brackets, and braces to N. The
3332 .. option:: -fconstexpr-depth=N
3334 Sets the limit for constexpr function invocations to N. The default is 512.
3336 .. option:: -fconstexpr-steps=N
3338 Sets the limit for the number of full-expressions evaluated in a single
3339 constant expression evaluation. The default is 1048576.
3341 .. option:: -ftemplate-depth=N
3343 Sets the limit for recursively nested template instantiations to N. The
3346 .. option:: -foperator-arrow-depth=N
3348 Sets the limit for iterative calls to 'operator->' functions to N. The
3353 Objective-C Language Features
3354 =============================
3358 Objective-C++ Language Features
3359 ===============================
3366 Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport`
3367 for additional details.
3369 Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
3372 Use `-fopenmp-simd` to enable OpenMP simd features only, without linking
3373 the runtime library; for combined constructs
3374 (e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses
3375 will be ignored. This can be disabled with `-fno-openmp-simd`.
3377 Controlling implementation limits
3378 ---------------------------------
3380 .. option:: -fopenmp-use-tls
3382 Controls code generation for OpenMP threadprivate variables. In presence of
3383 this option all threadprivate variables are generated the same way as thread
3384 local variables, using TLS support. If `-fno-openmp-use-tls`
3385 is provided or target does not support TLS, code generation for threadprivate
3386 variables relies on OpenMP runtime library.
3393 Clang can be used to compile OpenCL kernels for execution on a device
3394 (e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMDGPU)
3395 that can be uploaded to run directly on a device (e.g. using
3396 `clCreateProgramWithBinary
3397 <https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
3398 into generic bitcode files loadable into other toolchains.
3400 Compiling to a binary using the default target from the installation can be done
3403 .. code-block:: console
3405 $ echo "kernel void k(){}" > test.cl
3408 Compiling for a specific target can be done by specifying the triple corresponding
3409 to the target, for example:
3411 .. code-block:: console
3413 $ clang --target=nvptx64-unknown-unknown test.cl
3414 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
3416 Compiling to bitcode can be done as follows:
3418 .. code-block:: console
3420 $ clang -c -emit-llvm test.cl
3422 This will produce a file `test.bc` that can be used in vendor toolchains
3423 to perform machine code generation.
3425 Note that if compiled to bitcode for generic targets such as SPIR/SPIR-V,
3426 portable IR is produced that can be used with various vendor
3427 tools as well as open source tools such as `SPIRV-LLVM Translator
3428 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_
3429 to produce SPIR-V binary. More details are provided in `the offline
3430 compilation from OpenCL kernel sources into SPIR-V using open source
3432 <https://github.com/KhronosGroup/OpenCL-Guide/blob/main/chapters/os_tooling.md>`_.
3433 From clang 14 onwards SPIR-V can be generated directly as detailed in
3434 :ref:`the SPIR-V support section <spir-v>`.
3436 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
3437 supports full profile. There is only very limited support of the embedded
3439 From clang 9 a C++ mode is available for OpenCL (see
3440 :ref:`C++ for OpenCL <cxx_for_opencl>`).
3442 OpenCL v3.0 support is complete but it remains in experimental state, see more
3443 details about the experimental features and limitations in :doc:`OpenCLSupport`
3446 OpenCL Specific Options
3447 -----------------------
3449 Most of the OpenCL build options from `the specification v2.0 section 5.8.4
3450 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
3454 .. code-block:: console
3456 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
3459 Many flags used for the compilation for C sources can also be passed while
3460 compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
3462 Some extra options are available to support special OpenCL features.
3464 .. option:: -cl-no-stdinc
3466 Allows to disable all extra types and functions that are not native to the compiler.
3467 This might reduce the compilation speed marginally but many declarations from the
3468 OpenCL standard will not be accessible. For example, the following will fail to
3471 .. code-block:: console
3473 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
3474 $ clang -cl-std=CL2.0 -cl-no-stdinc test.cl
3475 error: use of undeclared identifier 'get_enqueued_local_size'
3476 error: use of undeclared identifier 'get_local_size'
3478 More information about the standard types and functions is provided in :ref:`the
3479 section on the OpenCL Header <opencl_header>`.
3485 Enables/Disables support of OpenCL extensions and optional features. All OpenCL
3486 targets set a list of extensions that they support. Clang allows to amend this using
3487 the ``-cl-ext`` flag with a comma-separated list of extensions prefixed with
3488 ``'+'`` or ``'-'``. The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where
3489 extensions can be either one of `the OpenCL published extensions
3490 <https://www.khronos.org/registry/OpenCL>`_
3491 or any vendor extension. Alternatively, ``'all'`` can be used to enable
3492 or disable all known extensions.
3494 Example disabling double support for the 64-bit SPIR-V target:
3496 .. code-block:: console
3498 $ clang -c --target=spirv64 -cl-ext=-cl_khr_fp64 test.cl
3500 Enabling all extensions except double support in R600 AMD GPU can be done using:
3502 .. code-block:: console
3504 $ clang --target=r600 -cl-ext=-all,+cl_khr_fp16 test.cl
3506 Note that some generic targets e.g. SPIR/SPIR-V enable all extensions/features in
3512 OpenCL targets are derived from the regular Clang target classes. The OpenCL
3513 specific parts of the target representation provide address space mapping as
3514 well as a set of supported extensions.
3519 There is a set of concrete HW architectures that OpenCL can be compiled for.
3523 .. code-block:: console
3525 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
3527 - For Nvidia architectures:
3529 .. code-block:: console
3531 $ clang --target=nvptx64-unknown-unknown test.cl
3537 - A SPIR-V binary can be produced for 32 or 64 bit targets.
3539 .. code-block:: console
3541 $ clang --target=spirv32 -c test.cl
3542 $ clang --target=spirv64 -c test.cl
3544 More details can be found in :ref:`the SPIR-V support section <spir-v>`.
3546 - SPIR is available as a generic target to allow portable bitcode to be produced
3547 that can be used across GPU toolchains. The implementation follows `the SPIR
3548 specification <https://www.khronos.org/spir>`_. There are two flavors
3549 available for 32 and 64 bits.
3551 .. code-block:: console
3553 $ clang --target=spir test.cl -emit-llvm -c
3554 $ clang --target=spir64 test.cl -emit-llvm -c
3556 Clang will generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and
3557 SPIR v2.0 for OpenCL v2.0 or C++ for OpenCL.
3559 - x86 is used by some implementations that are x86 compatible and currently
3560 remains for backwards compatibility (with older implementations prior to
3561 SPIR target support). For "non-SPMD" targets which cannot spawn multiple
3562 work-items on the fly using hardware, which covers practically all non-GPU
3563 devices such as CPUs and DSPs, additional processing is needed for the kernels
3564 to support multiple work-item execution. For this, a 3rd party toolchain,
3565 such as for example `POCL <http://portablecl.org/>`_, can be used.
3567 This target does not support multiple memory segments and, therefore, the fake
3568 address space map can be added using the :ref:`-ffake-address-space-map
3569 <opencl_fake_address_space_map>` flag.
3571 All known OpenCL extensions and features are set to supported in the generic targets,
3572 however :option:`-cl-ext` flag can be used to toggle individual extensions and
3580 By default Clang will include standard headers and therefore most of OpenCL
3581 builtin functions and types are available during compilation. The
3582 default declarations of non-native compiler types and functions can be disabled
3583 by using flag :option:`-cl-no-stdinc`.
3585 The following example demonstrates that OpenCL kernel sources with various
3586 standard builtin functions can be compiled without the need for an explicit
3587 includes or compiler flags.
3589 .. code-block:: console
3591 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
3592 $ clang -cl-std=CL2.0 test.cl
3594 More information about the default headers is provided in :doc:`OpenCLSupport`.
3599 Most of the ``cl_khr_*`` extensions to OpenCL C from `the official OpenCL
3600 registry <https://www.khronos.org/registry/OpenCL/>`_ are available and
3601 configured per target depending on the support available in the specific
3604 It is possible to alter the default extensions setting per target using
3605 ``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
3607 Vendor extensions can be added flexibly by declaring the list of types and
3608 functions associated with each extensions enclosed within the following
3609 compiler pragma directives:
3613 #pragma OPENCL EXTENSION the_new_extension_name : begin
3614 // declare types and functions associated with the extension here
3615 #pragma OPENCL EXTENSION the_new_extension_name : end
3617 For example, parsing the following code adds ``my_t`` type and ``my_func``
3618 function to the custom ``my_ext`` extension.
3622 #pragma OPENCL EXTENSION my_ext : begin
3627 #pragma OPENCL EXTENSION my_ext : end
3629 There is no conflict resolution for identifier clashes among extensions.
3630 It is therefore recommended that the identifiers are prefixed with a
3631 double underscore to avoid clashing with user space identifiers. Vendor
3632 extension should use reserved identifier prefix e.g. amd, arm, intel.
3634 Clang also supports language extensions documented in `The OpenCL C Language
3635 Extensions Documentation
3636 <https://github.com/KhronosGroup/Khronosdotorg/blob/main/api/opencl/assets/OpenCL_LangExt.pdf>`_.
3638 OpenCL-Specific Attributes
3639 --------------------------
3641 OpenCL support in Clang contains a set of attribute taken directly from the
3642 specification as well as additional attributes.
3644 See also :doc:`AttributeReference`.
3649 Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
3650 does not have any effect on the IR. For more details reffer to the specification
3652 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
3658 The implementation of this feature mirrors the unroll hint for C.
3659 More details on the syntax can be found in the specification
3661 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
3666 To make sure no invalid optimizations occur for single program multiple data
3667 (SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
3668 can be used for special functions that have cross work item semantics.
3669 An example is the subgroup operations such as `intel_sub_group_shuffle
3670 <https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
3674 // Define custom my_sub_group_shuffle(data, c)
3675 // that makes use of intel_sub_group_shuffle
3677 if (r0) r1 = computeA();
3678 // Shuffle data from r1 into r3
3679 // of threads id r2.
3680 r3 = my_sub_group_shuffle(r1, r2);
3681 if (r0) r3 = computeB();
3683 with non-SPMD semantics this is optimized to the following equivalent code:
3689 // Incorrect functionality! The data in r1
3690 // have not been computed by all threads yet.
3691 r3 = my_sub_group_shuffle(r1, r2);
3694 r3 = my_sub_group_shuffle(r1, r2);
3698 Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
3703 my_sub_group_shuffle() __attribute__((convergent));
3705 Using ``convergent`` guarantees correct execution by keeping CFG equivalence
3706 wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
3707 node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
3708 respect to ``Ni`` remain the same in both ``G`` and ``G´``.
3713 ``noduplicate`` is more restrictive with respect to optimizations than
3714 ``convergent`` because a convergent function only preserves CFG equivalence.
3715 This allows some optimizations to happen as long as the control flow remains
3720 for (int i=0; i<4; i++)
3721 my_sub_group_shuffle()
3727 my_sub_group_shuffle();
3728 my_sub_group_shuffle();
3729 my_sub_group_shuffle();
3730 my_sub_group_shuffle();
3732 while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
3733 have the same safe semantics of CFG as ``convergent`` and can cause changes in
3734 CFG that modify semantics of the original program.
3736 ``noduplicate`` is kept for backwards compatibility only and it considered to be
3737 deprecated for future uses.
3744 Starting from clang 9 kernel code can contain C++17 features: classes, templates,
3745 function overloading, type deduction, etc. Please note that this is not an
3746 implementation of `OpenCL C++
3747 <https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and
3748 there is no plan to support it in clang in any new releases in the near future.
3750 Clang currently supports C++ for OpenCL 1.0 and 2021.
3751 For detailed information about this language refer to the C++ for OpenCL
3752 Programming Language Documentation available
3753 in `the latest build
3754 <https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html>`_
3755 or in `the official release
3756 <https://github.com/KhronosGroup/OpenCL-Docs/releases/tag/cxxforopencl-docrev2021.12>`_.
3758 To enable the C++ for OpenCL mode, pass one of following command line options when
3759 compiling ``.clcpp`` file:
3761 - C++ for OpenCL 1.0: ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-cl-std=clc++1.0``,
3762 ``-cl-std=CLC++1.0``, ``-std=clc++``, ``-std=CLC++``, ``-std=clc++1.0`` or
3765 - C++ for OpenCL 2021: ``-cl-std=clc++2021``, ``-cl-std=CLC++2021``,
3766 ``-std=clc++2021``, ``-std=CLC++2021``.
3771 template<class T> T add( T x, T y )
3776 __kernel void test( __global float* a, __global float* b)
3778 auto index = get_global_id(0);
3779 a[index] = add(b[index], b[index+1]);
3783 .. code-block:: console
3785 clang -cl-std=clc++1.0 test.clcpp
3786 clang -cl-std=clc++ -c --target=spirv64 test.cl
3789 By default, files with ``.clcpp`` extension are compiled with the C++ for
3792 .. code-block:: console
3796 For backward compatibility files with ``.cl`` extensions can also be compiled
3797 in C++ for OpenCL mode but the desirable language mode must be activated with
3800 .. code-block:: console
3802 clang -cl-std=clc++ test.cl
3804 Support of C++ for OpenCL 2021 is currently in experimental phase, refer to
3805 :doc:`OpenCLSupport` for more details.
3807 C++ for OpenCL kernel sources can also be compiled online in drivers supporting
3808 `cl_ext_cxx_for_opencl
3809 <https://www.khronos.org/registry/OpenCL/extensions/ext/cl_ext_cxx_for_opencl.html>`_
3812 Constructing and destroying global objects
3813 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3815 Global objects with non-trivial constructors require the constructors to be run
3816 before the first kernel using the global objects is executed. Similarly global
3817 objects with non-trivial destructors require destructor invocation just after
3818 the last kernel using the program objects is executed.
3819 In OpenCL versions earlier than v2.2 there is no support for invoking global
3820 constructors. However, an easy workaround is to manually enqueue the
3821 constructor initialization kernel that has the following name scheme
3822 ``_GLOBAL__sub_I_<compiled file name>``.
3823 This kernel is only present if there are global objects with non-trivial
3824 constructors present in the compiled binary. One way to check this is by
3825 passing ``CL_PROGRAM_KERNEL_NAMES`` to ``clGetProgramInfo`` (OpenCL v2.0
3826 s5.8.7) and then checking whether any kernel name matches the naming scheme of
3827 global constructor initialization kernel above.
3829 Note that if multiple files are compiled and linked into libraries, multiple
3830 kernels that initialize global objects for multiple modules would have to be
3833 Applications are currently required to run initialization of global objects
3834 manually before running any kernels in which the objects are used.
3836 .. code-block:: console
3838 clang -cl-std=clc++ test.cl
3840 If there are any global objects to be initialized, the final binary will
3841 contain the ``_GLOBAL__sub_I_test.cl`` kernel to be enqueued.
3843 Note that the manual workaround only applies to objects declared at the
3844 program scope. There is no manual workaround for the construction of static
3845 objects with non-trivial constructors inside functions.
3847 Global destructors can not be invoked manually in the OpenCL v2.0 drivers.
3848 However, all memory used for program scope objects should be released on
3849 ``clReleaseProgram``.
3853 Limited experimental support of C++ standard libraries for OpenCL is
3854 described in :doc:`OpenCLSupport` page.
3856 .. _target_features:
3858 Target-Specific Features and Limitations
3859 ========================================
3861 CPU Architectures Features and Limitations
3862 ------------------------------------------
3867 The support for X86 (both 32-bit and 64-bit) is considered stable on
3868 Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested
3869 to correctly compile many large C, C++, Objective-C, and Objective-C++
3872 On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
3873 Microsoft x64 calling convention. You might need to tweak
3874 ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
3876 For the X86 target, clang supports the `-m16` command line
3877 argument which enables 16-bit code output. This is broadly similar to
3878 using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
3879 and the ABI remains 32-bit but the assembler emits instructions
3880 appropriate for a CPU running in 16-bit mode, with address-size and
3881 operand-size prefixes to enable 32-bit addressing and operations.
3883 Several micro-architecture levels as specified by the x86-64 psABI are defined.
3884 They are cumulative in the sense that features from previous levels are
3885 implicitly included in later levels.
3887 - ``-march=x86-64``: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
3888 - ``-march=x86-64-v2``: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
3889 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
3890 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
3895 The support for ARM (specifically ARMv6 and ARMv7) is considered stable
3896 on Darwin (iOS): it has been tested to correctly compile many large C,
3897 C++, Objective-C, and Objective-C++ codebases. Clang only supports a
3898 limited number of ARM architectures. It does not yet fully support
3904 The support for PowerPC (especially PowerPC64) is considered stable
3905 on Linux and FreeBSD: it has been tested to correctly compile many
3906 large C and C++ codebases. PowerPC (32bit) is still missing certain
3907 features (e.g. PIC code on ELF platforms).
3912 clang currently contains some support for other architectures (e.g. Sparc);
3913 however, significant pieces of code generation are still missing, and they
3914 haven't undergone significant testing.
3916 clang contains limited support for the MSP430 embedded processor, but
3917 both the clang support and the LLVM backend support are highly
3920 Other platforms are completely unsupported at the moment. Adding the
3921 minimal support needed for parsing and semantic analysis on a new
3922 platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
3923 tree. This level of support is also sufficient for conversion to LLVM IR
3924 for simple programs. Proper support for conversion to LLVM IR requires
3925 adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
3926 change soon, though. Generating assembly requires a suitable LLVM
3929 Operating System Features and Limitations
3930 -----------------------------------------
3935 Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
3938 See also :ref:`Microsoft Extensions <c_ms>`.
3943 Clang works on Cygwin-1.7.
3948 Clang works on some mingw32 distributions. Clang assumes directories as
3951 - ``C:/mingw/include``
3953 - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
3955 On MSYS, a few tests might fail.
3960 For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
3963 - ``GCC versions 4.5.0 to 4.5.3, 4.6.0 to 4.6.2, or 4.7.0 (for the C++ header search path)``
3964 - ``some_directory/bin/gcc.exe``
3965 - ``some_directory/bin/clang.exe``
3966 - ``some_directory/bin/clang++.exe``
3967 - ``some_directory/bin/../include/c++/GCC_version``
3968 - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
3969 - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
3970 - ``some_directory/bin/../include/c++/GCC_version/backward``
3971 - ``some_directory/bin/../x86_64-w64-mingw32/include``
3972 - ``some_directory/bin/../i686-w64-mingw32/include``
3973 - ``some_directory/bin/../include``
3975 This directory layout is standard for any toolchain you will find on the
3976 official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
3978 Clang expects the GCC executable "gcc.exe" compiled for
3979 ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
3981 `Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
3982 ``x86_64-w64-mingw32``.
3987 The ``-mdefault-visibility-export-mapping=`` option can be used to control
3988 mapping of default visibility to an explicit shared object export
3989 (i.e. XCOFF exported visibility). Three values are provided for the option:
3991 * ``-mdefault-visibility-export-mapping=none``: no additional export
3992 information is created for entities with default visibility.
3993 * ``-mdefault-visibility-export-mapping=explicit``: mark entities for export
3994 if they have explicit (e.g. via an attribute) default visibility from the
3995 source, including RTTI.
3996 * ``-mdefault-visibility-export-mapping=all``: set XCOFF exported visibility
3997 for all entities with default visibility from any source. This gives a
3998 export behavior similar to ELF platforms where all entities with default
3999 visibility are exported.
4006 Clang supports generation of SPIR-V conformant to `the OpenCL Environment
4008 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Env.html>`_.
4010 To generate SPIR-V binaries, Clang uses the external ``llvm-spirv`` tool from the
4011 `SPIRV-LLVM-Translator repo
4012 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_.
4014 Prior to the generation of SPIR-V binary with Clang, ``llvm-spirv``
4015 should be built or installed. Please refer to `the following instructions
4016 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator#build-instructions>`_
4017 for more details. Clang will expect the ``llvm-spirv`` executable to
4018 be present in the ``PATH`` environment variable. Clang uses ``llvm-spirv``
4019 with `the widely adopted assembly syntax package
4020 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator/#build-with-spirv-tools>`_.
4023 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator/releases>`_ of
4024 ``llvm-spirv`` is aligned with Clang major releases. The same applies to the
4025 main development branch. It is therefore important to ensure the ``llvm-spirv``
4026 version is in alignment with the Clang version. For troubleshooting purposes
4027 ``llvm-spirv`` can be `tested in isolation
4028 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator#test-instructions>`_.
4030 Example usage for OpenCL kernel compilation:
4032 .. code-block:: console
4034 $ clang --target=spirv32 -c test.cl
4035 $ clang --target=spirv64 -c test.cl
4037 Both invocations of Clang will result in the generation of a SPIR-V binary file
4038 `test.o` for 32 bit and 64 bit respectively. This file can be imported
4039 by an OpenCL driver that support SPIR-V consumption or it can be compiled
4040 further by offline SPIR-V consumer tools.
4042 Converting to SPIR-V produced with the optimization levels other than `-O0` is
4043 currently available as an experimental feature and it is not guaranteed to work
4046 Clang also supports integrated generation of SPIR-V without use of ``llvm-spirv``
4047 tool as an experimental feature when ``-fintegrated-objemitter`` flag is passed in
4050 .. code-block:: console
4052 $ clang --target=spirv32 -fintegrated-objemitter -c test.cl
4054 Note that only very basic functionality is supported at this point and therefore
4055 it is not suitable for arbitrary use cases. This feature is only enabled when clang
4056 build is configured with ``-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=SPIRV`` option.
4058 Linking is done using ``spirv-link`` from `the SPIRV-Tools project
4059 <https://github.com/KhronosGroup/SPIRV-Tools#linker>`_. Similar to other external
4060 linkers, Clang will expect ``spirv-link`` to be installed separately and to be
4061 present in the ``PATH`` environment variable. Please refer to `the build and
4062 installation instructions
4063 <https://github.com/KhronosGroup/SPIRV-Tools#build>`_.
4065 .. code-block:: console
4067 $ clang --target=spirv64 test1.cl test2.cl
4069 More information about the SPIR-V target settings and supported versions of SPIR-V
4070 format can be found in `the SPIR-V target guide
4071 <https://llvm.org/docs/SPIRVUsage.html>`__.
4078 clang-cl is an alternative command-line interface to Clang, designed for
4079 compatibility with the Visual C++ compiler, cl.exe.
4081 To enable clang-cl to find system headers, libraries, and the linker when run
4082 from the command-line, it should be executed inside a Visual Studio Native Tools
4083 Command Prompt or a regular Command Prompt where the environment has been set
4084 up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
4086 clang-cl can also be used from inside Visual Studio by selecting the LLVM
4087 Platform Toolset. The toolset is not part of the installer, but may be installed
4089 `Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_.
4090 To use the toolset, select a project in Solution Explorer, open its Property
4091 Page (Alt+F7), and in the "General" section of "Configuration Properties"
4092 change "Platform Toolset" to LLVM. Doing so enables an additional Property
4093 Page for selecting the clang-cl executable to use for builds.
4095 To use the toolset with MSBuild directly, invoke it with e.g.
4096 ``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain
4097 without modifying your project files.
4099 It's also possible to point MSBuild at clang-cl without changing toolset by
4100 passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.
4102 When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:
4106 cmake -G"Visual Studio 16 2019" -T LLVM ..
4108 When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and
4109 ``CMAKE_CXX_COMPILER`` variables to clang-cl:
4113 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"
4114 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..
4117 Command-Line Options
4118 --------------------
4120 To be compatible with cl.exe, clang-cl supports most of the same command-line
4121 options. Those options can start with either ``/`` or ``-``. It also supports
4122 some of Clang's core options, such as the ``-W`` options.
4124 Options that are known to clang-cl, but not currently supported, are ignored
4125 with a warning. For example:
4129 clang-cl.exe: warning: argument unused during compilation: '/AI'
4131 To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
4133 Options that are not known to clang-cl will be ignored by default. Use the
4134 ``-Werror=unknown-argument`` option in order to treat them as errors. If these
4135 options are spelled with a leading ``/``, they will be mistaken for a filename:
4139 clang-cl.exe: error: no such file or directory: '/foobar'
4141 Please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=clang&component=Driver>`_
4142 for any valid cl.exe flags that clang-cl does not understand.
4144 Execute ``clang-cl /?`` to see a list of supported options:
4148 CL.EXE COMPATIBILITY OPTIONS:
4149 /? Display available options
4150 /arch:<value> Set architecture for code generation
4151 /Brepro- Emit an object file which cannot be reproduced over time
4152 /Brepro Emit an object file which can be reproduced over time
4153 /clang:<arg> Pass <arg> to the clang driver
4154 /C Don't discard comments when preprocessing
4156 /d1PP Retain macro definitions in /E mode
4157 /d1reportAllClassLayout Dump record layout information
4158 /diagnostics:caret Enable caret and column diagnostics (on by default)
4159 /diagnostics:classic Disable column and caret diagnostics
4160 /diagnostics:column Disable caret diagnostics but keep column info
4161 /D <macro[=value]> Define macro
4162 /EH<value> Exception handling model
4163 /EP Disable linemarker output and preprocess to stdout
4164 /execution-charset:<value>
4165 Runtime encoding, supports only UTF-8
4166 /E Preprocess to stdout
4167 /FA Output assembly code file during compilation
4168 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
4169 /Fe<file or directory> Set output executable file or directory (ends in / or \)
4170 /FI <value> Include file before parsing
4171 /Fi<file> Set preprocess output file name (with /P)
4172 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
4178 /Fp<filename> Set pch filename (with /Yc and /Yu)
4179 /GA Assume thread-local variables are defined in the executable
4180 /Gd Set __cdecl as a default calling convention
4181 /GF- Disable string pooling
4182 /GF Enable string pooling (default)
4183 /GR- Disable emission of RTTI data
4184 /Gregcall Set __regcall as a default calling convention
4185 /GR Enable emission of RTTI data
4186 /Gr Set __fastcall as a default calling convention
4187 /GS- Disable buffer security check
4188 /GS Enable buffer security check (default)
4189 /Gs Use stack probes (default)
4190 /Gs<value> Set stack probe size (default 4096)
4191 /guard:<value> Enable Control Flow Guard with /guard:cf,
4192 or only the table with /guard:cf,nochecks.
4193 Enable EH Continuation Guard with /guard:ehcont
4194 /Gv Set __vectorcall as a default calling convention
4195 /Gw- Don't put each data item in its own section
4196 /Gw Put each data item in its own section
4197 /GX- Disable exception handling
4198 /GX Enable exception handling
4199 /Gy- Don't put each function in its own section (default)
4200 /Gy Put each function in its own section
4201 /Gz Set __stdcall as a default calling convention
4202 /help Display available options
4203 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
4204 /I <dir> Add directory to include search path
4205 /J Make char type unsigned
4206 /LDd Create debug DLL
4208 /link <options> Forward options to the linker
4209 /MDd Use DLL debug run-time
4210 /MD Use DLL run-time
4211 /MTd Use static debug run-time
4212 /MT Use static run-time
4213 /O0 Disable optimization
4214 /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy)
4215 /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy)
4216 /Ob0 Disable function inlining
4217 /Ob1 Only inline functions which are (explicitly or implicitly) marked inline
4218 /Ob2 Inline functions as deemed beneficial by the compiler
4219 /Od Disable optimization
4221 /Oi- Disable use of builtin functions
4222 /Oi Enable use of builtin functions
4223 /Os Optimize for size
4224 /Ot Optimize for speed
4225 /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead
4226 /Oy- Disable frame pointer omission (x86 only, default)
4227 /Oy Enable frame pointer omission (x86 only)
4228 /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-'
4229 /o <file or directory> Set output file or directory (ends in / or \)
4230 /P Preprocess to file
4231 /Qvec- Disable the loop vectorization passes
4232 /Qvec Enable the loop vectorization passes
4233 /showFilenames- Don't print the name of each compiled file (default)
4234 /showFilenames Print the name of each compiled file
4235 /showIncludes Print info about included files to stderr
4236 /source-charset:<value> Source encoding, supports only UTF-8
4237 /std:<value> Language standard to compile for
4238 /TC Treat all source files as C
4239 /Tc <filename> Specify a C source file
4240 /TP Treat all source files as C++
4241 /Tp <filename> Specify a C++ source file
4242 /utf-8 Set source and runtime encoding to UTF-8 (default)
4243 /U <macro> Undefine macro
4244 /vd<value> Control vtordisp placement
4245 /vmb Use a best-case representation method for member pointers
4246 /vmg Use a most-general representation for member pointers
4247 /vmm Set the default most-general representation to multiple inheritance
4248 /vms Set the default most-general representation to single inheritance
4249 /vmv Set the default most-general representation to virtual inheritance
4250 /volatile:iso Volatile loads and stores have standard semantics
4251 /volatile:ms Volatile loads and stores have acquire and release semantics
4252 /W0 Disable all warnings
4256 /W4 Enable -Wall and -Wextra
4257 /Wall Enable -Weverything
4258 /WX- Do not treat warnings as errors
4259 /WX Treat warnings as errors
4260 /w Disable all warnings
4261 /X Don't add %INCLUDE% to the include search path
4262 /Y- Disable precompiled headers, overrides /Yc and /Yu
4263 /Yc<filename> Generate a pch file for all code up to and including <filename>
4264 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
4265 /Z7 Enable CodeView debug information in object files
4266 /Zc:char8_t Enable C++2a char8_t type
4267 /Zc:char8_t- Disable C++2a char8_t type
4268 /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes
4269 /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default)
4270 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
4271 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
4272 /Zc:strictStrings Treat string literals as const
4273 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
4274 /Zc:threadSafeInit Enable thread-safe initialization of static variables
4275 /Zc:trigraphs- Disable trigraphs (default)
4276 /Zc:trigraphs Enable trigraphs
4277 /Zc:twoPhase- Disable two-phase name lookup in templates
4278 /Zc:twoPhase Enable two-phase name lookup in templates
4279 /Zi Alias for /Z7. Does not produce PDBs.
4280 /Zl Don't mention any default libraries in the object file
4281 /Zp Set the default maximum struct packing alignment to 1
4282 /Zp<value> Specify the default maximum struct packing alignment
4283 /Zs Run the preprocessor, parser and semantic analysis stages
4286 -### Print (but do not run) the commands to run for this compilation
4287 --analyze Run the static analyzer
4288 -faddrsig Emit an address-significance table
4289 -fansi-escape-codes Use ANSI escape codes for diagnostics
4290 -fblocks Enable the 'blocks' language feature
4291 -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none.
4292 -fcf-protection Enable cf-protection in 'full' mode
4293 -fcolor-diagnostics Use colors in diagnostics
4294 -fcomplete-member-pointers
4295 Require member pointer base types to be complete if they would be significant under the Microsoft ABI
4296 -fcoverage-mapping Generate coverage mapping to enable code coverage analysis
4297 -fcrash-diagnostics-dir=<dir>
4298 Put crash-report files in <dir>
4299 -fdebug-macro Emit macro debug information
4300 -fdelayed-template-parsing
4301 Parse templated function definitions at the end of the translation unit
4302 -fdiagnostics-absolute-paths
4303 Print absolute paths in diagnostics
4304 -fdiagnostics-parseable-fixits
4305 Print fix-its in machine parseable form
4306 -flto=<value> Set LTO mode to either 'full' or 'thin'
4307 -flto Enable LTO in 'full' mode
4308 -fmerge-all-constants Allow merging of constants
4309 -fms-compatibility-version=<value>
4310 Dot-separated value representing the Microsoft compiler version
4311 number to report in _MSC_VER (0 = don't define it (default))
4312 -fms-compatibility Enable full Microsoft Visual C++ compatibility
4313 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
4314 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
4315 (0 = don't define it (default))
4316 -fno-addrsig Don't emit an address-significance table
4317 -fno-builtin-<value> Disable implicit builtin knowledge of a specific function
4318 -fno-builtin Disable implicit builtin knowledge of functions
4319 -fno-complete-member-pointers
4320 Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI
4321 -fno-coverage-mapping Disable code coverage analysis
4322 -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash
4323 -fno-debug-macro Do not emit macro debug information
4324 -fno-delayed-template-parsing
4325 Disable delayed template parsing
4326 -fno-sanitize-address-poison-custom-array-cookie
4327 Disable poisoning array cookies when using custom operator new[] in AddressSanitizer
4328 -fno-sanitize-address-use-after-scope
4329 Disable use-after-scope detection in AddressSanitizer
4330 -fno-sanitize-address-use-odr-indicator
4331 Disable ODR indicator globals
4332 -fno-sanitize-ignorelist Don't use ignorelist file for sanitizers
4333 -fno-sanitize-cfi-cross-dso
4334 Disable control flow integrity (CFI) checks for cross-DSO calls.
4335 -fno-sanitize-coverage=<value>
4336 Disable specified features of coverage instrumentation for Sanitizers
4337 -fno-sanitize-memory-track-origins
4338 Disable origins tracking in MemorySanitizer
4339 -fno-sanitize-memory-use-after-dtor
4340 Disable use-after-destroy detection in MemorySanitizer
4341 -fno-sanitize-recover=<value>
4342 Disable recovery for specified sanitizers
4343 -fno-sanitize-stats Disable sanitizer statistics gathering.
4344 -fno-sanitize-thread-atomics
4345 Disable atomic operations instrumentation in ThreadSanitizer
4346 -fno-sanitize-thread-func-entry-exit
4347 Disable function entry/exit instrumentation in ThreadSanitizer
4348 -fno-sanitize-thread-memory-access
4349 Disable memory access instrumentation in ThreadSanitizer
4350 -fno-sanitize-trap=<value>
4351 Disable trapping for specified sanitizers
4352 -fno-standalone-debug Limit debug information produced to reduce size of debug binary
4353 -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version
4354 -fprofile-exclude-files=<value>
4355 Instrument only functions from files where names don't match all the regexes separated by a semi-colon
4356 -fprofile-filter-files=<value>
4357 Instrument only functions from files where names match any regex separated by a semi-colon
4358 -fprofile-instr-generate=<file>
4359 Generate instrumented code to collect execution counts into <file>
4360 (overridden by LLVM_PROFILE_FILE env var)
4361 -fprofile-instr-generate
4362 Generate instrumented code to collect execution counts into default.profraw file
4363 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
4364 -fprofile-instr-use=<value>
4365 Use instrumentation data for profile-guided optimization
4366 -fprofile-remapping-file=<file>
4367 Use the remappings described in <file> to match the profile data against names in the program
4368 -fprofile-list=<file>
4369 Filename defining the list of functions/files to instrument
4370 -fsanitize-address-field-padding=<value>
4371 Level of field padding for AddressSanitizer
4372 -fsanitize-address-globals-dead-stripping
4373 Enable linker dead stripping of globals in AddressSanitizer
4374 -fsanitize-address-poison-custom-array-cookie
4375 Enable poisoning array cookies when using custom operator new[] in AddressSanitizer
4376 -fsanitize-address-use-after-return=<mode>
4377 Select the mode of detecting stack use-after-return in AddressSanitizer: never | runtime (default) | always
4378 -fsanitize-address-use-after-scope
4379 Enable use-after-scope detection in AddressSanitizer
4380 -fsanitize-address-use-odr-indicator
4381 Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size
4382 -fsanitize-ignorelist=<value>
4383 Path to ignorelist file for sanitizers
4384 -fsanitize-cfi-cross-dso
4385 Enable control flow integrity (CFI) checks for cross-DSO calls.
4386 -fsanitize-cfi-icall-generalize-pointers
4387 Generalize pointers in CFI indirect call type signature checks
4388 -fsanitize-coverage=<value>
4389 Specify the type of coverage instrumentation for Sanitizers
4390 -fsanitize-hwaddress-abi=<value>
4391 Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor)
4392 -fsanitize-memory-track-origins=<value>
4393 Enable origins tracking in MemorySanitizer
4394 -fsanitize-memory-track-origins
4395 Enable origins tracking in MemorySanitizer
4396 -fsanitize-memory-use-after-dtor
4397 Enable use-after-destroy detection in MemorySanitizer
4398 -fsanitize-recover=<value>
4399 Enable recovery for specified sanitizers
4400 -fsanitize-stats Enable sanitizer statistics gathering.
4401 -fsanitize-thread-atomics
4402 Enable atomic operations instrumentation in ThreadSanitizer (default)
4403 -fsanitize-thread-func-entry-exit
4404 Enable function entry/exit instrumentation in ThreadSanitizer (default)
4405 -fsanitize-thread-memory-access
4406 Enable memory access instrumentation in ThreadSanitizer (default)
4407 -fsanitize-trap=<value> Enable trapping for specified sanitizers
4408 -fsanitize-undefined-strip-path-components=<number>
4409 Strip (or keep only, if negative) a given number of path components when emitting check metadata.
4410 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
4411 behavior. See user manual for available checks
4412 -fsplit-lto-unit Enables splitting of the LTO unit.
4413 -fstandalone-debug Emit full debug info for all types used by the program
4414 -fsyntax-only Run the preprocessor, parser and semantic analysis stages
4415 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
4416 -gcodeview-ghash Emit type record hashes in a .debug$H section
4417 -gcodeview Generate CodeView debug information
4418 -gline-directives-only Emit debug line info directives only
4419 -gline-tables-only Emit debug line number tables only
4420 -miamcu Use Intel MCU ABI
4421 -mllvm <value> Additional arguments to forward to LLVM's option processing
4422 -nobuiltininc Disable builtin #include directories
4423 -Qunused-arguments Don't emit warning for unused driver arguments
4424 -R<remark> Enable the specified remark
4425 --target=<value> Generate code for the given target
4426 --version Print version information
4427 -v Show commands to run and use verbose output
4428 -W<warning> Enable the specified warning
4429 -Xclang <arg> Pass <arg> to the clang compiler
4434 When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all
4435 of the ``<arg>`` arguments and process them as if they were passed to the clang
4436 driver. This mechanism allows you to pass flags that are not exposed in the
4437 clang-cl options or flags that have a different meaning when passed to the clang
4438 driver. Regardless of where they appear in the command line, the ``/clang:``
4439 arguments are treated as if they were passed at the end of the clang-cl command
4442 The /Zc:dllexportInlines- Option
4443 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4445 This causes the class-level `dllexport` and `dllimport` attributes to not apply
4446 to inline member functions, as they otherwise would. For example, in the code
4447 below `S::foo()` would normally be defined and exported by the DLL, but when
4448 using the ``/Zc:dllexportInlines-`` flag it is not:
4452 struct __declspec(dllexport) S {
4456 This has the benefit that the compiler doesn't need to emit a definition of
4457 `S::foo()` in every translation unit where the declaration is included, as it
4458 would otherwise do to ensure there's a definition in the DLL even if it's not
4459 used there. If the declaration occurs in a header file that's widely used, this
4460 can save significant compilation time and output size. It also reduces the
4461 number of functions exported by the DLL similarly to what
4462 ``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.
4463 Since the function declaration comes with an inline definition, users of the
4464 library can use that definition directly instead of importing it from the DLL.
4466 Note that the Microsoft Visual C++ compiler does not support this option, and
4467 if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the
4468 DLL must be compiled in the same way so that it doesn't attempt to dllimport
4469 the inline member functions. The reverse scenario should generally work though:
4470 a DLL compiled without this flag (such as a system library compiled with Visual
4471 C++) can be referenced from code compiled using the flag, meaning that the
4472 referencing code will use the inline definitions instead of importing them from
4475 Also note that like when using ``-fvisibility-inlines-hidden``, the address of
4476 `S::foo()` will be different inside and outside the DLL, breaking the C/C++
4477 standard requirement that functions have a unique address.
4479 The flag does not apply to explicit class template instantiation definitions or
4480 declarations, as those are typically used to explicitly provide a single
4481 definition in a DLL, (dllexported instantiation definition) or to signal that
4482 the definition is available elsewhere (dllimport instantiation declaration). It
4483 also doesn't apply to inline members with static local variables, to ensure
4484 that the same instance of the variable is used inside and outside the DLL.
4486 Using this flag can cause problems when inline functions that would otherwise
4487 be dllexported refer to internal symbols of a DLL. For example:
4493 struct __declspec(dllimport) S {
4494 void foo() { internal(); }
4497 Normally, references to `S::foo()` would use the definition in the DLL from
4498 which it was exported, and which presumably also has the definition of
4499 `internal()`. However, when using ``/Zc:dllexportInlines-``, the inline
4500 definition of `S::foo()` is used directly, resulting in a link error since
4501 `internal()` is not available. Even worse, if there is an inline definition of
4502 `internal()` containing a static local variable, we will now refer to a
4503 different instance of that variable than in the DLL:
4507 inline int internal() { static int x; return x++; }
4509 struct __declspec(dllimport) S {
4510 int foo() { return internal(); }
4513 This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can
4514 lead to the same issue. To avoid it in this case, make `S::foo()` or
4515 `internal()` non-inline, or mark them `dllimport/dllexport` explicitly.
4517 Finding Clang runtime libraries
4518 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4520 clang-cl supports several features that require runtime library support:
4522 - Address Sanitizer (ASan): ``-fsanitize=address``
4523 - Undefined Behavior Sanitizer (UBSan): ``-fsanitize=undefined``
4524 - Code coverage: ``-fprofile-instr-generate -fcoverage-mapping``
4525 - Profile Guided Optimization (PGO): ``-fprofile-instr-generate``
4526 - Certain math operations (int128 division) require the builtins library
4528 In order to use these features, the user must link the right runtime libraries
4529 into their program. These libraries are distributed alongside Clang in the
4530 library resource directory. Clang searches for the resource directory by
4531 searching relative to the Clang executable. For example, if LLVM is installed
4532 in ``C:\Program Files\LLVM``, then the profile runtime library will be located
4534 ``C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows\clang_rt.profile-x86_64.lib``.
4536 For UBSan, PGO, and coverage, Clang will emit object files that auto-link the
4537 appropriate runtime library, but the user generally needs to help the linker
4538 (whether it is ``lld-link.exe`` or MSVC ``link.exe``) find the library resource
4539 directory. Using the example installation above, this would mean passing
4540 ``/LIBPATH:C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows`` to the linker.
4541 If the user links the program with the ``clang`` or ``clang-cl`` drivers, the
4542 driver will pass this flag for them.
4544 If the linker cannot find the appropriate library, it will emit an error like
4547 $ clang-cl -c -fsanitize=undefined t.cpp
4549 $ lld-link t.obj -dll
4550 lld-link: error: could not open 'clang_rt.ubsan_standalone-x86_64.lib': no such file or directory
4551 lld-link: error: could not open 'clang_rt.ubsan_standalone_cxx-x86_64.lib': no such file or directory
4553 $ link t.obj -dll -nologo
4554 LINK : fatal error LNK1104: cannot open file 'clang_rt.ubsan_standalone-x86_64.lib'
4556 To fix the error, add the appropriate ``/libpath:`` flag to the link line.
4558 For ASan, as of this writing, the user is also responsible for linking against
4559 the correct ASan libraries.
4561 If the user is using the dynamic CRT (``/MD``), then they should add
4562 ``clang_rt.asan_dynamic-x86_64.lib`` to the link line as a regular input. For
4563 other architectures, replace x86_64 with the appropriate name here and below.
4565 If the user is using the static CRT (``/MT``), then different runtimes are used
4566 to produce DLLs and EXEs. To link a DLL, pass
4567 ``clang_rt.asan_dll_thunk-x86_64.lib``. To link an EXE, pass
4568 ``-wholearchive:clang_rt.asan-x86_64.lib``.
4570 Windows System Headers and Library Lookup
4571 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4573 clang-cl uses a set of different approaches to locate the right system libraries
4574 to link against when building code. The Windows environment uses libraries from
4575 three distinct sources:
4578 2. UCRT (Universal C Runtime)
4579 3. Visual C++ Tools (VCRuntime)
4581 The Windows SDK provides the import libraries and headers required to build
4582 programs against the Windows system packages. Underlying the Windows SDK is the
4583 UCRT, the universal C runtime.
4585 This difference is best illustrated by the various headers that one would find
4586 in the different categories. The WinSDK would contain headers such as
4587 `WinSock2.h` which is part of the Windows API surface, providing the Windows
4588 socketing interfaces for networking. UCRT provides the C library headers,
4589 including e.g. `stdio.h`. Finally, the Visual C++ tools provides the underlying
4590 Visual C++ Runtime headers such as `stdint.h` or `crtdefs.h`.
4592 There are various controls that allow the user control over where clang-cl will
4593 locate these headers. The default behaviour for the Windows SDK and UCRT is as
4596 1. Consult the command line.
4598 Anything the user specifies is always given precedence. The following
4599 extensions are part of the clang-cl toolset:
4603 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix
4604 environments. It allows the control of an alternate location to be treated
4605 as a system root. When specified, it will be used as the root where the
4606 `Windows Kits` is located.
4611 If `/winsysroot:` is not specified, the `/winsdkdir:` argument is consulted
4612 as a location to identify where the Windows SDK is located. Contrary to
4613 `/winsysroot:`, `/winsdkdir:` is expected to be the complete path rather
4614 than a root to locate `Windows Kits`.
4616 The `/winsdkversion:` flag allows the user to specify a version identifier
4617 for the SDK to prefer. When this is specified, no additional validation is
4618 performed and this version is preferred. If the version is not specified,
4619 the highest detected version number will be used.
4621 2. Consult the environment.
4623 TODO: This is not yet implemented.
4625 This will consult the environment variables:
4630 3. Fallback to the registry.
4632 If no arguments are used to indicate where the SDK is present, and the
4633 compiler is running on Windows, the registry is consulted to locate the
4636 The Visual C++ Toolset has a slightly more elaborate mechanism for detection.
4638 1. Consult the command line.
4642 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix
4643 environments. It allows the control of an alternate location to be treated
4644 as a system root. When specified, it will be used as the root where the
4645 `VC` directory is located.
4648 - `/vctoolsversion:`
4650 If `/winsysroot:` is not specified, the `/vctoolsdir:` argument is consulted
4651 as a location to identify where the Visual C++ Tools are located. If
4652 `/vctoolsversion:` is specified, that version is preferred, otherwise, the
4653 highest version detected is used.
4655 2. Consult the environment.
4657 - `/external:[VARIABLE]`
4659 This specifies a user identified environment variable which is treated as
4660 a path delimiter (`;`) separated list of paths to map into `-imsvc`
4661 arguments which are treated as `-isystem`.
4663 - `INCLUDE` and `EXTERNAL_INCLUDE`
4665 The path delimiter (`;`) separated list of paths will be mapped to
4666 `-imsvc` arguments which are treated as `-isystem`.
4668 - `LIB` (indirectly)
4670 The linker `link.exe` or `lld-link.exe` will honour the environment
4671 variable `LIB` which is a path delimiter (`;`) set of paths to consult for
4672 the import libraries to use when linking the final target.
4674 The following environment variables will be consulted and used to form paths
4675 to validate and load content from as appropriate:
4677 - `VCToolsInstallDir`
4681 3. Consult `ISetupConfiguration` [Windows Only]
4683 Assuming that the toolchain is built with `USE_MSVC_SETUP_API` defined and
4684 is running on Windows, the Visual Studio COM interface `ISetupConfiguration`
4685 will be used to locate the installation of the MSVC toolset.
4687 4. Fallback to the registry [DEPRECATED]
4689 The registry information is used to help locate the installation as a final
4690 fallback. This is only possible for pre-VS2017 installations and is
4691 considered deprecated.