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 .. option:: --warning-suppression-mappings=foo.txt
156 :ref:`Suppress certain diagnostics for certain files. <warning_suppression_mappings>`
158 .. _cl_diag_formatting:
160 Formatting of Diagnostics
161 ^^^^^^^^^^^^^^^^^^^^^^^^^
163 Clang aims to produce beautiful diagnostics by default, particularly for
164 new users that first come to Clang. However, different people have
165 different preferences, and sometimes Clang is driven not by a human,
166 but by a program that wants consistent and easily parsable output. For
167 these cases, Clang provides a wide range of options to control the exact
168 output format of the diagnostics that it generates.
170 .. _opt_fshow-column:
172 .. option:: -f[no-]show-column
174 Print column number in diagnostic.
176 This option, which defaults to on, controls whether or not Clang
177 prints the column number of a diagnostic. For example, when this is
178 enabled, Clang will print something like:
182 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
187 When this is disabled, Clang will print "test.c:28: warning..." with
190 The printed column numbers count bytes from the beginning of the
191 line; take care if your source contains multibyte characters.
193 .. _opt_fshow-source-location:
195 .. option:: -f[no-]show-source-location
197 Print source file/line/column information in diagnostic.
199 This option, which defaults to on, controls whether or not Clang
200 prints the filename, line number and column number of a diagnostic.
201 For example, when this is enabled, Clang will print something like:
205 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
210 When this is disabled, Clang will not print the "test.c:28:8: "
213 .. _opt_fcaret-diagnostics:
215 .. option:: -f[no-]caret-diagnostics
217 Print source line and ranges from source code in diagnostic.
218 This option, which defaults to on, controls whether or not Clang
219 prints the source line, source ranges, and caret when emitting a
220 diagnostic. For example, when this is enabled, Clang will print
225 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
230 .. option:: -f[no-]color-diagnostics
232 This option, which defaults to on when a color-capable terminal is
233 detected, controls whether or not Clang prints diagnostics in color.
235 When this option is enabled, Clang will use colors to highlight
236 specific parts of the diagnostic, e.g.,
238 .. nasty hack to not lose our dignity
243 <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>
245 <span style="color:green">^</span>
246 <span style="color:green">//</span>
249 When this is disabled, Clang will just print:
253 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
258 If the ``NO_COLOR`` environment variable is defined and not empty
259 (regardless of value), color diagnostics are disabled. If ``NO_COLOR`` is
260 defined and ``-fcolor-diagnostics`` is passed on the command line, Clang
261 will honor the command line argument.
263 .. option:: -fansi-escape-codes
265 Controls whether ANSI escape codes are used instead of the Windows Console
266 API to output colored diagnostics. This option is only used on Windows and
269 .. option:: -fdiagnostics-format=clang/msvc/vi
271 Changes diagnostic output format to better match IDEs and command line tools.
273 This option controls the output format of the filename, line number,
274 and column printed in diagnostic messages. The options, and their
275 affect on formatting a simple conversion diagnostic, follow:
280 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
285 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
290 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
292 .. _opt_fdiagnostics-show-option:
294 .. option:: -f[no-]diagnostics-show-option
296 Enable ``[-Woption]`` information in diagnostic line.
298 This option, which defaults to on, controls whether or not Clang
299 prints the associated :ref:`warning group <cl_diag_warning_groups>`
300 option name when outputting a warning diagnostic. For example, in
305 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
310 Passing **-fno-diagnostics-show-option** will prevent Clang from
311 printing the [:option:`-Wextra-tokens`] information in
312 the diagnostic. This information tells you the flag needed to enable
313 or disable the diagnostic, either from the command line or through
314 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
316 .. option:: -fdiagnostics-show-category=none/id/name
318 Enable printing category information in diagnostic line.
320 This option, which defaults to "none", controls whether or not Clang
321 prints the category associated with a diagnostic when emitting it.
322 Each diagnostic may or many not have an associated category, if it
323 has one, it is listed in the diagnostic categorization field of the
324 diagnostic line (in the []'s).
326 For example, a format string warning will produce these three
327 renditions based on the setting of this option:
331 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
332 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
333 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
335 This category can be used by clients that want to group diagnostics
336 by category, so it should be a high level category. We want dozens
337 of these, not hundreds or thousands of them.
339 .. _opt_fsave-optimization-record:
341 .. option:: -f[no-]save-optimization-record[=<format>]
343 Enable optimization remarks during compilation and write them to a separate
346 This option, which defaults to off, controls whether Clang writes
347 optimization reports to a separate file. By recording diagnostics in a file,
348 users can parse or sort the remarks in a convenient way.
350 By default, the serialization format is YAML.
352 The supported serialization formats are:
354 - .. _opt_fsave_optimization_record_yaml:
356 ``-fsave-optimization-record=yaml``: A structured YAML format.
358 - .. _opt_fsave_optimization_record_bitstream:
360 ``-fsave-optimization-record=bitstream``: A binary format based on LLVM
363 The output file is controlled by :option:`-foptimization-record-file`.
365 In the absence of an explicit output file, the file is chosen using the
368 ``<base>.opt.<format>``
370 where ``<base>`` is based on the output file of the compilation (whether
371 it's explicitly specified through `-o` or not) when used with `-c` or `-S`.
374 * ``clang -fsave-optimization-record -c in.c -o out.o`` will generate
377 * ``clang -fsave-optimization-record -c in.c`` will generate
380 When targeting (Thin)LTO, the base is derived from the output filename, and
381 the extension is not dropped.
383 When targeting ThinLTO, the following scheme is used:
385 ``<base>.opt.<format>.thin.<num>.<format>``
387 Darwin-only: when used for generating a linked binary from a source file
388 (through an intermediate object file), the driver will invoke `cc1` to
389 generate a temporary object file. The temporary remark file will be emitted
390 next to the object file, which will then be picked up by `dsymutil` and
391 emitted in the .dSYM bundle. This is available for all formats except YAML.
395 ``clang -fsave-optimization-record=bitstream in.c -o out`` will generate
397 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.o``
399 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.opt.bitstream``
403 * ``out.dSYM/Contents/Resources/Remarks/out``
405 Darwin-only: compiling for multiple architectures will use the following
408 ``<base>-<arch>.opt.<format>``
410 Note that this is incompatible with passing the
411 :option:`-foptimization-record-file` option.
413 .. option:: -foptimization-record-file
415 Control the file to which optimization reports are written. This implies
416 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`.
418 On Darwin platforms, this is incompatible with passing multiple
419 ``-arch <arch>`` options.
421 .. option:: -foptimization-record-passes
423 Only include passes which match a specified regular expression.
425 When optimization reports are being output (see
426 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
427 option controls the passes that will be included in the final report.
429 If this option is not used, all the passes are included in the optimization
432 .. _opt_fdiagnostics-show-hotness:
434 .. option:: -f[no-]diagnostics-show-hotness
436 Enable profile hotness information in diagnostic line.
438 This option controls whether Clang prints the profile hotness associated
439 with diagnostics in the presence of profile-guided optimization information.
440 This is currently supported with optimization remarks (see
441 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
442 allows users to focus on the hot optimization remarks that are likely to be
443 more relevant for run-time performance.
445 For example, in this output, the block containing the callsite of `foo` was
446 executed 3000 times according to the profile data:
450 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
451 sum += foo(x, x - 2);
454 This option is implied when
455 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
456 Otherwise, it defaults to off.
458 .. option:: -fdiagnostics-hotness-threshold
460 Prevent optimization remarks from being output if they do not have at least
463 This option, which defaults to zero, controls the minimum hotness an
464 optimization remark would need in order to be output by Clang. This is
465 currently supported with optimization remarks (see :ref:`Options to Emit
466 Optimization Reports <rpass>`) when profile hotness information in
467 diagnostics is enabled (see
468 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
470 .. _opt_fdiagnostics-fixit-info:
472 .. option:: -f[no-]diagnostics-fixit-info
474 Enable "FixIt" information in the diagnostics output.
476 This option, which defaults to on, controls whether or not Clang
477 prints the information on how to fix a specific diagnostic
478 underneath it when it knows. For example, in this output:
482 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
487 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
488 printing the "//" line at the end of the message. This information
489 is useful for users who may not understand what is wrong, but can be
490 confusing for machine parsing.
492 .. _opt_fdiagnostics-print-source-range-info:
494 .. option:: -fdiagnostics-print-source-range-info
496 Print machine parsable information about source ranges.
497 This option makes Clang print information about source ranges in a machine
498 parsable format after the file/line/column number information. The
499 information is a simple sequence of brace enclosed ranges, where each range
500 lists the start and end line/column locations. For example, in this output:
504 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
505 P = (P-42) + Gamma*4;
508 The {}'s are generated by -fdiagnostics-print-source-range-info.
510 The printed column numbers count bytes from the beginning of the
511 line; take care if your source contains multibyte characters.
513 .. option:: -fdiagnostics-parseable-fixits
515 Print Fix-Its in a machine parseable form.
517 This option makes Clang print available Fix-Its in a machine
518 parseable format at the end of diagnostics. The following example
519 illustrates the format:
523 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
525 The range printed is a half-open range, so in this example the
526 characters at column 25 up to but not including column 29 on line 7
527 in t.cpp should be replaced with the string "Gamma". Either the
528 range or the replacement string may be empty (representing strict
529 insertions and strict erasures, respectively). Both the file name
530 and the insertion string escape backslash (as "\\\\"), tabs (as
531 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
532 non-printable characters (as octal "\\xxx").
534 The printed column numbers count bytes from the beginning of the
535 line; take care if your source contains multibyte characters.
537 .. option:: -fno-elide-type
539 Turns off elision in template type printing.
541 The default for template type printing is to elide as many template
542 arguments as possible, removing those which are the same in both
543 template types, leaving only the differences. Adding this flag will
544 print all the template arguments. If supported by the terminal,
545 highlighting will still appear on differing arguments.
551 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;
557 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;
559 .. option:: -fdiagnostics-show-template-tree
561 Template type diffing prints a text tree.
563 For diffing large templated types, this option will cause Clang to
564 display the templates as an indented text tree, one argument per
565 line, with differences marked inline. This is compatible with
572 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;
574 With :option:`-fdiagnostics-show-template-tree`:
578 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
587 .. option:: -fcaret-diagnostics-max-lines:
589 Controls how many lines of code clang prints for diagnostics. By default,
590 clang prints a maximum of 16 lines of code.
593 .. option:: -fdiagnostics-show-line-numbers:
595 Controls whether clang will print a margin containing the line number on
596 the left of each line of code it prints for diagnostics.
602 test.cpp:5:1: error: 'main' must return 'int'
608 With -fno-diagnostics-show-line-numbers:
612 test.cpp:5:1: error: 'main' must return 'int'
619 .. _cl_diag_warning_groups:
621 Individual Warning Groups
622 ^^^^^^^^^^^^^^^^^^^^^^^^^
624 TODO: Generate this from tblgen. Define one anchor per warning group.
626 .. option:: -Wextra-tokens
628 Warn about excess tokens at the end of a preprocessor directive.
630 This option, which defaults to on, enables warnings about extra
631 tokens at the end of preprocessor directives. For example:
635 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
639 These extra tokens are not strictly conforming, and are usually best
640 handled by commenting them out.
642 .. option:: -Wambiguous-member-template
644 Warn about unqualified uses of a member template whose name resolves to
645 another template at the location of the use.
647 This option, which defaults to on, enables a warning in the
652 template<typename T> struct set{};
653 template<typename T> struct trait { typedef const T& type; };
655 template<typename T> void set(typename trait<T>::type value) {}
662 C++ [basic.lookup.classref] requires this to be an error, but,
663 because it's hard to work around, Clang downgrades it to a warning
666 .. option:: -Wbind-to-temporary-copy
668 Warn about an unusable copy constructor when binding a reference to a
671 This option enables warnings about binding a
672 reference to a temporary when the temporary doesn't have a usable
673 copy constructor. For example:
680 NonCopyable(const NonCopyable&);
682 void foo(const NonCopyable&);
684 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
689 struct NonCopyable2 {
691 NonCopyable2(NonCopyable2&);
693 void foo(const NonCopyable2&);
695 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
698 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
699 whose instantiation produces a compile error, that error will still
700 be a hard error in C++98 mode even if this warning is turned off.
702 Options to Control Clang Crash Diagnostics
703 ------------------------------------------
705 As unbelievable as it may sound, Clang does crash from time to time.
706 Generally, this only occurs to those living on the `bleeding
707 edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great
708 lengths to assist you in filing a bug report. Specifically, Clang
709 generates preprocessed source file(s) and associated run script(s) upon
710 a crash. These files should be attached to a bug report to ease
711 reproducibility of the failure. Below are the command line options to
712 control the crash diagnostics.
714 .. option:: -fcrash-diagnostics=<val>
718 * ``off`` (Disable auto-generation of preprocessed source files during a clang crash.)
719 * ``compiler`` (Generate diagnostics for compiler crashes (default))
720 * ``all`` (Generate diagnostics for all tools which support it)
722 .. option:: -fno-crash-diagnostics
724 Disable auto-generation of preprocessed source files during a clang crash.
726 The -fno-crash-diagnostics flag can be helpful for speeding the process
727 of generating a delta reduced test case.
729 .. option:: -fcrash-diagnostics-dir=<dir>
731 Specify where to write the crash diagnostics files; defaults to the
732 usual location for temporary files.
734 .. envvar:: CLANG_CRASH_DIAGNOSTICS_DIR=<dir>
736 Like ``-fcrash-diagnostics-dir=<dir>``, specifies where to write the
737 crash diagnostics files, but with lower precedence than the option.
739 Clang is also capable of generating preprocessed source file(s) and associated
740 run script(s) even without a crash. This is specially useful when trying to
741 generate a reproducer for warnings or errors while using modules.
743 .. option:: -gen-reproducer
745 Generates preprocessed source files, a reproducer script and if relevant, a
746 cache containing: built module pcm's and all headers needed to rebuild the
751 Options to Emit Optimization Reports
752 ------------------------------------
754 Optimization reports trace, at a high-level, all the major decisions
755 done by compiler transformations. For instance, when the inliner
756 decides to inline function ``foo()`` into ``bar()``, or the loop unroller
757 decides to unroll a loop N times, or the vectorizer decides to
758 vectorize a loop body.
760 Clang offers a family of flags which the optimizers can use to emit
761 a diagnostic in three cases:
763 1. When the pass makes a transformation (`-Rpass`).
765 2. When the pass fails to make a transformation (`-Rpass-missed`).
767 3. When the pass determines whether or not to make a transformation
770 NOTE: Although the discussion below focuses on `-Rpass`, the exact
771 same options apply to `-Rpass-missed` and `-Rpass-analysis`.
773 Since there are dozens of passes inside the compiler, each of these flags
774 take a regular expression that identifies the name of the pass which should
775 emit the associated diagnostic. For example, to get a report from the inliner,
776 compile the code with:
778 .. code-block:: console
780 $ clang -O2 -Rpass=inline code.cc -o code
781 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
782 int bar(int j) { return foo(j, j - 2); }
785 Note that remarks from the inliner are identified with `[-Rpass=inline]`.
786 To request a report from every optimization pass, you should use
787 `-Rpass=.*` (in fact, you can use any valid POSIX regular
788 expression). However, do not expect a report from every transformation
789 made by the compiler. Optimization remarks do not really make sense
790 outside of the major transformations (e.g., inlining, vectorization,
791 loop optimizations) and not every optimization pass supports this
794 Note that when using profile-guided optimization information, profile hotness
795 information can be included in the remarks (see
796 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
801 1. Optimization remarks that refer to function names will display the
802 mangled name of the function. Since these remarks are emitted by the
803 back end of the compiler, it does not know anything about the input
804 language, nor its mangling rules.
806 2. Some source locations are not displayed correctly. The front end has
807 a more detailed source location tracking than the locations included
808 in the debug info (e.g., the front end can locate code inside macro
809 expansions). However, the locations used by `-Rpass` are
810 translated from debug annotations. That translation can be lossy,
811 which results in some remarks having no location information.
813 Options to Emit Resource Consumption Reports
814 --------------------------------------------
816 These are options that report execution time and consumed memory of different
819 .. option:: -fproc-stat-report=
821 This option requests driver to print used memory and execution time of each
822 compilation step. The ``clang`` driver during execution calls different tools,
823 like compiler, assembler, linker etc. With this option the driver reports
824 total execution time, the execution time spent in user mode and peak memory
825 usage of each the called tool. Value of the option specifies where the report
826 is sent to. If it specifies a regular file, the data are saved to this file in
829 .. code-block:: console
831 $ clang -fproc-stat-report=abc foo.c
833 clang-11,"/tmp/foo-123456.o",92000,84000,87536
834 ld,"a.out",900,8000,53568
836 The data on each row represent:
838 * file name of the tool executable,
839 * output file name in quotes,
840 * total execution time in microseconds,
841 * execution time in user mode in microseconds,
842 * peak memory usage in Kb.
844 It is possible to specify this option without any value. In this case statistics
845 are printed on standard output in human readable format:
847 .. code-block:: console
849 $ clang -fproc-stat-report foo.c
850 clang-11: output=/tmp/foo-855a8e.o, total=68.000 ms, user=60.000 ms, mem=86920 Kb
851 ld: output=a.out, total=8.000 ms, user=4.000 ms, mem=52320 Kb
853 The report file specified in the option is locked for write, so this option
854 can be used to collect statistics in parallel builds. The report file is not
855 cleared, new data is appended to it, thus making possible to accumulate build
858 You can also use environment variables to control the process statistics reporting.
859 Setting ``CC_PRINT_PROC_STAT`` to ``1`` enables the feature, the report goes to
860 stdout in human readable format.
861 Setting ``CC_PRINT_PROC_STAT_FILE`` to a fully qualified file path makes it report
862 process statistics to the given file in the CSV format. Specifying a relative
863 path will likely lead to multiple files with the same name created in different
864 directories, since the path is relative to a changing working directory.
866 These environment variables are handy when you need to request the statistics
867 report without changing your build scripts or alter the existing set of compiler
868 options. Note that ``-fproc-stat-report`` take precedence over ``CC_PRINT_PROC_STAT``
869 and ``CC_PRINT_PROC_STAT_FILE``.
871 .. code-block:: console
873 $ export CC_PRINT_PROC_STAT=1
874 $ export CC_PRINT_PROC_STAT_FILE=~/project-build-proc-stat.csv
879 Clang options that don't fit neatly into other categories.
881 .. option:: -fgnuc-version=
883 This flag controls the value of ``__GNUC__`` and related macros. This flag
884 does not enable or disable any GCC extensions implemented in Clang. Setting
885 the version to zero causes Clang to leave ``__GNUC__`` and other
886 GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined.
890 When emitting a dependency file, use formatting conventions appropriate
891 for NMake or Jom. Ignored unless another option causes Clang to emit a
894 When Clang emits a dependency file (e.g., you supplied the -M option)
895 most filenames can be written to the file without any special formatting.
896 Different Make tools will treat different sets of characters as "special"
897 and use different conventions for telling the Make tool that the character
898 is actually part of the filename. Normally Clang uses backslash to "escape"
899 a special character, which is the convention used by GNU Make. The -MV
900 option tells Clang to put double-quotes around the entire filename, which
901 is the convention used by NMake and Jom.
903 .. option:: -femit-dwarf-unwind=<value>
905 When to emit DWARF unwind (EH frame) info. This is a Mach-O-specific option.
909 * ``no-compact-unwind`` - Only emit DWARF unwind when compact unwind encodings
910 aren't available. This is the default for arm64.
911 * ``always`` - Always emit DWARF unwind regardless.
912 * ``default`` - Use the platform-specific default (``always`` for all
913 non-arm64-platforms).
915 ``no-compact-unwind`` is a performance optimization -- Clang will emit smaller
916 object files that are more quickly processed by the linker. This may cause
917 binary compatibility issues on older x86_64 targets, however, so use it with
920 .. option:: -fdisable-block-signature-string
922 Instruct clang not to emit the signature string for blocks. Disabling the
923 string can potentially break existing code that relies on it. Users should
924 carefully consider this possibiilty when using the flag.
926 .. _configuration-files:
931 Configuration files group command-line options and allow all of them to be
932 specified just by referencing the configuration file. They may be used, for
933 example, to collect options required to tune compilation for particular
934 target, such as ``-L``, ``-I``, ``-l``, ``--sysroot``, codegen options, etc.
936 Configuration files can be either specified on the command line or loaded
937 from default locations. If both variants are present, the default configuration
938 files are loaded first.
940 The command line option ``--config=`` can be used to specify explicit
941 configuration files in a Clang invocation. If the option is used multiple times,
942 all specified files are loaded, in order. For example:
946 clang --config=/home/user/cfgs/testing.txt
947 clang --config=debug.cfg --config=runtimes.cfg
949 If the provided argument contains a directory separator, it is considered as
950 a file path, and options are read from that file. Otherwise the argument is
951 treated as a file name and is searched for sequentially in the directories:
955 - the directory where Clang executable resides.
957 Both user and system directories for configuration files can be specified
958 either during build or during runtime. At build time, use
959 ``CLANG_CONFIG_FILE_USER_DIR`` and ``CLANG_CONFIG_FILE_SYSTEM_DIR``. At run
960 time use the ``--config-user-dir=`` and ``--config-system-dir=`` command line
961 options. Specifying config directories at runtime overrides the config
962 directories set at build time The first file found is used. It is an error if
963 the required file cannot be found.
965 The default configuration files are searched for in the same directories
966 following the rules described in the next paragraphs. Loading default
967 configuration files can be disabled entirely via passing
968 the ``--no-default-config`` flag.
970 First, the algorithm searches for a configuration file named
971 ``<triple>-<driver>.cfg`` where `triple` is the triple for the target being
972 built for, and `driver` is the name of the currently used driver. The algorithm
973 first attempts to use the canonical name for the driver used, then falls back
974 to the one found in the executable name.
976 The following canonical driver names are used:
978 - ``clang`` for the ``gcc`` driver (used to compile C programs)
979 - ``clang++`` for the ``gxx`` driver (used to compile C++ programs)
980 - ``clang-cpp`` for the ``cpp`` driver (pure preprocessor)
981 - ``clang-cl`` for the ``cl`` driver
982 - ``flang`` for the ``flang`` driver
983 - ``clang-dxc`` for the ``dxc`` driver
985 For example, when calling ``x86_64-pc-linux-gnu-clang-g++``,
986 the driver will first attempt to use the configuration file named::
988 x86_64-pc-linux-gnu-clang++.cfg
990 If this file is not found, it will attempt to use the name found
991 in the executable instead::
993 x86_64-pc-linux-gnu-clang-g++.cfg
995 Note that options such as ``--driver-mode=``, ``--target=``, ``-m32`` affect
996 the search algorithm. For example, the aforementioned executable called with
997 ``-m32`` argument will instead search for::
999 i386-pc-linux-gnu-clang++.cfg
1001 If none of the aforementioned files are found, the driver will instead search
1002 for separate driver and target configuration files and attempt to load both.
1003 The former is named ``<driver>.cfg`` while the latter is named
1004 ``<triple>.cfg``. Similarly to the previous variants, the canonical driver name
1005 will be preferred, and the compiler will fall back to the actual name.
1007 For example, ``x86_64-pc-linux-gnu-clang-g++`` will attempt to load two
1008 configuration files named respectively::
1011 x86_64-pc-linux-gnu.cfg
1013 with fallback to trying::
1016 x86_64-pc-linux-gnu.cfg
1018 It is not an error if either of these files is not found.
1020 The configuration file consists of command-line options specified on one or
1021 more lines. Lines composed of whitespace characters only are ignored as well as
1022 lines in which the first non-blank character is ``#``. Long options may be split
1023 between several lines by a trailing backslash. Here is example of a
1028 # Several options on line
1029 -c --target=x86_64-unknown-linux-gnu
1031 # Long option split between lines
1032 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\
1035 # other config files may be included
1038 Files included by ``@file`` directives in configuration files are resolved
1039 relative to the including file. For example, if a configuration file
1040 ``~/.llvm/target.cfg`` contains the directive ``@os/linux.opts``, the file
1041 ``linux.opts`` is searched for in the directory ``~/.llvm/os``. Another way to
1042 include a file content is using the command line option ``--config=``. It works
1043 similarly but the included file is searched for using the rules for configuration
1046 To generate paths relative to the configuration file, the ``<CFGDIR>`` token may
1047 be used. This will expand to the absolute path of the directory containing the
1050 In cases where a configuration file is deployed alongside SDK contents, the
1051 SDK directory can remain fully portable by using ``<CFGDIR>`` prefixed paths.
1052 In this way, the user may only need to specify a root configuration file with
1053 ``--config=`` to establish every aspect of the SDK with the compiler:
1058 -isystem <CFGDIR>/include
1060 -T <CFGDIR>/ldscripts/link.ld
1062 Language and Target-Independent Features
1063 ========================================
1065 Controlling Errors and Warnings
1066 -------------------------------
1068 Clang provides a number of ways to control which code constructs cause
1069 it to emit errors and warning messages, and how they are displayed to
1072 Controlling How Clang Displays Diagnostics
1073 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1075 When Clang emits a diagnostic, it includes rich information in the
1076 output, and gives you fine-grain control over which information is
1077 printed. Clang has the ability to print this information, and these are
1078 the options that control it:
1080 #. A file/line/column indicator that shows exactly where the diagnostic
1081 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
1082 :ref:`-fshow-source-location <opt_fshow-source-location>`].
1083 #. A categorization of the diagnostic as a note, warning, error, or
1085 #. A text string that describes what the problem is.
1086 #. An option that indicates how to control the diagnostic (for
1087 diagnostics that support it)
1088 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
1089 #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
1090 for clients that want to group diagnostics by class (for diagnostics
1092 [:option:`-fdiagnostics-show-category`].
1093 #. The line of source code that the issue occurs on, along with a caret
1094 and ranges that indicate the important locations
1095 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
1096 #. "FixIt" information, which is a concise explanation of how to fix the
1097 problem (when Clang is certain it knows)
1098 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
1099 #. A machine-parsable representation of the ranges involved (off by
1101 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
1103 For more information please see :ref:`Formatting of
1104 Diagnostics <cl_diag_formatting>`.
1109 All diagnostics are mapped into one of these 6 classes:
1118 .. _diagnostics_categories:
1120 Diagnostic Categories
1121 ^^^^^^^^^^^^^^^^^^^^^
1123 Though not shown by default, diagnostics may each be associated with a
1124 high-level category. This category is intended to make it possible to
1125 triage builds that produce a large number of errors or warnings in a
1128 Categories are not shown by default, but they can be turned on with the
1129 :option:`-fdiagnostics-show-category` option.
1130 When set to "``name``", the category is printed textually in the
1131 diagnostic output. When it is set to "``id``", a category number is
1132 printed. The mapping of category names to category id's can be obtained
1133 by running '``clang --print-diagnostic-categories``'.
1135 Controlling Diagnostics via Command Line Flags
1136 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1138 TODO: -W flags, -pedantic, etc
1140 .. _pragma_gcc_diagnostic:
1142 Controlling Diagnostics via Pragmas
1143 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1145 Clang can also control what diagnostics are enabled through the use of
1146 pragmas in the source code. This is useful for turning off specific
1147 warnings in a section of source code. Clang supports GCC's pragma for
1148 compatibility with existing source code, so ``#pragma GCC diagnostic``
1149 and ``#pragma clang diagnostic`` are synonyms for Clang. GCC will ignore
1150 ``#pragma clang diagnostic``, though.
1152 The pragma may control any warning that can be used from the command
1153 line. Warnings may be set to ignored, warning, error, or fatal. The
1154 following example code will tell Clang or GCC to ignore the ``-Wall``
1159 #pragma GCC diagnostic ignored "-Wall"
1161 Clang also allows you to push and pop the current warning state. This is
1162 particularly useful when writing a header file that will be compiled by
1163 other people, because you don't know what warning flags they build with.
1165 In the below example :option:`-Wextra-tokens` is ignored for only a single line
1166 of code, after which the diagnostics return to whatever state had previously
1172 #endif foo // warning: extra tokens at end of #endif directive
1174 #pragma GCC diagnostic push
1175 #pragma GCC diagnostic ignored "-Wextra-tokens"
1178 #endif foo // no warning
1180 #pragma GCC diagnostic pop
1182 The push and pop pragmas will save and restore the full diagnostic state
1183 of the compiler, regardless of how it was set. It should be noted that while Clang
1184 supports the GCC pragma, Clang and GCC do not support the exact same set
1185 of warnings, so even when using GCC compatible #pragmas there is no
1186 guarantee that they will have identical behaviour on both compilers.
1188 Clang also doesn't yet support GCC behavior for ``#pragma diagnostic pop``
1189 that doesn't have a corresponding ``#pragma diagnostic push``. In this case
1190 GCC pretends that there is a ``#pragma diagnostic push`` at the very beginning
1191 of the source file, so "unpaired" ``#pragma diagnostic pop`` matches that
1192 implicit push. This makes a difference for ``#pragma GCC diagnostic ignored``
1193 which are not guarded by push and pop. Refer to
1194 `GCC documentation <https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html>`_
1197 Like GCC, Clang accepts ``ignored``, ``warning``, ``error``, and ``fatal``
1198 severity levels. They can be used to change severity of a particular diagnostic
1199 for a region of source file. A notable difference from GCC is that diagnostic
1200 not enabled via command line arguments can't be enabled this way yet.
1202 Some diagnostics associated with a ``-W`` flag have the error severity by
1203 default. They can be ignored or downgraded to warnings:
1208 #pragma GCC diagnostic warning "-Wimplicit-function-declaration"
1209 int main(void) { puts(""); }
1211 In addition to controlling warnings and errors generated by the compiler, it is
1212 possible to generate custom warning and error messages through the following
1217 // The following will produce warning messages
1218 #pragma message "some diagnostic message"
1219 #pragma GCC warning "TODO: replace deprecated feature"
1221 // The following will produce an error message
1222 #pragma GCC error "Not supported"
1224 These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
1225 directives, except that they may also be embedded into preprocessor macros via
1226 the C99 ``_Pragma`` operator, for example:
1231 #define DEFER(M,...) M(__VA_ARGS__)
1232 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
1234 CUSTOM_ERROR("Feature not available");
1236 Controlling Diagnostics in System Headers
1237 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1239 Warnings are suppressed when they occur in system headers. By default,
1240 an included file is treated as a system header if it is found in an
1241 include path specified by ``-isystem``, but this can be overridden in
1244 The ``system_header`` pragma can be used to mark the current file as
1245 being a system header. No warnings will be produced from the location of
1246 the pragma onwards within the same file.
1251 #endif foo // warning: extra tokens at end of #endif directive
1253 #pragma clang system_header
1256 #endif foo // no warning
1258 The `--system-header-prefix=` and `--no-system-header-prefix=`
1259 command-line arguments can be used to override whether subsets of an include
1260 path are treated as system headers. When the name in a ``#include`` directive
1261 is found within a header search path and starts with a system prefix, the
1262 header is treated as a system header. The last prefix on the
1263 command-line which matches the specified header name takes precedence.
1266 .. code-block:: console
1268 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
1269 --no-system-header-prefix=x/y/
1271 Here, ``#include "x/a.h"`` is treated as including a system header, even
1272 if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
1273 as not including a system header, even if the header is found in
1276 A ``#include`` directive which finds a file relative to the current
1277 directory is treated as including a system header if the including file
1278 is treated as a system header.
1280 Controlling Deprecation Diagnostics in Clang-Provided C Runtime Headers
1281 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1283 Clang is responsible for providing some of the C runtime headers that cannot be
1284 provided by a platform CRT, such as implementation limits or when compiling in
1285 freestanding mode. Define the ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro
1286 prior to including such a C runtime header to disable the deprecation warnings.
1287 Note that the C Standard Library headers are allowed to transitively include
1288 other standard library headers (see 7.1.2p5), and so the most appropriate use
1289 of this macro is to set it within the build system using ``-D`` or before any
1290 include directives in the translation unit.
1294 #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
1295 #include <stdint.h> // Clang CRT deprecation warnings are disabled.
1296 #include <stdatomic.h> // Clang CRT deprecation warnings are disabled.
1298 .. _diagnostics_enable_everything:
1300 Enabling All Diagnostics
1301 ^^^^^^^^^^^^^^^^^^^^^^^^
1303 In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
1304 by passing :option:`-Weverything`. This works as expected with
1305 :option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some
1306 diagnostics contradict each other, therefore, users of :option:`-Weverything`
1307 often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat`
1308 because they contradict recent C++ standards.
1310 Since :option:`-Weverything` enables every diagnostic, we generally don't
1311 recommend using it. `-Wall` `-Wextra` are a better choice for most projects.
1312 Using :option:`-Weverything` means that updating your compiler is more difficult
1313 because you're exposed to experimental diagnostics which might be of lower
1314 quality than the default ones. If you do use :option:`-Weverything` then we
1315 advise that you address all new compiler diagnostics as they get added to Clang,
1316 either by fixing everything they find or explicitly disabling that diagnostic
1317 with its corresponding `Wno-` option.
1319 Note that when combined with :option:`-w` (which disables all warnings),
1320 disabling all warnings wins.
1322 .. _warning_suppression_mappings:
1324 Controlling Diagnostics via Suppression Mappings
1325 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1327 Warning suppression mappings enable users to suppress Clang's diagnostics at a
1328 per-file granularity. This allows enforcing diagnostics in specific parts of the
1329 project even if there are violations in some headers.
1331 .. code-block:: console
1337 $ clang --warning-suppression-mappings=mapping.txt -Wunused foo/bar.cc
1338 # This compilation won't emit any unused findings for sources under foo/
1339 # directory. But it'll still complain for all the other sources, e.g:
1341 #include "dir/include.h" // Clang flags unused declarations here.
1342 #include "foo/include.h" // but unused warnings under this source is omitted.
1343 #include "next_to_bar_cc.h" // as are unused warnings from this header file.
1344 // Further, unused warnings in the remainder of bar.cc are also omitted.
1347 See :doc:`WarningSuppressionMappings` for details about the file format and
1350 Controlling Static Analyzer Diagnostics
1351 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1353 While not strictly part of the compiler, the diagnostics from Clang's
1354 `static analyzer <https://clang-analyzer.llvm.org>`_ can also be
1355 influenced by the user via changes to the source code. See the available
1356 `annotations <https://clang-analyzer.llvm.org/annotations.html>`_ and the
1358 page <https://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
1361 .. _usersmanual-precompiled-headers:
1366 `Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_
1367 are a general approach employed by many compilers to reduce compilation
1368 time. The underlying motivation of the approach is that it is common for
1369 the same (and often large) header files to be included by multiple
1370 source files. Consequently, compile times can often be greatly improved
1371 by caching some of the (redundant) work done by a compiler to process
1372 headers. Precompiled header files, which represent one of many ways to
1373 implement this optimization, are literally files that represent an
1374 on-disk cache that contains the vital information necessary to reduce
1375 some of the work needed to process a corresponding header file. While
1376 details of precompiled headers vary between compilers, precompiled
1377 headers have been shown to be highly effective at speeding up program
1378 compilation on systems with very large system headers (e.g., macOS).
1380 Generating a PCH File
1381 ^^^^^^^^^^^^^^^^^^^^^
1383 To generate a PCH file using Clang, one invokes Clang with the
1384 `-x <language>-header` option. This mirrors the interface in GCC
1385 for generating PCH files:
1387 .. code-block:: console
1389 $ gcc -x c-header test.h -o test.h.gch
1390 $ clang -x c-header test.h -o test.h.pch
1395 A PCH file can then be used as a prefix header when a ``-include-pch``
1396 option is passed to ``clang``:
1398 .. code-block:: console
1400 $ clang -include-pch test.h.pch test.c -o test
1402 The ``clang`` driver will check if the PCH file ``test.h.pch`` is
1403 available; if so, the contents of ``test.h`` (and the files it includes)
1404 will be processed from the PCH file. Otherwise, Clang will report an error.
1408 Clang does *not* automatically use PCH files for headers that are directly
1409 included within a source file or indirectly via :option:`-include`.
1412 .. code-block:: console
1414 $ clang -x c-header test.h -o test.h.pch
1417 $ clang test.c -o test
1419 In this example, ``clang`` will not automatically use the PCH file for
1420 ``test.h`` since ``test.h`` was included directly in the source file and not
1421 specified on the command line using ``-include-pch``.
1423 Relocatable PCH Files
1424 ^^^^^^^^^^^^^^^^^^^^^
1426 It is sometimes necessary to build a precompiled header from headers
1427 that are not yet in their final, installed locations. For example, one
1428 might build a precompiled header within the build tree that is then
1429 meant to be installed alongside the headers. Clang permits the creation
1430 of "relocatable" precompiled headers, which are built with a given path
1431 (into the build directory) and can later be used from an installed
1434 To build a relocatable precompiled header, place your headers into a
1435 subdirectory whose structure mimics the installed location. For example,
1436 if you want to build a precompiled header for the header ``mylib.h``
1437 that will be installed into ``/usr/include``, create a subdirectory
1438 ``build/usr/include`` and place the header ``mylib.h`` into that
1439 subdirectory. If ``mylib.h`` depends on other headers, then they can be
1440 stored within ``build/usr/include`` in a way that mimics the installed
1443 Building a relocatable precompiled header requires two additional
1444 arguments. First, pass the ``--relocatable-pch`` flag to indicate that
1445 the resulting PCH file should be relocatable. Second, pass
1446 ``-isysroot /path/to/build``, which makes all includes for your library
1447 relative to the build directory. For example:
1449 .. code-block:: console
1451 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
1453 When loading the relocatable PCH file, the various headers used in the
1454 PCH file are found from the system header root. For example, ``mylib.h``
1455 can be found in ``/usr/include/mylib.h``. If the headers are installed
1456 in some other system root, the ``-isysroot`` option can be used provide
1457 a different system root from which the headers will be based. For
1458 example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
1459 ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
1461 Relocatable precompiled headers are intended to be used in a limited
1462 number of cases where the compilation environment is tightly controlled
1463 and the precompiled header cannot be generated after headers have been
1466 .. _controlling-fp-behavior:
1468 Controlling Floating Point Behavior
1469 -----------------------------------
1471 Clang provides a number of ways to control floating point behavior, including
1472 with command line options and source pragmas. This section
1473 describes the various floating point semantic modes and the corresponding options.
1475 .. csv-table:: Floating Point Semantic Modes
1476 :header: "Mode", "Values"
1479 "ffp-exception-behavior", "{ignore, strict, maytrap}",
1480 "fenv_access", "{off, on}", "(none)"
1481 "frounding-math", "{dynamic, tonearest, downward, upward, towardzero}"
1482 "ffp-contract", "{on, off, fast, fast-honor-pragmas}"
1483 "fdenormal-fp-math", "{IEEE, PreserveSign, PositiveZero}"
1484 "fdenormal-fp-math-fp32", "{IEEE, PreserveSign, PositiveZero}"
1485 "fmath-errno", "{on, off}"
1486 "fhonor-nans", "{on, off}"
1487 "fhonor-infinities", "{on, off}"
1488 "fsigned-zeros", "{on, off}"
1489 "freciprocal-math", "{on, off}"
1490 "fallow-approximate-fns", "{on, off}"
1491 "fassociative-math", "{on, off}"
1492 "fcomplex-arithmetic", "{basic, improved, full, promoted}"
1494 This table describes the option settings that correspond to the three
1495 floating point semantic models: precise (the default), strict, and fast.
1498 .. csv-table:: Floating Point Models
1499 :header: "Mode", "Precise", "Strict", "Fast", "Aggressive"
1500 :widths: 25, 25, 25, 25, 25
1502 "except_behavior", "ignore", "strict", "ignore", "ignore"
1503 "fenv_access", "off", "on", "off", "off"
1504 "rounding_mode", "tonearest", "dynamic", "tonearest", "tonearest"
1505 "contract", "on", "off", "fast", "fast"
1506 "support_math_errno", "on", "on", "off", "off"
1507 "no_honor_nans", "off", "off", "off", "on"
1508 "no_honor_infinities", "off", "off", "off", "on"
1509 "no_signed_zeros", "off", "off", "on", "on"
1510 "allow_reciprocal", "off", "off", "on", "on"
1511 "allow_approximate_fns", "off", "off", "on", "on"
1512 "allow_reassociation", "off", "off", "on", "on"
1513 "complex_arithmetic", "full", "full", "promoted", "basic"
1515 The ``-ffp-model`` option does not modify the ``fdenormal-fp-math``
1516 setting, but it does have an impact on whether ``crtfastmath.o`` is
1517 linked. Because linking ``crtfastmath.o`` has a global effect on the
1518 program, and because the global denormal handling can be changed in
1519 other ways, the state of ``fdenormal-fp-math`` handling cannot
1520 be assumed in any function based on fp-model. See :ref:`crtfastmath.o`
1523 .. option:: -ffast-math
1525 Enable fast-math mode. This option lets the
1526 compiler make aggressive, potentially-lossy assumptions about
1527 floating-point math. These include:
1529 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1530 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1531 ``(a + b) * c == a * c + b * c``),
1532 * No ``NaN`` or infinite values will be operands or results of
1533 floating-point operations,
1534 * ``+0`` and ``-0`` may be treated as interchangeable.
1536 ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor
1537 macro. Some math libraries recognize this macro and change their behavior.
1538 With the exception of ``-ffp-contract=fast``, using any of the options
1539 below to disable any of the individual optimizations in ``-ffast-math``
1540 will cause ``__FAST_MATH__`` to no longer be set.
1541 ``-ffast-math`` enables ``-fcx-limited-range``.
1543 This option implies:
1545 * ``-fno-honor-infinities``
1547 * ``-fno-honor-nans``
1551 * ``-fno-math-errno``
1553 * ``-ffinite-math-only``
1555 * ``-fassociative-math``
1557 * ``-freciprocal-math``
1559 * ``-fno-signed-zeros``
1561 * ``-fno-trapping-math``
1563 * ``-fno-rounding-math``
1565 * ``-ffp-contract=fast``
1567 Note: ``-ffast-math`` causes ``crtfastmath.o`` to be linked with code unless
1568 ``-shared`` or ``-mno-daz-ftz`` is present. See
1569 :ref:`crtfastmath.o` for more details.
1571 .. option:: -fno-fast-math
1573 Disable fast-math mode. This options disables unsafe floating-point
1574 optimizations by preventing the compiler from making any transformations that
1575 could affect the results.
1577 This option implies:
1579 * ``-fhonor-infinities``
1583 * ``-fno-approx-func``
1585 * ``-fno-finite-math-only``
1587 * ``-fno-associative-math``
1589 * ``-fno-reciprocal-math``
1591 * ``-fsigned-zeros``
1593 * ``-ffp-contract=on``
1595 Also, this option resets following options to their target-dependent defaults.
1597 * ``-f[no-]math-errno``
1599 There is ambiguity about how ``-ffp-contract``, ``-ffast-math``,
1600 and ``-fno-fast-math`` behave when combined. To keep the value of
1601 ``-ffp-contract`` consistent, we define this set of rules:
1603 * ``-ffast-math`` sets ``ffp-contract`` to ``fast``.
1605 * ``-fno-fast-math`` sets ``-ffp-contract`` to ``on`` (``fast`` for CUDA and
1608 * If ``-ffast-math`` and ``-ffp-contract`` are both seen, but
1609 ``-ffast-math`` is not followed by ``-fno-fast-math``, ``ffp-contract``
1610 will be given the value of whichever option was last seen.
1612 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has been seen at least
1613 once, the ``ffp-contract`` will get the value of the last seen value of
1616 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has not been seen, the
1617 ``-ffp-contract`` setting is determined by the default value of
1620 Note: ``-fno-fast-math`` causes ``crtfastmath.o`` to not be linked with code
1621 unless ``-mdaz-ftz`` is present.
1623 .. option:: -fdenormal-fp-math=<value>
1625 Select which denormal numbers the code is permitted to require.
1629 * ``ieee`` - IEEE 754 denormal numbers
1630 * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 0
1631 * ``positive-zero`` - denormals are flushed to positive zero
1633 The default value depends on the target. For most targets, defaults to
1636 .. option:: -f[no-]strict-float-cast-overflow
1638 When a floating-point value is not representable in a destination integer
1639 type, the code has undefined behavior according to the language standard.
1640 By default, Clang will not guarantee any particular result in that case.
1641 With the 'no-strict' option, Clang will saturate towards the smallest and
1642 largest representable integer values instead. NaNs will be converted to zero.
1643 Defaults to ``-fstrict-float-cast-overflow``.
1645 .. option:: -f[no-]math-errno
1647 Require math functions to indicate errors by setting errno.
1648 The default varies by ToolChain. ``-fno-math-errno`` allows optimizations
1649 that might cause standard C math functions to not set ``errno``.
1650 For example, on some systems, the math function ``sqrt`` is specified
1651 as setting ``errno`` to ``EDOM`` when the input is negative. On these
1652 systems, the compiler cannot normally optimize a call to ``sqrt`` to use
1653 inline code (e.g. the x86 ``sqrtsd`` instruction) without additional
1654 checking to ensure that ``errno`` is set appropriately.
1655 ``-fno-math-errno`` permits these transformations.
1657 On some targets, math library functions never set ``errno``, and so
1658 ``-fno-math-errno`` is the default. This includes most BSD-derived
1659 systems, including Darwin.
1661 .. option:: -f[no-]trapping-math
1663 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.
1665 - The option ``-ftrapping-math`` behaves identically to ``-ffp-exception-behavior=strict``.
1666 - The option ``-fno-trapping-math`` behaves identically to ``-ffp-exception-behavior=ignore``. This is the default.
1668 .. option:: -ffp-contract=<value>
1670 Specify when the compiler is permitted to form fused floating-point
1671 operations, such as fused multiply-add (FMA). Fused operations are
1672 permitted to produce more precise results than performing the same
1673 operations separately.
1675 The C standard permits intermediate floating-point results within an
1676 expression to be computed with more precision than their type would
1677 normally allow. This permits operation fusing, and Clang takes advantage
1678 of this by default. This behavior can be controlled with the ``FP_CONTRACT``
1679 and ``clang fp contract`` pragmas. Please refer to the pragma documentation
1680 for a description of how the pragmas interact with this option.
1684 * ``fast`` (fuse across statements disregarding pragmas, default for CUDA)
1685 * ``on`` (fuse in the same statement unless dictated by pragmas, default for languages other than CUDA/HIP)
1686 * ``off`` (never fuse)
1687 * ``fast-honor-pragmas`` (fuse across statements unless dictated by pragmas, default for HIP)
1689 .. option:: -f[no-]honor-infinities
1691 Allow floating-point optimizations that assume arguments and results are
1693 Defaults to ``-fhonor-infinities``.
1695 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1696 has the same effect as specifying ``-ffinite-math-only``.
1698 .. option:: -f[no-]honor-nans
1700 Allow floating-point optimizations that assume arguments and results are
1702 Defaults to ``-fhonor-nans``.
1704 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1705 has the same effect as specifying ``-ffinite-math-only``.
1707 .. option:: -f[no-]approx-func
1709 Allow certain math function calls (such as ``log``, ``sqrt``, ``pow``, etc)
1710 to be replaced with an approximately equivalent set of instructions
1711 or alternative math function calls. For example, a ``pow(x, 0.25)``
1712 may be replaced with ``sqrt(sqrt(x))``, despite being an inexact result
1713 in cases where ``x`` is ``-0.0`` or ``-inf``.
1714 Defaults to ``-fno-approx-func``.
1716 .. option:: -f[no-]signed-zeros
1718 Allow optimizations that ignore the sign of floating point zeros.
1719 Defaults to ``-fsigned-zeros``.
1721 .. option:: -f[no-]associative-math
1723 Allow floating point operations to be reassociated.
1724 Defaults to ``-fno-associative-math``.
1726 .. option:: -f[no-]reciprocal-math
1728 Allow division operations to be transformed into multiplication by a
1729 reciprocal. This can be significantly faster than an ordinary division
1730 but can also have significantly less precision. Defaults to
1731 ``-fno-reciprocal-math``.
1733 .. option:: -f[no-]unsafe-math-optimizations
1735 Allow unsafe floating-point optimizations.
1736 ``-funsafe-math-optimizations`` also implies:
1739 * ``-fassociative-math``
1740 * ``-freciprocal-math``
1741 * ``-fno-signed-zeros``
1742 * ``-fno-trapping-math``
1743 * ``-ffp-contract=fast``
1745 ``-fno-unsafe-math-optimizations`` implies:
1747 * ``-fno-approx-func``
1748 * ``-fno-associative-math``
1749 * ``-fno-reciprocal-math``
1750 * ``-fsigned-zeros``
1751 * ``-ffp-contract=on``
1753 There is ambiguity about how ``-ffp-contract``,
1754 ``-funsafe-math-optimizations``, and ``-fno-unsafe-math-optimizations``
1755 behave when combined. Explanation in :option:`-fno-fast-math` also applies
1758 Defaults to ``-fno-unsafe-math-optimizations``.
1760 .. option:: -f[no-]finite-math-only
1762 Allow floating-point optimizations that assume arguments and results are
1763 not NaNs or +-Inf. ``-ffinite-math-only`` defines the
1764 ``__FINITE_MATH_ONLY__`` preprocessor macro.
1765 ``-ffinite-math-only`` implies:
1767 * ``-fno-honor-infinities``
1768 * ``-fno-honor-nans``
1770 ``-ffno-inite-math-only`` implies:
1772 * ``-fhonor-infinities``
1775 Defaults to ``-fno-finite-math-only``.
1777 .. option:: -f[no-]rounding-math
1779 Force floating-point operations to honor the dynamically-set rounding mode by default.
1781 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.
1783 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``.
1785 - The option ``-fno-rounding-math`` allows the compiler to assume that the rounding mode is set to ``FE_TONEAREST``. This is the default.
1786 - 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.
1788 .. option:: -ffp-model=<value>
1790 Specify floating point behavior. ``-ffp-model`` is an umbrella
1791 option that encompasses functionality provided by other, single
1792 purpose, floating point options. Valid values are: ``precise``, ``strict``,
1793 ``fast``, and ``aggressive``.
1796 * ``precise`` Disables optimizations that are not value-safe on
1797 floating-point data, although FP contraction (FMA) is enabled
1798 (``-ffp-contract=on``). This is the default behavior. This value resets
1799 ``-fmath-errno`` to its target-dependent default.
1800 * ``strict`` Enables ``-frounding-math`` and
1801 ``-ffp-exception-behavior=strict``, and disables contractions (FMA). All
1802 of the ``-ffast-math`` enablements are disabled. Enables
1803 ``STDC FENV_ACCESS``: by default ``FENV_ACCESS`` is disabled. This option
1804 setting behaves as though ``#pragma STDC FENV_ACCESS ON`` appeared at the
1805 top of the source file.
1806 * ``fast`` Behaves identically to specifying ``-funsafe-math-optimizations``,
1807 ``-fno-math-errno`` and ``-fcomplex-arithmetic=promoted``
1808 ``ffp-contract=fast``
1809 * ``aggressive`` Behaves identically to specifying both ``-ffast-math`` and
1810 ``ffp-contract=fast``
1812 Note: If your command line specifies multiple instances
1813 of the ``-ffp-model`` option, or if your command line option specifies
1814 ``-ffp-model`` and later on the command line selects a floating point
1815 option that has the effect of negating part of the ``ffp-model`` that
1816 has been selected, then the compiler will issue a diagnostic warning
1817 that the override has occurred.
1819 .. option:: -ffp-exception-behavior=<value>
1821 Specify the floating-point exception behavior.
1823 Valid values are: ``ignore``, ``maytrap``, and ``strict``.
1824 The default value is ``ignore``. Details:
1826 * ``ignore`` The compiler assumes that the exception status flags will not be read and that floating point exceptions will be masked.
1827 * ``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.
1828 * ``strict`` The compiler ensures that all transformations strictly preserve the floating point exception semantics of the original code.
1830 .. option:: -ffp-eval-method=<value>
1832 Specify the floating-point evaluation method for intermediate results within
1833 a single expression of the code.
1835 Valid values are: ``source``, ``double``, and ``extended``.
1836 For 64-bit targets, the default value is ``source``. For 32-bit x86 targets
1837 however, in the case of NETBSD 6.99.26 and under, the default value is
1838 ``double``; in the case of NETBSD greater than 6.99.26, with NoSSE, the
1839 default value is ``extended``, with SSE the default value is ``source``.
1842 * ``source`` The compiler uses the floating-point type declared in the source program as the evaluation method.
1843 * ``double`` The compiler uses ``double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``double``.
1844 * ``extended`` The compiler uses ``long double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``long double``.
1846 .. option:: -f[no-]protect-parens
1848 This option pertains to floating-point types, complex types with
1849 floating-point components, and vectors of these types. Some arithmetic
1850 expression transformations that are mathematically correct and permissible
1851 according to the C and C++ language standards may be incorrect when dealing
1852 with floating-point types, such as reassociation and distribution. Further,
1853 the optimizer may ignore parentheses when computing arithmetic expressions
1854 in circumstances where the parenthesized and unparenthesized expression
1855 express the same mathematical value. For example (a+b)+c is the same
1856 mathematical value as a+(b+c), but the optimizer is free to evaluate the
1857 additions in any order regardless of the parentheses. When enabled, this
1858 option forces the optimizer to honor the order of operations with respect
1859 to parentheses in all circumstances.
1860 Defaults to ``-fno-protect-parens``.
1862 Note that floating-point contraction (option `-ffp-contract=`) is disabled
1863 when `-fprotect-parens` is enabled. Also note that in safe floating-point
1864 modes, such as `-ffp-model=precise` or `-ffp-model=strict`, this option
1865 has no effect because the optimizer is prohibited from making unsafe
1868 .. option:: -fexcess-precision:
1870 The C and C++ standards allow floating-point expressions to be computed as if
1871 intermediate results had more precision (and/or a wider range) than the type
1872 of the expression strictly allows. This is called excess precision
1874 Excess precision arithmetic can improve the accuracy of results (although not
1875 always), and it can make computation significantly faster if the target lacks
1876 direct hardware support for arithmetic in a particular type. However, it can
1877 also undermine strict floating-point reproducibility.
1879 Under the standards, assignments and explicit casts force the operand to be
1880 converted to its formal type, discarding any excess precision. Because data
1881 can only flow between statements via an assignment, this means that the use
1882 of excess precision arithmetic is a reliable local property of a single
1883 statement, and results do not change based on optimization. However, when
1884 excess precision arithmetic is in use, Clang does not guarantee strict
1885 reproducibility, and future compiler releases may recognize more
1886 opportunities to use excess precision arithmetic, e.g. with floating-point
1889 Clang does not use excess precision arithmetic for most types or on most
1890 targets. For example, even on pre-SSE X86 targets where ``float`` and
1891 ``double`` computations must be performed in the 80-bit X87 format, Clang
1892 rounds all intermediate results correctly for their type. Clang currently
1893 uses excess precision arithmetic by default only for the following types and
1896 * ``_Float16`` on X86 targets without ``AVX512-FP16``.
1898 The ``-fexcess-precision=<value>`` option can be used to control the use of
1899 excess precision arithmetic. Valid values are:
1901 * ``standard`` - The default. Allow the use of excess precision arithmetic
1902 under the constraints of the C and C++ standards. Has no effect except on
1903 the types and targets listed above.
1904 * ``fast`` - Accepted for GCC compatibility, but currently treated as an
1905 alias for ``standard``.
1906 * ``16`` - Forces ``_Float16`` operations to be emitted without using excess
1907 precision arithmetic.
1909 .. option:: -fcomplex-arithmetic=<value>:
1911 This option specifies the implementation for complex multiplication and division.
1913 Valid values are: ``basic``, ``improved``, ``full`` and ``promoted``.
1915 * ``basic`` Implementation of complex division and multiplication using
1916 algebraic formulas at source precision. No special handling to avoid
1917 overflow. NaN and infinite values are not handled.
1918 * ``improved`` Implementation of complex division using the Smith algorithm
1919 at source precision. Smith's algorithm for complex division.
1920 See SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
1921 This value offers improved handling for overflow in intermediate
1922 calculations, but overflow may occur. NaN and infinite values are not
1923 handled in some cases.
1924 * ``full`` Implementation of complex division and multiplication using a
1925 call to runtime library functions (generally the case, but the BE might
1926 sometimes replace the library call if it knows enough about the potential
1927 range of the inputs). Overflow and non-finite values are handled by the
1928 library implementation. For the case of multiplication overflow will occur in
1929 accordance with normal floating-point rules. This is the default value.
1930 * ``promoted`` Implementation of complex division using algebraic formulas at
1931 higher precision. Overflow is handled. Non-finite values are handled in some
1932 cases. If the target does not have native support for a higher precision
1933 data type, the implementation for the complex operation using the Smith
1934 algorithm will be used. Overflow may still occur in some cases. NaN and
1935 infinite values are not handled.
1937 .. option:: -fcx-limited-range:
1939 This option is aliased to ``-fcomplex-arithmetic=basic``. It enables the
1940 naive mathematical formulas for complex division and multiplication with no
1941 NaN checking of results. The default is ``-fno-cx-limited-range`` aliased to
1942 ``-fcomplex-arithmetic=full``. This option is enabled by the ``-ffast-math``
1945 .. option:: -fcx-fortran-rules:
1947 This option is aliased to ``-fcomplex-arithmetic=improved``. It enables the
1948 naive mathematical formulas for complex multiplication and enables application
1949 of Smith's algorithm for complex division. See SMITH, R. L. Algorithm 116:
1950 Complex division. Commun. ACM 5, 8 (1962).
1951 The default is ``-fno-cx-fortran-rules`` aliased to
1952 ``-fcomplex-arithmetic=full``.
1954 .. _floating-point-environment:
1956 Accessing the floating point environment
1957 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1958 Many targets allow floating point operations to be configured to control things
1959 such as how inexact results should be rounded and how exceptional conditions
1960 should be handled. This configuration is called the floating point environment.
1961 C and C++ restrict access to the floating point environment by default, and the
1962 compiler is allowed to assume that all operations are performed in the default
1963 environment. When code is compiled in this default mode, operations that depend
1964 on the environment (such as floating-point arithmetic and `FLT_ROUNDS`) may have
1965 undefined behavior if the dynamic environment is not the default environment; for
1966 example, `FLT_ROUNDS` may or may not simply return its default value for the target
1967 instead of reading the dynamic environment, and floating-point operations may be
1968 optimized as if the dynamic environment were the default. Similarly, it is undefined
1969 behavior to change the floating point environment in this default mode, for example
1970 by calling the `fesetround` function.
1971 C provides two pragmas to allow code to dynamically modify the floating point environment:
1973 - ``#pragma STDC FENV_ACCESS ON`` allows dynamic changes to the entire floating
1976 - ``#pragma STDC FENV_ROUND FE_DYNAMIC`` allows dynamic changes to just the floating
1977 point rounding mode. This may be more optimizable than ``FENV_ACCESS ON`` because
1978 the compiler can still ignore the possibility of floating-point exceptions by default.
1980 Both of these can be used either at the start of a block scope, in which case
1981 they cover all code in that scope (unless they're turned off in a child scope),
1982 or at the top level in a file, in which case they cover all subsequent function
1983 bodies until they're turned off. Note that it is undefined behavior to enter
1984 code that is *not* covered by one of these pragmas from code that *is* covered
1985 by one of these pragmas unless the floating point environment has been restored
1986 to its default state. See the C standard for more information about these pragmas.
1988 The command line option ``-frounding-math`` behaves as if the translation unit
1989 began with ``#pragma STDC FENV_ROUND FE_DYNAMIC``. The command line option
1990 ``-ffp-model=strict`` behaves as if the translation unit began with ``#pragma STDC FENV_ACCESS ON``.
1992 Code that just wants to use a specific rounding mode for specific floating point
1993 operations can avoid most of the hazards of the dynamic floating point environment
1994 by using ``#pragma STDC FENV_ROUND`` with a value other than ``FE_DYNAMIC``.
1998 A note about ``crtfastmath.o``
1999 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2000 ``-ffast-math`` and ``-funsafe-math-optimizations`` without the ``-shared``
2001 option cause ``crtfastmath.o`` to be
2002 automatically linked, which adds a static constructor that sets the FTZ/DAZ
2003 bits in MXCSR, affecting not only the current compilation unit but all static
2004 and shared libraries included in the program. This decision can be overridden
2005 by using either the flag ``-mdaz-ftz`` or ``-mno-daz-ftz`` to respectively
2006 link or not link ``crtfastmath.o``.
2008 .. _FLT_EVAL_METHOD:
2010 A note about ``__FLT_EVAL_METHOD__``
2011 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2012 The ``__FLT_EVAL_METHOD__`` is not defined as a traditional macro, and so it
2013 will not appear when dumping preprocessor macros. Instead, the value
2014 ``__FLT_EVAL_METHOD__`` expands to is determined at the point of expansion
2015 either from the value set by the ``-ffp-eval-method`` command line option or
2016 from the target. This is because the ``__FLT_EVAL_METHOD__`` macro
2017 cannot expand to the correct evaluation method in the presence of a ``#pragma``
2018 which alters the evaluation method. An error is issued if
2019 ``__FLT_EVAL_METHOD__`` is expanded inside a scope modified by
2020 ``#pragma clang fp eval_method``.
2022 .. _fp-constant-eval:
2024 A note about Floating Point Constant Evaluation
2025 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2027 In C, the only place floating point operations are guaranteed to be evaluated
2028 during translation is in the initializers of variables of static storage
2029 duration, which are all notionally initialized before the program begins
2030 executing (and thus before a non-default floating point environment can be
2031 entered). But C++ has many more contexts where floating point constant
2032 evaluation occurs. Specifically: for static/thread-local variables,
2033 first try evaluating the initializer in a constant context, including in the
2034 constant floating point environment (just like in C), and then, if that fails,
2035 fall back to emitting runtime code to perform the initialization (which might
2036 in general be in a different floating point environment).
2038 Consider this example when compiled with ``-frounding-math``
2040 .. code-block:: console
2042 constexpr float func_01(float x, float y) {
2045 float V1 = func_01(1.0F, 0x0.000001p0F);
2047 The C++ rule is that initializers for static storage duration variables are
2048 first evaluated during translation (therefore, in the default rounding mode),
2049 and only evaluated at runtime (and therefore in the runtime rounding mode) if
2050 the compile-time evaluation fails. This is in line with the C rules;
2051 C11 F.8.5 says: *All computation for automatic initialization is done (as if)
2052 at execution time; thus, it is affected by any operative modes and raises
2053 floating-point exceptions as required by IEC 60559 (provided the state for the
2054 FENV_ACCESS pragma is ‘‘on’’). All computation for initialization of objects
2055 that have static or thread storage duration is done (as if) at translation
2056 time.* C++ generalizes this by adding another phase of initialization
2057 (at runtime) if the translation-time initialization fails, but the
2058 translation-time evaluation of the initializer of succeeds, it will be
2059 treated as a constant initializer.
2062 .. _controlling-code-generation:
2064 Controlling Code Generation
2065 ---------------------------
2067 Clang provides a number of ways to control code generation. The options
2070 .. option:: -f[no-]sanitize=check1,check2,...
2072 Turn on runtime checks for various forms of undefined or suspicious
2075 This option controls whether Clang adds runtime checks for various
2076 forms of undefined or suspicious behavior, and is disabled by
2077 default. If a check fails, a diagnostic message is produced at
2078 runtime explaining the problem. The main checks are:
2080 - .. _opt_fsanitize_address:
2082 ``-fsanitize=address``:
2083 :doc:`AddressSanitizer`, a memory error
2085 - .. _opt_fsanitize_thread:
2087 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
2088 - .. _opt_fsanitize_memory:
2090 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
2091 a detector of uninitialized reads. Requires instrumentation of all
2093 - .. _opt_fsanitize_undefined:
2095 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
2096 a fast and compatible undefined behavior checker.
2098 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
2100 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
2101 checks. Requires ``-flto``.
2102 - ``-fsanitize=kcfi``: kernel indirect call forward-edge control flow
2104 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
2105 protection against stack-based memory corruption errors.
2106 - ``-fsanitize=realtime``: :doc:`RealtimeSanitizer`,
2107 a real-time safety checker.
2109 There are more fine-grained checks available: see
2110 the :ref:`list <ubsan-checks>` of specific kinds of
2111 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
2112 of control flow integrity schemes.
2114 The ``-fsanitize=`` argument must also be provided when linking, in
2115 order to link to the appropriate runtime library.
2117 It is not possible to combine more than one of the ``-fsanitize=address``,
2118 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
2121 .. option:: -f[no-]sanitize-recover=check1,check2,...
2123 .. option:: -f[no-]sanitize-recover[=all]
2125 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
2126 If the check is fatal, program will halt after the first error
2127 of this kind is detected and error report is printed.
2129 By default, non-fatal checks are those enabled by
2130 :doc:`UndefinedBehaviorSanitizer`,
2131 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
2132 sanitizers may not support recovery (or not support it by default
2133 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
2136 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
2137 This means that if a check has been configured to trap elsewhere on the
2138 command line, or if the check traps by default, this flag will not have
2139 any effect unless that sanitizer's trapping behavior is disabled with
2140 ``-fno-sanitize-trap``.
2142 For example, if a command line contains the flags ``-fsanitize=undefined
2143 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
2144 will have no effect on its own; it will need to be accompanied by
2145 ``-fno-sanitize-trap=alignment``.
2147 .. option:: -f[no-]sanitize-trap=check1,check2,...
2149 .. option:: -f[no-]sanitize-trap[=all]
2151 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
2152 option is intended for use in cases where the sanitizer runtime cannot
2153 be used (for instance, when building libc or a kernel module), or where
2154 the binary size increase caused by the sanitizer runtime is a concern.
2156 This flag is only compatible with :doc:`control flow integrity
2157 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
2158 checks other than ``vptr``.
2160 This flag is enabled by default for sanitizers in the ``cfi`` group.
2162 .. option:: -fsanitize-ignorelist=/path/to/ignorelist/file
2164 Disable or modify sanitizer checks for objects (source files, functions,
2165 variables, types) listed in the file. See
2166 :doc:`SanitizerSpecialCaseList` for file format description.
2168 .. option:: -fno-sanitize-ignorelist
2170 Don't use ignorelist file, if it was specified earlier in the command line.
2172 .. option:: -f[no-]sanitize-coverage=[type,features,...]
2174 Enable simple code coverage in addition to certain sanitizers.
2175 See :doc:`SanitizerCoverage` for more details.
2177 .. option:: -f[no-]sanitize-address-outline-instrumentation
2179 Controls how address sanitizer code is generated. If enabled will always use
2180 a function call instead of inlining the code. Turning this option on could
2181 reduce the binary size, but might result in a worse run-time performance.
2183 See :doc: `AddressSanitizer` for more details.
2185 .. option:: -f[no-]sanitize-stats
2187 Enable simple statistics gathering for the enabled sanitizers.
2188 See :doc:`SanitizerStats` for more details.
2190 .. option:: -fsanitize-undefined-trap-on-error
2192 Deprecated alias for ``-fsanitize-trap=undefined``.
2194 .. option:: -fsanitize-cfi-cross-dso
2196 Enable cross-DSO control flow integrity checks. This flag modifies
2197 the behavior of sanitizers in the ``cfi`` group to allow checking
2198 of cross-DSO virtual and indirect calls.
2200 .. option:: -fsanitize-cfi-icall-generalize-pointers
2202 Generalize pointers in return and argument types in function type signatures
2203 checked by Control Flow Integrity indirect call checking. See
2204 :doc:`ControlFlowIntegrity` for more details.
2206 .. option:: -fsanitize-cfi-icall-experimental-normalize-integers
2208 Normalize integers in return and argument types in function type signatures
2209 checked by Control Flow Integrity indirect call checking. See
2210 :doc:`ControlFlowIntegrity` for more details.
2212 This option is currently experimental.
2214 .. option:: -fstrict-vtable-pointers
2216 Enable optimizations based on the strict rules for overwriting polymorphic
2217 C++ objects, i.e. the vptr is invariant during an object's lifetime.
2218 This enables better devirtualization. Turned off by default, because it is
2221 .. option:: -fwhole-program-vtables
2223 Enable whole-program vtable optimizations, such as single-implementation
2224 devirtualization and virtual constant propagation, for classes with
2225 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
2227 .. option:: -f[no]split-lto-unit
2229 Controls splitting the :doc:`LTO unit <LTOVisibility>` into regular LTO and
2230 :doc:`ThinLTO` portions, when compiling with -flto=thin. Defaults to false
2231 unless ``-fsanitize=cfi`` or ``-fwhole-program-vtables`` are specified, in
2232 which case it defaults to true. Splitting is required with ``fsanitize=cfi``,
2233 and it is an error to disable via ``-fno-split-lto-unit``. Splitting is
2234 optional with ``-fwhole-program-vtables``, however, it enables more
2235 aggressive whole program vtable optimizations (specifically virtual constant
2238 When enabled, vtable definitions and select virtual functions are placed
2239 in the split regular LTO module, enabling more aggressive whole program
2240 vtable optimizations required for CFI and virtual constant propagation.
2241 However, this can increase the LTO link time and memory requirements over
2242 pure ThinLTO, as all split regular LTO modules are merged and LTO linked
2245 .. option:: -fforce-emit-vtables
2247 In order to improve devirtualization, forces emitting of vtables even in
2248 modules where it isn't necessary. It causes more inline virtual functions
2251 .. option:: -fno-assume-sane-operator-new
2253 Don't assume that the C++'s new operator is sane.
2255 This option tells the compiler to do not assume that C++'s global
2256 new operator will always return a pointer that does not alias any
2257 other pointer when the function returns.
2259 .. option:: -fassume-nothrow-exception-dtor
2261 Assume that an exception object' destructor will not throw, and generate
2262 less code for catch handlers. A throw expression of a type with a
2263 potentially-throwing destructor will lead to an error.
2265 By default, Clang assumes that the exception object may have a throwing
2266 destructor. For the Itanium C++ ABI, Clang generates a landing pad to
2267 destroy local variables and call ``_Unwind_Resume`` for the code
2268 ``catch (...) { ... }``. This option tells Clang that an exception object's
2269 destructor will not throw and code simplification is possible.
2271 .. option:: -ftrap-function=[name]
2273 Instruct code generator to emit a function call to the specified
2274 function name for ``__builtin_trap()``.
2276 LLVM code generator translates ``__builtin_trap()`` to a trap
2277 instruction if it is supported by the target ISA. Otherwise, the
2278 builtin is translated into a call to ``abort``. If this option is
2279 set, then the code generator will always lower the builtin to a call
2280 to the specified function regardless of whether the target ISA has a
2281 trap instruction. This option is useful for environments (e.g.
2282 deeply embedded) where a trap cannot be properly handled, or when
2283 some custom behavior is desired.
2285 .. option:: -ftls-model=[model]
2287 Select which TLS model to use.
2289 Valid values are: ``global-dynamic``, ``local-dynamic``,
2290 ``initial-exec`` and ``local-exec``. The default value is
2291 ``global-dynamic``. The compiler may use a different model if the
2292 selected model is not supported by the target, or if a more
2293 efficient model can be used. The TLS model can be overridden per
2294 variable using the ``tls_model`` attribute.
2296 .. option:: -femulated-tls
2298 Select emulated TLS model, which overrides all -ftls-model choices.
2300 In emulated TLS mode, all access to TLS variables are converted to
2301 calls to __emutls_get_address in the runtime library.
2303 .. option:: -mhwdiv=[values]
2305 Select the ARM modes (arm or thumb) that support hardware division
2308 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
2309 This option is used to indicate which mode (arm or thumb) supports
2310 hardware division instructions. This only applies to the ARM
2313 .. option:: -m[no-]crc
2315 Enable or disable CRC instructions.
2317 This option is used to indicate whether CRC instructions are to
2318 be generated. This only applies to the ARM architecture.
2320 CRC instructions are enabled by default on ARMv8.
2322 .. option:: -mgeneral-regs-only
2324 Generate code which only uses the general purpose registers.
2326 This option restricts the generated code to use general registers
2327 only. This only applies to the AArch64 architecture.
2329 .. option:: -mcompact-branches=[values]
2331 Control the usage of compact branches for MIPSR6.
2333 Valid values are: ``never``, ``optimal`` and ``always``.
2334 The default value is ``optimal`` which generates compact branches
2335 when a delay slot cannot be filled. ``never`` disables the usage of
2336 compact branches and ``always`` generates compact branches whenever
2339 .. option:: -f[no-]max-type-align=[number]
2341 Instruct the code generator to not enforce a higher alignment than the given
2342 number (of bytes) when accessing memory via an opaque pointer or reference.
2343 This cap is ignored when directly accessing a variable or when the pointee
2344 type has an explicit “aligned” attribute.
2346 The value should usually be determined by the properties of the system allocator.
2347 Some builtin types, especially vector types, have very high natural alignments;
2348 when working with values of those types, Clang usually wants to use instructions
2349 that take advantage of that alignment. However, many system allocators do
2350 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
2351 this option to limit the alignment that the compiler can assume for an arbitrary
2352 pointer, which may point onto the heap.
2354 This option does not affect the ABI alignment of types; the layout of structs and
2355 unions and the value returned by the alignof operator remain the same.
2357 This option can be overridden on a case-by-case basis by putting an explicit
2358 “aligned” alignment on a struct, union, or typedef. For example:
2360 .. code-block:: console
2362 #include <immintrin.h>
2363 // Make an aligned typedef of the AVX-512 16-int vector type.
2364 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
2366 void initialize_vector(__aligned_v16si *v) {
2367 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
2368 // value of -fmax-type-align.
2371 .. option:: -faddrsig, -fno-addrsig
2373 Controls whether Clang emits an address-significance table into the object
2374 file. Address-significance tables allow linkers to implement `safe ICF
2375 <https://research.google.com/pubs/archive/36912.pdf>`_ without the false
2376 positives that can result from other implementation techniques such as
2377 relocation scanning. Address-significance tables are enabled by default
2378 on ELF targets when using the integrated assembler. This flag currently
2379 only has an effect on ELF targets.
2381 .. _funique_internal_linkage_names:
2383 .. option:: -f[no]-unique-internal-linkage-names
2385 Controls whether Clang emits a unique (best-effort) symbol name for internal
2386 linkage symbols. When this option is set, compiler hashes the main source
2387 file path from the command line and appends it to all internal symbols. If a
2388 program contains multiple objects compiled with the same command-line source
2389 file path, the symbols are not guaranteed to be unique. This option is
2390 particularly useful in attributing profile information to the correct
2391 function when multiple functions with the same private linkage name exist
2394 It should be noted that this option cannot guarantee uniqueness and the
2395 following is an example where it is not unique when two modules contain
2396 symbols with the same private linkage name:
2398 .. code-block:: console
2400 $ cd $P/foo && clang -c -funique-internal-linkage-names name_conflict.c
2401 $ cd $P/bar && clang -c -funique-internal-linkage-names name_conflict.c
2402 $ cd $P && clang foo/name_conflict.o && bar/name_conflict.o
2404 .. option:: -f[no]-basic-block-address-map:
2405 Emits a ``SHT_LLVM_BB_ADDR_MAP`` section which includes address offsets for each
2406 basic block in the program, relative to the parent function address.
2409 .. option:: -fbasic-block-sections=[all, list=<arg>, none]
2411 Controls how Clang emits text sections for basic blocks. With values ``all``
2412 and ``list=<arg>``, each basic block or a subset of basic blocks can be placed
2413 in its own unique section.
2415 With the ``list=<arg>`` option, a file containing the subset of basic blocks
2416 that need to placed in unique sections can be specified. The format of the
2417 file is as follows. For example, ``list=spec.txt`` where ``spec.txt`` is the
2426 will place the machine basic block with ``id 2`` in function ``foo`` in a
2427 unique section. It will also place all basic blocks of functions ``bar``
2430 Further, section clusters can also be specified using the ``list=<arg>``
2431 option. For example, ``list=spec.txt`` where ``spec.txt`` contains:
2439 will create two unique sections for function ``foo`` with the first
2440 containing the odd numbered basic blocks and the second containing the
2441 even numbered basic blocks.
2443 Basic block sections allow the linker to reorder basic blocks and enables
2444 link-time optimizations like whole program inter-procedural basic block
2447 .. option:: -fcodegen-data-generate[=<path>]
2449 Emit the raw codegen (CG) data into custom sections in the object file.
2450 Currently, this option also combines the raw CG data from the object files
2451 into an indexed CG data file specified by the <path>, for LLD MachO only.
2452 When the <path> is not specified, `default.cgdata` is created.
2453 The CG data file combines all the outlining instances that occurred locally
2454 in each object file.
2456 .. code-block:: console
2458 $ clang -fuse-ld=lld -Oz -fcodegen-data-generate code.cc
2460 For linkers that do not yet support this feature, `llvm-cgdata` can be used
2461 manually to merge this CG data in object files.
2463 .. code-block:: console
2465 $ clang -c -fuse-ld=lld -Oz -fcodegen-data-generate code.cc
2466 $ llvm-cgdata --merge -o default.cgdata code.o
2468 .. option:: -fcodegen-data-use[=<path>]
2470 Read the codegen data from the specified path to more effectively outline
2471 functions across compilation units. When the <path> is not specified,
2472 `default.cgdata` is used. This option can create many identically outlined
2473 functions that can be optimized by the conventional linker’s identical code
2476 .. code-block:: console
2478 $ clang -fuse-ld=lld -Oz -Wl,--icf=safe -fcodegen-data-use code.cc
2480 Profile Guided Optimization
2481 ---------------------------
2483 Profile information enables better optimization. For example, knowing that a
2484 branch is taken very frequently helps the compiler make better decisions when
2485 ordering basic blocks. Knowing that a function ``foo`` is called more
2486 frequently than another function ``bar`` helps the inliner. Optimization
2487 levels ``-O2`` and above are recommended for use of profile guided optimization.
2489 Clang supports profile guided optimization with two different kinds of
2490 profiling. A sampling profiler can generate a profile with very low runtime
2491 overhead, or you can build an instrumented version of the code that collects
2492 more detailed profile information. Both kinds of profiles can provide execution
2493 counts for instructions in the code and information on branches taken and
2494 function invocation.
2496 Regardless of which kind of profiling you use, be careful to collect profiles
2497 by running your code with inputs that are representative of the typical
2498 behavior. Code that is not exercised in the profile will be optimized as if it
2499 is unimportant, and the compiler may make poor optimization choices for code
2500 that is disproportionately used while profiling.
2502 Differences Between Sampling and Instrumentation
2503 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2505 Although both techniques are used for similar purposes, there are important
2506 differences between the two:
2508 1. Profile data generated with one cannot be used by the other, and there is no
2509 conversion tool that can convert one to the other. So, a profile generated
2510 via ``-fprofile-generate`` or ``-fprofile-instr-generate`` must be used with
2511 ``-fprofile-use`` or ``-fprofile-instr-use``. Similarly, sampling profiles
2512 generated by external profilers must be converted and used with ``-fprofile-sample-use``
2513 or ``-fauto-profile``.
2515 2. Instrumentation profile data can be used for code coverage analysis and
2518 3. Sampling profiles can only be used for optimization. They cannot be used for
2519 code coverage analysis. Although it would be technically possible to use
2520 sampling profiles for code coverage, sample-based profiles are too
2521 coarse-grained for code coverage purposes; it would yield poor results.
2523 4. Sampling profiles must be generated by an external tool. The profile
2524 generated by that tool must then be converted into a format that can be read
2525 by LLVM. The section on sampling profilers describes one of the supported
2526 sampling profile formats.
2529 Using Sampling Profilers
2530 ^^^^^^^^^^^^^^^^^^^^^^^^
2532 Sampling profilers are used to collect runtime information, such as
2533 hardware counters, while your application executes. They are typically
2534 very efficient and do not incur a large runtime overhead. The
2535 sample data collected by the profiler can be used during compilation
2536 to determine what the most executed areas of the code are.
2538 Using the data from a sample profiler requires some changes in the way
2539 a program is built. Before the compiler can use profiling information,
2540 the code needs to execute under the profiler. The following is the
2541 usual build cycle when using sample profilers for optimization:
2543 1. Build the code with source line table information. You can use all the
2544 usual build flags that you always build your application with. The only
2545 requirement is that DWARF debug info including source line information is
2546 generated. This DWARF information is important for the profiler to be able
2547 to map instructions back to source line locations. The usefulness of this
2548 DWARF information can be improved with the ``-fdebug-info-for-profiling``
2549 and ``-funique-internal-linkage-names`` options.
2553 .. code-block:: console
2555 $ clang++ -O2 -gline-tables-only \
2556 -fdebug-info-for-profiling -funique-internal-linkage-names \
2559 While MSVC-style targets default to CodeView debug information, DWARF debug
2560 information is required to generate source-level LLVM profiles. Use
2561 ``-gdwarf`` to include DWARF debug information:
2563 .. code-block:: winbatch
2565 > clang-cl /O2 -gdwarf -gline-tables-only ^
2566 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2567 code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf
2571 :ref:`-funique-internal-linkage-names <funique_internal_linkage_names>`
2572 generates unique names based on given command-line source file paths. If
2573 your build system uses absolute source paths and these paths may change
2574 between steps 1 and 4, then the uniqued function names may change and result
2575 in unused profile data. Consider omitting this option in such cases.
2577 2. Run the executable under a sampling profiler. The specific profiler
2578 you use does not really matter, as long as its output can be converted
2579 into the format that the LLVM optimizer understands.
2581 Two such profilers are the Linux Perf profiler
2582 (https://perf.wiki.kernel.org/) and Intel's Sampling Enabling Product (SEP),
2583 available as part of `Intel VTune
2584 <https://software.intel.com/content/www/us/en/develop/tools/oneapi/components/vtune-profiler.html>`_.
2585 While Perf is Linux-specific, SEP can be used on Linux, Windows, and FreeBSD.
2587 The LLVM tool ``llvm-profgen`` can convert output of either Perf or SEP. An
2588 external project, `AutoFDO <https://github.com/google/autofdo>`_, also
2589 provides a ``create_llvm_prof`` tool which supports Linux Perf output.
2593 .. code-block:: console
2595 $ perf record -b -e BR_INST_RETIRED.NEAR_TAKEN:uppp ./code
2597 If the event above is unavailable, ``branches:u`` is probably next-best.
2599 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
2600 Record (LBR) to record call chains. While this is not strictly required,
2601 it provides better call information, which improves the accuracy of
2606 .. code-block:: console
2608 $ sep -start -out code.tb7 -ec BR_INST_RETIRED.NEAR_TAKEN:precise=yes:pdir -lbr no_filter:usr -perf-script brstack -app ./code
2610 This produces a ``code.perf.data.script`` output which can be used with
2611 ``llvm-profgen``'s ``--perfscript`` input option.
2613 3. Convert the collected profile data to LLVM's sample profile format. This is
2614 currently supported via the `AutoFDO <https://github.com/google/autofdo>`_
2615 converter ``create_llvm_prof``. Once built and installed, you can convert
2616 the ``perf.data`` file to LLVM using the command:
2618 .. code-block:: console
2620 $ create_llvm_prof --binary=./code --out=code.prof
2622 This will read ``perf.data`` and the binary file ``./code`` and emit
2623 the profile data in ``code.prof``. Note that if you ran ``perf``
2624 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
2625 calling ``create_llvm_prof``.
2627 Alternatively, the LLVM tool ``llvm-profgen`` can also be used to generate
2628 the LLVM sample profile:
2630 .. code-block:: console
2632 $ llvm-profgen --binary=./code --output=code.prof --perfdata=perf.data
2634 When using SEP the output is in the textual format corresponding to
2635 ``llvm-profgen --perfscript``. For example:
2637 .. code-block:: console
2639 $ llvm-profgen --binary=./code --output=code.prof --perfscript=code.perf.data.script
2642 4. Build the code again using the collected profile. This step feeds
2643 the profile back to the optimizers. This should result in a binary
2644 that executes faster than the original one. Note that you are not
2645 required to build the code with the exact same arguments that you
2646 used in the first step. The only requirement is that you build the code
2647 with the same debug info options and ``-fprofile-sample-use``.
2651 .. code-block:: console
2653 $ clang++ -O2 -gline-tables-only \
2654 -fdebug-info-for-profiling -funique-internal-linkage-names \
2655 -fprofile-sample-use=code.prof code.cc -o code
2659 .. code-block:: winbatch
2661 > clang-cl /O2 -gdwarf -gline-tables-only ^
2662 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2663 /fprofile-sample-use=code.prof code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf
2665 [OPTIONAL] Sampling-based profiles can have inaccuracies or missing block/
2666 edge counters. The profile inference algorithm (profi) can be used to infer
2667 missing blocks and edge counts, and improve the quality of profile data.
2668 Enable it with ``-fsample-profile-use-profi``. For example, on Linux:
2670 .. code-block:: console
2672 $ clang++ -fsample-profile-use-profi -O2 -gline-tables-only \
2673 -fdebug-info-for-profiling -funique-internal-linkage-names \
2674 -fprofile-sample-use=code.prof code.cc -o code
2678 .. code-block:: winbatch
2680 > clang-cl /clang:-fsample-profile-use-profi /O2 -gdwarf -gline-tables-only ^
2681 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2682 /fprofile-sample-use=code.prof code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf
2684 Sample Profile Formats
2685 """"""""""""""""""""""
2687 Since external profilers generate profile data in a variety of custom formats,
2688 the data generated by the profiler must be converted into a format that can be
2689 read by the backend. LLVM supports three different sample profile formats:
2691 1. ASCII text. This is the easiest one to generate. The file is divided into
2692 sections, which correspond to each of the functions with profile
2693 information. The format is described below. It can also be generated from
2694 the binary or gcov formats using the ``llvm-profdata`` tool.
2696 2. Binary encoding. This uses a more efficient encoding that yields smaller
2697 profile files. This is the format generated by the ``create_llvm_prof`` tool
2698 in https://github.com/google/autofdo.
2700 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
2701 is only interesting in environments where GCC and Clang co-exist. This
2702 encoding is only generated by the ``create_gcov`` tool in
2703 https://github.com/google/autofdo. It can be read by LLVM and
2704 ``llvm-profdata``, but it cannot be generated by either.
2706 If you are using Linux Perf to generate sampling profiles, you can use the
2707 conversion tool ``create_llvm_prof`` described in the previous section.
2708 Otherwise, you will need to write a conversion tool that converts your
2709 profiler's native format into one of these three.
2712 Sample Profile Text Format
2713 """"""""""""""""""""""""""
2715 This section describes the ASCII text format for sampling profiles. It is,
2716 arguably, the easiest one to generate. If you are interested in generating any
2717 of the other two, consult the ``ProfileData`` library in LLVM's source tree
2718 (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
2720 .. code-block:: console
2722 function1:total_samples:total_head_samples
2723 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
2724 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
2726 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
2727 offsetA[.discriminator]: fnA:num_of_total_samples
2728 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
2729 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
2730 offsetB[.discriminator]: fnB:num_of_total_samples
2731 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
2733 This is a nested tree in which the indentation represents the nesting level
2734 of the inline stack. There are no blank lines in the file. And the spacing
2735 within a single line is fixed. Additional spaces will result in an error
2736 while reading the file.
2738 Any line starting with the '#' character is completely ignored.
2740 Inlined calls are represented with indentation. The Inline stack is a
2741 stack of source locations in which the top of the stack represents the
2742 leaf function, and the bottom of the stack represents the actual
2743 symbol to which the instruction belongs.
2745 Function names must be mangled in order for the profile loader to
2746 match them in the current translation unit. The two numbers in the
2747 function header specify how many total samples were accumulated in the
2748 function (first number), and the total number of samples accumulated
2749 in the prologue of the function (second number). This head sample
2750 count provides an indicator of how frequently the function is invoked.
2752 There are two types of lines in the function body.
2754 - Sampled line represents the profile information of a source location.
2755 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
2757 - Callsite line represents the profile information of an inlined callsite.
2758 ``offsetA[.discriminator]: fnA:num_of_total_samples``
2760 Each sampled line may contain several items. Some are optional (marked
2763 a. Source line offset. This number represents the line number
2764 in the function where the sample was collected. The line number is
2765 always relative to the line where symbol of the function is
2766 defined. So, if the function has its header at line 280, the offset
2767 13 is at line 293 in the file.
2769 Note that this offset should never be a negative number. This could
2770 happen in cases like macros. The debug machinery will register the
2771 line number at the point of macro expansion. So, if the macro was
2772 expanded in a line before the start of the function, the profile
2773 converter should emit a 0 as the offset (this means that the optimizers
2774 will not be able to associate a meaningful weight to the instructions
2777 b. [OPTIONAL] Discriminator. This is used if the sampled program
2778 was compiled with DWARF discriminator support
2779 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
2780 DWARF discriminators are unsigned integer values that allow the
2781 compiler to distinguish between multiple execution paths on the
2782 same source line location.
2784 For example, consider the line of code ``if (cond) foo(); else bar();``.
2785 If the predicate ``cond`` is true 80% of the time, then the edge
2786 into function ``foo`` should be considered to be taken most of the
2787 time. But both calls to ``foo`` and ``bar`` are at the same source
2788 line, so a sample count at that line is not sufficient. The
2789 compiler needs to know which part of that line is taken more
2792 This is what discriminators provide. In this case, the calls to
2793 ``foo`` and ``bar`` will be at the same line, but will have
2794 different discriminator values. This allows the compiler to correctly
2795 set edge weights into ``foo`` and ``bar``.
2797 c. Number of samples. This is an integer quantity representing the
2798 number of samples collected by the profiler at this source
2801 d. [OPTIONAL] Potential call targets and samples. If present, this
2802 line contains a call instruction. This models both direct and
2803 number of samples. For example,
2805 .. code-block:: console
2807 130: 7 foo:3 bar:2 baz:7
2809 The above means that at relative line offset 130 there is a call
2810 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
2811 with ``baz()`` being the relatively more frequently called target.
2813 As an example, consider a program with the call chain ``main -> foo -> bar``.
2814 When built with optimizations enabled, the compiler may inline the
2815 calls to ``bar`` and ``foo`` inside ``main``. The generated profile
2816 could then be something like this:
2818 .. code-block:: console
2826 This profile indicates that there were a total of 35,504 samples
2827 collected in main. All of those were at line 1 (the call to ``foo``).
2828 Of those, 31,977 were spent inside the body of ``bar``. The last line
2829 of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
2830 samples were collected there.
2834 Profiling with Instrumentation
2835 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2837 Clang also supports profiling via instrumentation. This requires building a
2838 special instrumented version of the code and has some runtime
2839 overhead during the profiling, but it provides more detailed results than a
2840 sampling profiler. It also provides reproducible results, at least to the
2841 extent that the code behaves consistently across runs.
2843 Clang supports two types of instrumentation: frontend-based and IR-based.
2844 Frontend-based instrumentation can be enabled with the option ``-fprofile-instr-generate``,
2845 and IR-based instrumentation can be enabled with the option ``-fprofile-generate``.
2846 For best performance with PGO, IR-based instrumentation should be used. It has
2847 the benefits of lower instrumentation overhead, smaller raw profile size, and
2848 better runtime performance. Frontend-based instrumentation, on the other hand,
2849 has better source correlation, so it should be used with source line-based
2852 The flag ``-fcs-profile-generate`` also instruments programs using the same
2853 instrumentation method as ``-fprofile-generate``. However, it performs a
2854 post-inline late instrumentation and can produce context-sensitive profiles.
2857 Here are the steps for using profile guided optimization with
2860 1. Build an instrumented version of the code by compiling and linking with the
2861 ``-fprofile-generate`` or ``-fprofile-instr-generate`` option.
2863 .. code-block:: console
2865 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
2867 2. Run the instrumented executable with inputs that reflect the typical usage.
2868 By default, the profile data will be written to a ``default.profraw`` file
2869 in the current directory. You can override that default by using option
2870 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
2871 environment variable to specify an alternate file. If non-default file name
2872 is specified by both the environment variable and the command line option,
2873 the environment variable takes precedence. The file name pattern specified
2874 can include different modifiers: ``%p``, ``%h``, ``%m``, ``%t``, and ``%c``.
2876 Any instance of ``%p`` in that file name will be replaced by the process
2877 ID, so that you can easily distinguish the profile output from multiple
2880 .. code-block:: console
2882 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
2884 The modifier ``%h`` can be used in scenarios where the same instrumented
2885 binary is run in multiple different host machines dumping profile data
2886 to a shared network based storage. The ``%h`` specifier will be substituted
2887 with the hostname so that profiles collected from different hosts do not
2890 While the use of ``%p`` specifier can reduce the likelihood for the profiles
2891 dumped from different processes to clobber each other, such clobbering can still
2892 happen because of the ``pid`` re-use by the OS. Another side-effect of using
2893 ``%p`` is that the storage requirement for raw profile data files is greatly
2894 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
2895 name. When this specifier is used, the profiler runtime will substitute ``%m``
2896 with a unique integer identifier associated with the instrumented binary. Additionally,
2897 multiple raw profiles dumped from different processes that share a file system (can be
2898 on different hosts) will be automatically merged by the profiler runtime during the
2899 dumping. If the program links in multiple instrumented shared libraries, each library
2900 will dump the profile data into its own profile data file (with its unique integer
2901 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
2902 profile data generated by profiler runtime. The resulting merged "raw" profile data
2903 file still needs to be converted to a different format expected by the compiler (
2906 .. code-block:: console
2908 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
2910 See `this <SourceBasedCodeCoverage.html#running-the-instrumented-program>`_ section
2911 about the ``%t``, and ``%c`` modifiers.
2913 3. Combine profiles from multiple runs and convert the "raw" profile format to
2914 the input expected by clang. Use the ``merge`` command of the
2915 ``llvm-profdata`` tool to do this.
2917 .. code-block:: console
2919 $ llvm-profdata merge -output=code.profdata code-*.profraw
2921 Note that this step is necessary even when there is only one "raw" profile,
2922 since the merge operation also changes the file format.
2924 4. Build the code again using the ``-fprofile-use`` or ``-fprofile-instr-use``
2925 option to specify the collected profile data.
2927 .. code-block:: console
2929 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
2931 You can repeat step 4 as often as you like without regenerating the
2932 profile. As you make changes to your code, clang may no longer be able to
2933 use the profile data. It will warn you when this happens.
2935 Note that ``-fprofile-use`` option is semantically equivalent to
2936 its GCC counterpart, it *does not* handle profile formats produced by GCC.
2937 Both ``-fprofile-use`` and ``-fprofile-instr-use`` accept profiles in the
2938 indexed format, regardeless whether it is produced by frontend or the IR pass.
2940 .. option:: -fprofile-generate[=<dirname>]
2942 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
2943 an alternative instrumentation method for profile generation. When
2944 given a directory name, it generates the profile file
2945 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
2946 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
2947 will be substituted with a unique id documented in step 2 above. In other words,
2948 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
2949 merging is turned on by default, so there will no longer any risk of profile
2950 clobbering from different running processes. For example,
2952 .. code-block:: console
2954 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
2956 When ``code`` is executed, the profile will be written to the file
2957 ``yyy/zzz/default_xxxx.profraw``.
2959 To generate the profile data file with the compiler readable format, the
2960 ``llvm-profdata`` tool can be used with the profile directory as the input:
2962 .. code-block:: console
2964 $ llvm-profdata merge -output=code.profdata yyy/zzz/
2966 If the user wants to turn off the auto-merging feature, or simply override the
2967 the profile dumping path specified at command line, the environment variable
2968 ``LLVM_PROFILE_FILE`` can still be used to override
2969 the directory and filename for the profile file at runtime.
2970 To override the path and filename at compile time, use
2971 ``-Xclang -fprofile-instrument-path=/path/to/file_pattern.profraw``.
2973 .. option:: -fcs-profile-generate[=<dirname>]
2975 The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use
2976 the same instrumentation method, and generate the same profile as in the
2977 ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is
2978 that the instrumentation is performed after inlining so that the resulted
2979 profile has a better context sensitive information. They cannot be used
2980 together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags.
2981 They are typically used in conjunction with ``-fprofile-use`` flag.
2982 The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate``
2983 can be merged by llvm-profdata. A use example:
2985 .. code-block:: console
2987 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
2989 $ llvm-profdata merge -output=code.profdata yyy/zzz/
2991 The first few steps are the same as that in ``-fprofile-generate``
2992 compilation. Then perform a second round of instrumentation.
2994 .. code-block:: console
2996 $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \
2999 $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata
3001 The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile
3002 generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by
3003 ``-fprofile-use`` compilation.
3005 .. code-block:: console
3007 $ clang++ -O2 -fprofile-use=cs_code.profdata
3009 The above command will read both profiles to the compiler at the identical
3010 point of instrumentations.
3012 .. option:: -fprofile-use[=<pathname>]
3014 Without any other arguments, ``-fprofile-use`` behaves identically to
3015 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
3016 profile file, it reads from that file. If ``pathname`` is a directory name,
3017 it reads from ``pathname/default.profdata``.
3019 .. option:: -fprofile-update[=<method>]
3021 Unless ``-fsanitize=thread`` is specified, the default is ``single``, which
3022 uses non-atomic increments. The counters can be inaccurate under thread
3023 contention. ``atomic`` uses atomic increments which is accurate but has
3024 overhead. ``prefer-atomic`` will be transformed to ``atomic`` when supported
3025 by the target, or ``single`` otherwise.
3027 Fine Tuning Profile Collection
3028 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3030 The PGO infrastructure provides user program knobs to fine tune profile
3031 collection. Specifically, the PGO runtime provides the following functions
3032 that can be used to control the regions in the program where profiles should
3035 * ``void __llvm_profile_set_filename(const char *Name)``: changes the name of
3036 the profile file to ``Name``.
3037 * ``void __llvm_profile_reset_counters(void)``: resets all counters to zero.
3038 * ``int __llvm_profile_dump(void)``: write the profile data to disk.
3039 * ``int __llvm_orderfile_dump(void)``: write the order file to disk.
3041 For example, the following pattern can be used to skip profiling program
3042 initialization, profile two specific hot regions, and skip profiling program
3050 // Reset all profile counters to 0 to omit profile collected during
3051 // initialize()'s execution.
3052 __llvm_profile_reset_counters();
3054 // Dump the profile for hot region 1.
3055 __llvm_profile_set_filename("region1.profraw");
3056 __llvm_profile_dump();
3058 // Reset counters before proceeding to hot region 2.
3059 __llvm_profile_reset_counters();
3061 // Dump the profile for hot region 2.
3062 __llvm_profile_set_filename("region2.profraw");
3063 __llvm_profile_dump();
3065 // Since the profile has been dumped, no further profile data
3066 // will be collected beyond the above __llvm_profile_dump().
3071 These APIs' names can be introduced to user programs in two ways.
3072 They can be declared as weak symbols on platforms which support
3073 treating weak symbols as ``null`` during linking. For example, the user can
3078 __attribute__((weak)) int __llvm_profile_dump(void);
3080 // Then later in the same source file
3081 if (__llvm_profile_dump)
3082 if (__llvm_profile_dump() != 0) { ... }
3083 // The first if condition tests if the symbol is actually defined.
3084 // Profile dumping only happens if the symbol is defined. Hence,
3085 // the user program works correctly during normal (not profile-generate)
3088 Alternatively, the user program can include the header
3089 ``profile/instr_prof_interface.h``, which contains the API names. For example,
3093 #include "profile/instr_prof_interface.h"
3095 // Then later in the same source file
3096 if (__llvm_profile_dump() != 0) { ... }
3098 The user code does not need to check if the API names are defined, because
3099 these names are automatically replaced by ``(0)`` or the equivalence of noop
3100 if the ``clang`` is not compiling for profile generation.
3102 Such replacement can happen because ``clang`` adds one of two macros depending
3103 on the ``-fprofile-generate`` and the ``-fprofile-use`` flags.
3105 * ``__LLVM_INSTR_PROFILE_GENERATE``: defined when one of
3106 ``-fprofile[-instr]-generate``/``-fcs-profile-generate`` is in effect.
3107 * ``__LLVM_INSTR_PROFILE_USE``: defined when one of
3108 ``-fprofile-use``/``-fprofile-instr-use`` is in effect.
3110 The two macros can be used to provide more flexibiilty so a user program
3111 can execute code specifically intended for profile generate or profile use.
3112 For example, a user program can have special logging during profile generate:
3116 #if __LLVM_INSTR_PROFILE_GENERATE
3117 expensive_logging_of_full_program_state();
3120 The logging is automatically excluded during a normal build of the program,
3121 hence it does not impact performance during a normal execution.
3123 It is advised to use such fine tuning only in a program's cold regions. The weak
3124 symbols can introduce extra control flow (the ``if`` checks), while the macros
3125 (hence declarations they guard in ``profile/instr_prof_interface.h``)
3126 can change the control flow of the functions that use them between profile
3127 generation and profile use (which can lead to discarded counters in such
3128 functions). Using these APIs in the program's cold regions introduces less
3129 overhead and leads to more optimized code.
3131 Disabling Instrumentation
3132 ^^^^^^^^^^^^^^^^^^^^^^^^^
3134 In certain situations, it may be useful to disable profile generation or use
3135 for specific files in a build, without affecting the main compilation flags
3136 used for the other files in the project.
3138 In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
3139 ``-fno-profile-generate``) to disable profile generation, and
3140 ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
3142 Note that these flags should appear after the corresponding profile
3143 flags to have an effect.
3147 When none of the translation units inside a binary is instrumented, in the
3148 case of Fuchsia the profile runtime will not be linked into the binary and
3149 no profile will be produced, while on other platforms the profile runtime
3150 will be linked and profile will be produced but there will not be any
3153 Instrumenting only selected files or functions
3154 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3156 Sometimes it's useful to only instrument certain files or functions. For
3157 example in automated testing infrastructure, it may be desirable to only
3158 instrument files or functions that were modified by a patch to reduce the
3159 overhead of instrumenting a full system.
3161 This can be done using the ``-fprofile-list`` option.
3163 .. option:: -fprofile-list=<pathname>
3165 This option can be used to apply profile instrumentation only to selected
3166 files or functions. ``pathname`` should point to a file in the
3167 :doc:`SanitizerSpecialCaseList` format which selects which files and
3168 functions to instrument.
3170 .. code-block:: console
3172 $ clang++ -O2 -fprofile-instr-generate -fprofile-list=fun.list code.cc -o code
3174 The option can be specified multiple times to pass multiple files.
3176 .. code-block:: console
3178 $ clang++ -O2 -fprofile-instr-generate -fcoverage-mapping -fprofile-list=fun.list -fprofile-list=code.list code.cc -o code
3180 Supported sections are ``[clang]``, ``[llvm]``, and ``[csllvm]`` representing
3181 clang PGO, IRPGO, and CSIRPGO, respectively. Supported prefixes are ``function``
3182 and ``source``. Supported categories are ``allow``, ``skip``, and ``forbid``.
3183 ``skip`` adds the ``skipprofile`` attribute while ``forbid`` adds the
3184 ``noprofile`` attribute to the appropriate function. Use
3185 ``default:<allow|skip|forbid>`` to specify the default category.
3187 .. code-block:: console
3190 # The following cases are for clang instrumentation.
3193 # We might not want to profile functions that are inlined in many places.
3194 function:inlinedLots=skip
3196 # We want to forbid profiling where it might be dangerous.
3197 source:lib/unsafe/*.cc=forbid
3199 # Otherwise we allow profiling.
3204 An older format is also supported, but it is only able to add the
3205 ``noprofile`` attribute.
3206 To filter individual functions or entire source files use ``fun:<name>`` or
3207 ``src:<file>`` respectively. To exclude a function or a source file, use
3208 ``!fun:<name>`` or ``!src:<file>`` respectively. The format also supports
3209 wildcard expansion. The compiler generated functions are assumed to be located
3210 in the main source file. It is also possible to restrict the filter to a
3211 particular instrumentation type by using a named section.
3213 .. code-block:: none
3215 # all functions whose name starts with foo will be instrumented.
3218 # except for foo1 which will be excluded from instrumentation.
3221 # every function in path/to/foo.cc will be instrumented.
3224 # bar will be instrumented only when using backend instrumentation.
3225 # Recognized section names are clang, llvm and csllvm.
3229 When the file contains only excludes, all files and functions except for the
3230 excluded ones will be instrumented. Otherwise, only the files and functions
3231 specified will be instrumented.
3233 Instrument function groups
3234 ^^^^^^^^^^^^^^^^^^^^^^^^^^
3236 Sometimes it is desirable to minimize the size overhead of instrumented
3237 binaries. One way to do this is to partition functions into groups and only
3238 instrument functions in a specified group. This can be done using the
3239 `-fprofile-function-groups` and `-fprofile-selected-function-group` options.
3241 .. option:: -fprofile-function-groups=<N>, -fprofile-selected-function-group=<i>
3243 The following uses 3 groups
3245 .. code-block:: console
3247 $ clang++ -Oz -fprofile-generate=group_0/ -fprofile-function-groups=3 -fprofile-selected-function-group=0 code.cc -o code.0
3248 $ clang++ -Oz -fprofile-generate=group_1/ -fprofile-function-groups=3 -fprofile-selected-function-group=1 code.cc -o code.1
3249 $ clang++ -Oz -fprofile-generate=group_2/ -fprofile-function-groups=3 -fprofile-selected-function-group=2 code.cc -o code.2
3251 After collecting raw profiles from the three binaries, they can be merged into
3252 a single profile like normal.
3254 .. code-block:: console
3256 $ llvm-profdata merge -output=code.profdata group_*/*.profraw
3262 When the program is compiled after a change that affects many symbol names,
3263 pre-existing profile data may no longer match the program. For example:
3265 * switching from libstdc++ to libc++ will result in the mangled names of all
3266 functions taking standard library types to change
3267 * renaming a widely-used type in C++ will result in the mangled names of all
3268 functions that have parameters involving that type to change
3269 * moving from a 32-bit compilation to a 64-bit compilation may change the
3270 underlying type of ``size_t`` and similar types, resulting in changes to
3273 Clang allows use of a profile remapping file to specify that such differences
3274 in mangled names should be ignored when matching the profile data against the
3277 .. option:: -fprofile-remapping-file=<file>
3279 Specifies a file containing profile remapping information, that will be
3280 used to match mangled names in the profile data to mangled names in the
3283 The profile remapping file is a text file containing lines of the form
3285 .. code-block:: text
3287 fragmentkind fragment1 fragment2
3289 where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``,
3290 indicating whether the following mangled name fragments are
3291 <`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s,
3292 <`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or
3293 <`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s,
3295 Blank lines and lines starting with ``#`` are ignored.
3297 For convenience, built-in <substitution>s such as ``St`` and ``Ss``
3298 are accepted as <name>s (even though they technically are not <name>s).
3300 For example, to specify that ``absl::string_view`` and ``std::string_view``
3301 should be treated as equivalent when matching profile data, the following
3302 remapping file could be used:
3304 .. code-block:: text
3306 # absl::string_view is considered equivalent to std::string_view
3307 type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE
3309 # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++
3311 name 3std St7__cxx11
3313 Matching profile data using a profile remapping file is supported on a
3314 best-effort basis. For example, information regarding indirect call targets is
3315 currently not remapped. For best results, you are encouraged to generate new
3316 profile data matching the updated program, or to remap the profile data
3317 using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools.
3321 Profile data remapping is currently only supported for C++ mangled names
3322 following the Itanium C++ ABI mangling scheme. This covers all C++ targets
3323 supported by Clang other than Windows.
3325 GCOV-based Profiling
3326 --------------------
3328 GCOV is a test coverage program, it helps to know how often a line of code
3329 is executed. When instrumenting the code with ``--coverage`` option, some
3330 counters are added for each edge linking basic blocks.
3332 At compile time, gcno files are generated containing information about
3333 blocks and edges between them. At runtime the counters are incremented and at
3334 exit the counters are dumped in gcda files.
3336 The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate
3337 a report ``.c.gcov``.
3339 .. option:: -fprofile-filter-files=[regexes]
3341 Define a list of regexes separated by a semi-colon.
3342 If a file name matches any of the regexes then the file is instrumented.
3344 .. code-block:: console
3346 $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c
3348 For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files.
3350 .. option:: -fprofile-exclude-files=[regexes]
3352 Define a list of regexes separated by a semi-colon.
3353 If a file name doesn't match all the regexes then the file is instrumented.
3355 .. code-block:: console
3357 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c
3359 For example, this will instrument all the files except the ones in ``/usr/include``.
3361 If both options are used then a file is instrumented if its name matches any
3362 of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes
3363 from ``-fprofile-exclude-list``.
3365 .. code-block:: console
3367 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \
3368 -fprofile-filter-files="^/usr/.*$"
3370 In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and
3371 doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches
3374 Controlling Debug Information
3375 -----------------------------
3377 Controlling Size of Debug Information
3378 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3380 Debug info kind generated by Clang can be set by one of the flags listed
3381 below. If multiple flags are present, the last one is used.
3385 Don't generate any debug info (default).
3387 .. option:: -gline-tables-only
3389 Generate line number tables only.
3391 This kind of debug info allows to obtain stack traces with function names,
3392 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
3393 doesn't contain any other data (e.g. description of local variables or
3394 function parameters).
3396 .. option:: -fstandalone-debug
3398 Clang supports a number of optimizations to reduce the size of debug
3399 information in the binary. They work based on the assumption that
3400 the debug type information can be spread out over multiple
3401 compilation units. Specifically, the optimizations are:
3403 - will not emit type definitions for types that are not needed by a
3404 module and could be replaced with a forward declaration.
3405 - will only emit type info for a dynamic C++ class in the module that
3406 contains the vtable for the class.
3407 - will only emit type info for a C++ class (non-trivial, non-aggregate)
3408 in the modules that contain a definition for one of its constructors.
3409 - will only emit type definitions for types that are the subject of explicit
3410 template instantiation declarations in the presence of an explicit
3411 instantiation definition for the type.
3413 The **-fstandalone-debug** option turns off these optimizations.
3414 This is useful when working with 3rd-party libraries that don't come
3415 with debug information. Note that Clang will never emit type
3416 information for types that are not referenced at all by the program.
3418 .. option:: -fno-standalone-debug
3420 On Darwin **-fstandalone-debug** is enabled by default. The
3421 **-fno-standalone-debug** option can be used to get to turn on the
3422 vtable-based optimization described above.
3426 Generate complete debug info.
3428 .. option:: -feliminate-unused-debug-types
3430 By default, Clang does not emit type information for types that are defined
3431 but not used in a program. To retain the debug info for these unused types,
3432 the negation **-fno-eliminate-unused-debug-types** can be used.
3433 This can be particulary useful on Windows, when using NATVIS files that
3434 can reference const symbols that would otherwise be stripped, even in full
3435 debug or standalone debug modes.
3437 Controlling Macro Debug Info Generation
3438 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3440 Debug info for C preprocessor macros increases the size of debug information in
3441 the binary. Macro debug info generated by Clang can be controlled by the flags
3444 .. option:: -fdebug-macro
3446 Generate debug info for preprocessor macros. This flag is discarded when
3449 .. option:: -fno-debug-macro
3451 Do not generate debug info for preprocessor macros (default).
3453 Controlling Debugger "Tuning"
3454 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3456 While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
3457 different debuggers may know how to take advantage of different specific DWARF
3458 features. You can "tune" the debug info for one of several different debuggers.
3460 .. option:: -ggdb, -glldb, -gsce, -gdbx
3462 Tune the debug info for the ``gdb``, ``lldb``, Sony PlayStation\ |reg|
3463 debugger, or ``dbx``, respectively. Each of these options implies **-g**.
3464 (Therefore, if you want both **-gline-tables-only** and debugger tuning, the
3465 tuning option must come first.)
3467 Controlling LLVM IR Output
3468 --------------------------
3470 Controlling Value Names in LLVM IR
3471 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3473 Emitting value names in LLVM IR increases the size and verbosity of the IR.
3474 By default, value names are only emitted in assertion-enabled builds of Clang.
3475 However, when reading IR it can be useful to re-enable the emission of value
3476 names to improve readability.
3478 .. option:: -fdiscard-value-names
3480 Discard value names when generating LLVM IR.
3482 .. option:: -fno-discard-value-names
3484 Do not discard value names when generating LLVM IR. This option can be used
3485 to re-enable names for release builds of Clang.
3488 Comment Parsing Options
3489 -----------------------
3491 Clang parses Doxygen and non-Doxygen style documentation comments and attaches
3492 them to the appropriate declaration nodes. By default, it only parses
3493 Doxygen-style comments and ignores ordinary comments starting with ``//`` and
3496 .. option:: -Wdocumentation
3498 Emit warnings about use of documentation comments. This warning group is off
3501 This includes checking that ``\param`` commands name parameters that actually
3502 present in the function signature, checking that ``\returns`` is used only on
3503 functions that actually return a value etc.
3505 .. option:: -Wno-documentation-unknown-command
3507 Don't warn when encountering an unknown Doxygen command.
3509 .. option:: -fparse-all-comments
3511 Parse all comments as documentation comments (including ordinary comments
3512 starting with ``//`` and ``/*``).
3514 .. option:: -fcomment-block-commands=[commands]
3516 Define custom documentation commands as block commands. This allows Clang to
3517 construct the correct AST for these custom commands, and silences warnings
3518 about unknown commands. Several commands must be separated by a comma
3519 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
3520 custom commands ``\foo`` and ``\bar``.
3522 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
3523 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
3531 The support for standard C in clang is feature-complete except for the
3532 C99 floating-point pragmas.
3534 Extensions supported by clang
3535 -----------------------------
3537 See :doc:`LanguageExtensions`.
3539 Differences between various standard modes
3540 ------------------------------------------
3542 clang supports the -std option, which changes what language mode clang uses.
3543 The supported modes for C are c89, gnu89, c94, c99, gnu99, c11, gnu11, c17,
3544 gnu17, c23, gnu23, c2y, gnu2y, and various aliases for those modes. If no -std
3545 option is specified, clang defaults to gnu17 mode. Many C99 and C11 features
3546 are supported in earlier modes as a conforming extension, with a warning. Use
3547 ``-pedantic-errors`` to request an error if a feature from a later standard
3548 revision is used in an earlier mode.
3550 Differences between all ``c*`` and ``gnu*`` modes:
3552 - ``c*`` modes define "``__STRICT_ANSI__``".
3553 - Target-specific defines not prefixed by underscores, like ``linux``,
3554 are defined in ``gnu*`` modes.
3555 - Trigraphs default to being off in ``gnu*`` modes; they can be enabled
3556 by the ``-trigraphs`` option.
3557 - The parser recognizes ``asm`` and ``typeof`` as keywords in ``gnu*`` modes;
3558 the variants ``__asm__`` and ``__typeof__`` are recognized in all modes.
3559 - The parser recognizes ``inline`` as a keyword in ``gnu*`` mode, in
3560 addition to recognizing it in the ``*99`` and later modes for which it is
3561 part of the ISO C standard. The variant ``__inline__`` is recognized in all
3563 - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
3564 on some platforms; it can be enabled in any mode with the ``-fblocks``
3567 Differences between ``*89`` and ``*94`` modes:
3569 - Digraphs are not recognized in c89 mode.
3571 Differences between ``*94`` and ``*99`` modes:
3573 - The ``*99`` modes default to implementing ``inline`` / ``__inline__``
3574 as specified in C99, while the ``*89`` modes implement the GNU version.
3575 This can be overridden for individual functions with the ``__gnu_inline__``
3577 - The scope of names defined inside a ``for``, ``if``, ``switch``, ``while``,
3578 or ``do`` statement is different. (example: ``if ((struct x {int x;}*)0) {}``.)
3579 - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
3580 - ``inline`` is not recognized as a keyword in ``c89`` mode.
3581 - ``restrict`` is not recognized as a keyword in ``*89`` modes.
3582 - Commas are allowed in integer constant expressions in ``*99`` modes.
3583 - Arrays which are not lvalues are not implicitly promoted to pointers
3585 - Some warnings are different.
3587 Differences between ``*99`` and ``*11`` modes:
3589 - Warnings for use of C11 features are disabled.
3590 - ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
3592 Differences between ``*11`` and ``*17`` modes:
3594 - ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.
3596 Differences between ``*17`` and ``*23`` modes:
3598 - ``__STDC_VERSION__`` is defined to ``202311L`` rather than ``201710L``.
3599 - ``nullptr`` and ``nullptr_t`` are supported, only in ``*23`` mode.
3600 - ``ATOMIC_VAR_INIT`` is removed from ``*23`` mode.
3601 - ``bool``, ``true``, ``false``, ``alignas``, ``alignof``, ``static_assert``,
3602 and ``thread_local`` are now first-class keywords, only in ``*23`` mode.
3603 - ``typeof`` and ``typeof_unqual`` are supported, only ``*23`` mode.
3604 - Bit-precise integers (``_BitInt(N)``) are supported by default in ``*23``
3605 mode, and as an extension in ``*17`` and earlier modes.
3606 - ``[[]]`` attributes are supported by default in ``*23`` mode, and as an
3607 extension in ``*17`` and earlier modes.
3609 Differences between ``*23`` and ``*2y`` modes:
3611 - ``__STDC_VERSION__`` is defined to ``202400L`` rather than ``202311L``.
3613 GCC extensions not implemented yet
3614 ----------------------------------
3616 clang tries to be compatible with gcc as much as possible, but some gcc
3617 extensions are not implemented yet:
3619 - clang does not support decimal floating point types (``_Decimal32`` and
3621 - clang does not support nested functions; this is a complex feature
3622 which is infrequently used, so it is unlikely to be implemented
3623 anytime soon. In C++11 it can be emulated by assigning lambda
3624 functions to local variables, e.g:
3628 auto const local_function = [&](int parameter) {
3634 - clang only supports global register variables when the register specified
3635 is non-allocatable (e.g. the stack pointer). Support for general global
3636 register variables is unlikely to be implemented soon because it requires
3637 additional LLVM backend support.
3638 - clang does not support static initialization of flexible array
3639 members. This appears to be a rarely used extension, but could be
3640 implemented pending user demand.
3641 - clang does not support
3642 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
3643 used rarely, but in some potentially interesting places, like the
3644 glibc headers, so it may be implemented pending user demand. Note
3645 that because clang pretends to be like GCC 4.2, and this extension
3646 was introduced in 4.3, the glibc headers will not try to use this
3647 extension with clang at the moment.
3648 - clang does not support the gcc extension for forward-declaring
3649 function parameters; this has not shown up in any real-world code
3650 yet, though, so it might never be implemented.
3652 This is not a complete list; if you find an unsupported extension
3653 missing from this list, please send an e-mail to cfe-dev. This list
3654 currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
3655 list does not include bugs in mostly-implemented features; please see
3657 tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
3658 for known existing bugs (FIXME: Is there a section for bug-reporting
3659 guidelines somewhere?).
3661 Intentionally unsupported GCC extensions
3662 ----------------------------------------
3664 - clang does not support the gcc extension that allows variable-length
3665 arrays in structures. This is for a few reasons: one, it is tricky to
3666 implement, two, the extension is completely undocumented, and three,
3667 the extension appears to be rarely used. Note that clang *does*
3668 support flexible array members (arrays with a zero or unspecified
3669 size at the end of a structure).
3670 - GCC accepts many expression forms that are not valid integer constant
3671 expressions in bit-field widths, enumerator constants, case labels,
3672 and in array bounds at global scope. Clang also accepts additional
3673 expression forms in these contexts, but constructs that GCC accepts due to
3674 simplifications GCC performs while parsing, such as ``x - x`` (where ``x`` is a
3675 variable) will likely never be accepted by Clang.
3676 - clang does not support ``__builtin_apply`` and friends; this extension
3677 is extremely obscure and difficult to implement reliably.
3681 Microsoft extensions
3682 --------------------
3684 clang has support for many extensions from Microsoft Visual C++. To enable these
3685 extensions, use the ``-fms-extensions`` command-line option. This is the default
3686 for Windows targets. Clang does not implement every pragma or declspec provided
3687 by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
3688 comment(lib)`` are well supported.
3690 clang has a ``-fms-compatibility`` flag that makes clang accept enough
3691 invalid C++ to be able to parse most Microsoft headers. For example, it
3692 allows `unqualified lookup of dependent base class members
3693 <https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
3694 a common compatibility issue with clang. This flag is enabled by default
3695 for Windows targets.
3697 ``-fdelayed-template-parsing`` lets clang delay parsing of function template
3698 definitions until the end of a translation unit. This flag is enabled by
3699 default for Windows targets.
3701 For compatibility with existing code that compiles with MSVC, clang defines the
3702 ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. When on Windows, these default to
3703 either the same value as the currently installed version of cl.exe, or ``1933``
3704 and ``193300000`` (respectively). The ``-fms-compatibility-version=`` flag
3705 overrides these values. It accepts a dotted version tuple, such as 19.00.23506.
3706 Changing the MSVC compatibility version makes clang behave more like that
3707 version of MSVC. For example, ``-fms-compatibility-version=19`` will enable
3708 C++14 features and define ``char16_t`` and ``char32_t`` as builtin types.
3712 C++ Language Features
3713 =====================
3715 clang fully implements all of standard C++98 except for exported
3716 templates (which were removed in C++11), all of standard C++11,
3717 C++14, and C++17, and most of C++20.
3719 See the `C++ support in Clang <https://clang.llvm.org/cxx_status.html>`_ page
3720 for detailed information on C++ feature support across Clang versions.
3722 Controlling implementation limits
3723 ---------------------------------
3725 .. option:: -fbracket-depth=N
3727 Sets the limit for nested parentheses, brackets, and braces to N. The
3730 .. option:: -fconstexpr-depth=N
3732 Sets the limit for constexpr function invocations to N. The default is 512.
3734 .. option:: -fconstexpr-steps=N
3736 Sets the limit for the number of full-expressions evaluated in a single
3737 constant expression evaluation. This also controls the maximum size
3738 of array and dynamic array allocation that can be constant evaluated.
3739 The default is 1048576.
3741 .. option:: -ftemplate-depth=N
3743 Sets the limit for recursively nested template instantiations to N. The
3746 .. option:: -foperator-arrow-depth=N
3748 Sets the limit for iterative calls to 'operator->' functions to N. The
3753 Objective-C Language Features
3754 =============================
3758 Objective-C++ Language Features
3759 ===============================
3766 Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport`
3767 for additional details.
3769 Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
3772 Use `-fopenmp-simd` to enable OpenMP simd features only, without linking
3773 the runtime library; for combined constructs
3774 (e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses
3775 will be ignored. This can be disabled with `-fno-openmp-simd`.
3777 Controlling implementation limits
3778 ---------------------------------
3780 .. option:: -fopenmp-use-tls
3782 Controls code generation for OpenMP threadprivate variables. In presence of
3783 this option all threadprivate variables are generated the same way as thread
3784 local variables, using TLS support. If `-fno-openmp-use-tls`
3785 is provided or target does not support TLS, code generation for threadprivate
3786 variables relies on OpenMP runtime library.
3793 Clang can be used to compile OpenCL kernels for execution on a device
3794 (e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMDGPU)
3795 that can be uploaded to run directly on a device (e.g. using
3796 `clCreateProgramWithBinary
3797 <https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
3798 into generic bitcode files loadable into other toolchains.
3800 Compiling to a binary using the default target from the installation can be done
3803 .. code-block:: console
3805 $ echo "kernel void k(){}" > test.cl
3808 Compiling for a specific target can be done by specifying the triple corresponding
3809 to the target, for example:
3811 .. code-block:: console
3813 $ clang --target=nvptx64-unknown-unknown test.cl
3814 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
3816 Compiling to bitcode can be done as follows:
3818 .. code-block:: console
3820 $ clang -c -emit-llvm test.cl
3822 This will produce a file `test.bc` that can be used in vendor toolchains
3823 to perform machine code generation.
3825 Note that if compiled to bitcode for generic targets such as SPIR/SPIR-V,
3826 portable IR is produced that can be used with various vendor
3827 tools as well as open source tools such as `SPIRV-LLVM Translator
3828 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_
3829 to produce SPIR-V binary. More details are provided in `the offline
3830 compilation from OpenCL kernel sources into SPIR-V using open source
3832 <https://github.com/KhronosGroup/OpenCL-Guide/blob/main/chapters/os_tooling.md>`_.
3833 From clang 14 onwards SPIR-V can be generated directly as detailed in
3834 :ref:`the SPIR-V support section <spir-v>`.
3836 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
3837 supports full profile. There is only very limited support of the embedded
3839 From clang 9 a C++ mode is available for OpenCL (see
3840 :ref:`C++ for OpenCL <cxx_for_opencl>`).
3842 OpenCL v3.0 support is complete but it remains in experimental state, see more
3843 details about the experimental features and limitations in :doc:`OpenCLSupport`
3846 OpenCL Specific Options
3847 -----------------------
3849 Most of the OpenCL build options from `the specification v2.0 section 5.8.4
3850 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
3854 .. code-block:: console
3856 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
3859 Many flags used for the compilation for C sources can also be passed while
3860 compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
3862 Some extra options are available to support special OpenCL features.
3864 .. option:: -cl-no-stdinc
3866 Allows to disable all extra types and functions that are not native to the compiler.
3867 This might reduce the compilation speed marginally but many declarations from the
3868 OpenCL standard will not be accessible. For example, the following will fail to
3871 .. code-block:: console
3873 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
3874 $ clang -cl-std=CL2.0 -cl-no-stdinc test.cl
3875 error: use of undeclared identifier 'get_enqueued_local_size'
3876 error: use of undeclared identifier 'get_local_size'
3878 More information about the standard types and functions is provided in :ref:`the
3879 section on the OpenCL Header <opencl_header>`.
3885 Enables/Disables support of OpenCL extensions and optional features. All OpenCL
3886 targets set a list of extensions that they support. Clang allows to amend this using
3887 the ``-cl-ext`` flag with a comma-separated list of extensions prefixed with
3888 ``'+'`` or ``'-'``. The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where
3889 extensions can be either one of `the OpenCL published extensions
3890 <https://www.khronos.org/registry/OpenCL>`_
3891 or any vendor extension. Alternatively, ``'all'`` can be used to enable
3892 or disable all known extensions.
3894 Example disabling double support for the 64-bit SPIR-V target:
3896 .. code-block:: console
3898 $ clang -c --target=spirv64 -cl-ext=-cl_khr_fp64 test.cl
3900 Enabling all extensions except double support in R600 AMD GPU can be done using:
3902 .. code-block:: console
3904 $ clang --target=r600 -cl-ext=-all,+cl_khr_fp16 test.cl
3906 Note that some generic targets e.g. SPIR/SPIR-V enable all extensions/features in
3912 OpenCL targets are derived from the regular Clang target classes. The OpenCL
3913 specific parts of the target representation provide address space mapping as
3914 well as a set of supported extensions.
3919 There is a set of concrete HW architectures that OpenCL can be compiled for.
3923 .. code-block:: console
3925 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
3927 - For Nvidia architectures:
3929 .. code-block:: console
3931 $ clang --target=nvptx64-unknown-unknown test.cl
3937 - A SPIR-V binary can be produced for 32 or 64 bit targets.
3939 .. code-block:: console
3941 $ clang --target=spirv32 -c test.cl
3942 $ clang --target=spirv64 -c test.cl
3944 More details can be found in :ref:`the SPIR-V support section <spir-v>`.
3946 - SPIR is available as a generic target to allow portable bitcode to be produced
3947 that can be used across GPU toolchains. The implementation follows `the SPIR
3948 specification <https://www.khronos.org/spir>`_. There are two flavors
3949 available for 32 and 64 bits.
3951 .. code-block:: console
3953 $ clang --target=spir test.cl -emit-llvm -c
3954 $ clang --target=spir64 test.cl -emit-llvm -c
3956 Clang will generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and
3957 SPIR v2.0 for OpenCL v2.0 or C++ for OpenCL.
3959 - x86 is used by some implementations that are x86 compatible and currently
3960 remains for backwards compatibility (with older implementations prior to
3961 SPIR target support). For "non-SPMD" targets which cannot spawn multiple
3962 work-items on the fly using hardware, which covers practically all non-GPU
3963 devices such as CPUs and DSPs, additional processing is needed for the kernels
3964 to support multiple work-item execution. For this, a 3rd party toolchain,
3965 such as for example `POCL <http://portablecl.org/>`_, can be used.
3967 This target does not support multiple memory segments and, therefore, the fake
3968 address space map can be added using the :ref:`-ffake-address-space-map
3969 <opencl_fake_address_space_map>` flag.
3971 All known OpenCL extensions and features are set to supported in the generic targets,
3972 however :option:`-cl-ext` flag can be used to toggle individual extensions and
3980 By default Clang will include standard headers and therefore most of OpenCL
3981 builtin functions and types are available during compilation. The
3982 default declarations of non-native compiler types and functions can be disabled
3983 by using flag :option:`-cl-no-stdinc`.
3985 The following example demonstrates that OpenCL kernel sources with various
3986 standard builtin functions can be compiled without the need for an explicit
3987 includes or compiler flags.
3989 .. code-block:: console
3991 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
3992 $ clang -cl-std=CL2.0 test.cl
3994 More information about the default headers is provided in :doc:`OpenCLSupport`.
3999 Most of the ``cl_khr_*`` extensions to OpenCL C from `the official OpenCL
4000 registry <https://www.khronos.org/registry/OpenCL/>`_ are available and
4001 configured per target depending on the support available in the specific
4004 It is possible to alter the default extensions setting per target using
4005 ``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
4007 Vendor extensions can be added flexibly by declaring the list of types and
4008 functions associated with each extensions enclosed within the following
4009 compiler pragma directives:
4013 #pragma OPENCL EXTENSION the_new_extension_name : begin
4014 // declare types and functions associated with the extension here
4015 #pragma OPENCL EXTENSION the_new_extension_name : end
4017 For example, parsing the following code adds ``my_t`` type and ``my_func``
4018 function to the custom ``my_ext`` extension.
4022 #pragma OPENCL EXTENSION my_ext : begin
4027 #pragma OPENCL EXTENSION my_ext : end
4029 There is no conflict resolution for identifier clashes among extensions.
4030 It is therefore recommended that the identifiers are prefixed with a
4031 double underscore to avoid clashing with user space identifiers. Vendor
4032 extension should use reserved identifier prefix e.g. amd, arm, intel.
4034 Clang also supports language extensions documented in `The OpenCL C Language
4035 Extensions Documentation
4036 <https://github.com/KhronosGroup/Khronosdotorg/blob/main/api/opencl/assets/OpenCL_LangExt.pdf>`_.
4038 OpenCL-Specific Attributes
4039 --------------------------
4041 OpenCL support in Clang contains a set of attribute taken directly from the
4042 specification as well as additional attributes.
4044 See also :doc:`AttributeReference`.
4049 Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
4050 does not have any effect on the IR. For more details reffer to the specification
4052 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
4058 The implementation of this feature mirrors the unroll hint for C.
4059 More details on the syntax can be found in the specification
4061 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
4066 To make sure no invalid optimizations occur for single program multiple data
4067 (SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
4068 can be used for special functions that have cross work item semantics.
4069 An example is the subgroup operations such as `intel_sub_group_shuffle
4070 <https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
4074 // Define custom my_sub_group_shuffle(data, c)
4075 // that makes use of intel_sub_group_shuffle
4077 if (r0) r1 = computeA();
4078 // Shuffle data from r1 into r3
4079 // of threads id r2.
4080 r3 = my_sub_group_shuffle(r1, r2);
4081 if (r0) r3 = computeB();
4083 with non-SPMD semantics this is optimized to the following equivalent code:
4089 // Incorrect functionality! The data in r1
4090 // have not been computed by all threads yet.
4091 r3 = my_sub_group_shuffle(r1, r2);
4094 r3 = my_sub_group_shuffle(r1, r2);
4098 Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
4103 my_sub_group_shuffle() __attribute__((convergent));
4105 Using ``convergent`` guarantees correct execution by keeping CFG equivalence
4106 wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
4107 node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
4108 respect to ``Ni`` remain the same in both ``G`` and ``G´``.
4113 ``noduplicate`` is more restrictive with respect to optimizations than
4114 ``convergent`` because a convergent function only preserves CFG equivalence.
4115 This allows some optimizations to happen as long as the control flow remains
4120 for (int i=0; i<4; i++)
4121 my_sub_group_shuffle()
4127 my_sub_group_shuffle();
4128 my_sub_group_shuffle();
4129 my_sub_group_shuffle();
4130 my_sub_group_shuffle();
4132 while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
4133 have the same safe semantics of CFG as ``convergent`` and can cause changes in
4134 CFG that modify semantics of the original program.
4136 ``noduplicate`` is kept for backwards compatibility only and it considered to be
4137 deprecated for future uses.
4144 Starting from clang 9 kernel code can contain C++17 features: classes, templates,
4145 function overloading, type deduction, etc. Please note that this is not an
4146 implementation of `OpenCL C++
4147 <https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and
4148 there is no plan to support it in clang in any new releases in the near future.
4150 Clang currently supports C++ for OpenCL 1.0 and 2021.
4151 For detailed information about this language refer to the C++ for OpenCL
4152 Programming Language Documentation available
4153 in `the latest build
4154 <https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html>`_
4155 or in `the official release
4156 <https://github.com/KhronosGroup/OpenCL-Docs/releases/tag/cxxforopencl-docrev2021.12>`_.
4158 To enable the C++ for OpenCL mode, pass one of following command line options when
4159 compiling ``.clcpp`` file:
4161 - C++ for OpenCL 1.0: ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-cl-std=clc++1.0``,
4162 ``-cl-std=CLC++1.0``, ``-std=clc++``, ``-std=CLC++``, ``-std=clc++1.0`` or
4165 - C++ for OpenCL 2021: ``-cl-std=clc++2021``, ``-cl-std=CLC++2021``,
4166 ``-std=clc++2021``, ``-std=CLC++2021``.
4171 template<class T> T add( T x, T y )
4176 __kernel void test( __global float* a, __global float* b)
4178 auto index = get_global_id(0);
4179 a[index] = add(b[index], b[index+1]);
4183 .. code-block:: console
4185 clang -cl-std=clc++1.0 test.clcpp
4186 clang -cl-std=clc++ -c --target=spirv64 test.cl
4189 By default, files with ``.clcpp`` extension are compiled with the C++ for
4192 .. code-block:: console
4196 For backward compatibility files with ``.cl`` extensions can also be compiled
4197 in C++ for OpenCL mode but the desirable language mode must be activated with
4200 .. code-block:: console
4202 clang -cl-std=clc++ test.cl
4204 Support of C++ for OpenCL 2021 is currently in experimental phase, refer to
4205 :doc:`OpenCLSupport` for more details.
4207 C++ for OpenCL kernel sources can also be compiled online in drivers supporting
4208 `cl_ext_cxx_for_opencl
4209 <https://www.khronos.org/registry/OpenCL/extensions/ext/cl_ext_cxx_for_opencl.html>`_
4212 Constructing and destroying global objects
4213 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4215 Global objects with non-trivial constructors require the constructors to be run
4216 before the first kernel using the global objects is executed. Similarly global
4217 objects with non-trivial destructors require destructor invocation just after
4218 the last kernel using the program objects is executed.
4219 In OpenCL versions earlier than v2.2 there is no support for invoking global
4220 constructors. However, an easy workaround is to manually enqueue the
4221 constructor initialization kernel that has the following name scheme
4222 ``_GLOBAL__sub_I_<compiled file name>``.
4223 This kernel is only present if there are global objects with non-trivial
4224 constructors present in the compiled binary. One way to check this is by
4225 passing ``CL_PROGRAM_KERNEL_NAMES`` to ``clGetProgramInfo`` (OpenCL v2.0
4226 s5.8.7) and then checking whether any kernel name matches the naming scheme of
4227 global constructor initialization kernel above.
4229 Note that if multiple files are compiled and linked into libraries, multiple
4230 kernels that initialize global objects for multiple modules would have to be
4233 Applications are currently required to run initialization of global objects
4234 manually before running any kernels in which the objects are used.
4236 .. code-block:: console
4238 clang -cl-std=clc++ test.cl
4240 If there are any global objects to be initialized, the final binary will
4241 contain the ``_GLOBAL__sub_I_test.cl`` kernel to be enqueued.
4243 Note that the manual workaround only applies to objects declared at the
4244 program scope. There is no manual workaround for the construction of static
4245 objects with non-trivial constructors inside functions.
4247 Global destructors can not be invoked manually in the OpenCL v2.0 drivers.
4248 However, all memory used for program scope objects should be released on
4249 ``clReleaseProgram``.
4253 Limited experimental support of C++ standard libraries for OpenCL is
4254 described in :doc:`OpenCLSupport` page.
4256 .. _target_features:
4258 Target-Specific Features and Limitations
4259 ========================================
4261 CPU Architectures Features and Limitations
4262 ------------------------------------------
4267 The support for X86 (both 32-bit and 64-bit) is considered stable on
4268 Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested
4269 to correctly compile many large C, C++, Objective-C, and Objective-C++
4272 On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
4273 Microsoft x64 calling convention. You might need to tweak
4274 ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/Targets/X86.cpp.
4276 For the X86 target, clang supports the `-m16` command line
4277 argument which enables 16-bit code output. This is broadly similar to
4278 using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
4279 and the ABI remains 32-bit but the assembler emits instructions
4280 appropriate for a CPU running in 16-bit mode, with address-size and
4281 operand-size prefixes to enable 32-bit addressing and operations.
4283 Several micro-architecture levels as specified by the x86-64 psABI are defined.
4284 They are cumulative in the sense that features from previous levels are
4285 implicitly included in later levels.
4287 - ``-march=x86-64``: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
4288 - ``-march=x86-64-v2``: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
4289 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
4290 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
4292 `Intel AVX10 ISA <https://cdrdv2.intel.com/v1/dl/getContent/784267>`_ is
4293 a major new vector ISA incorporating the modern vectorization aspects of
4294 Intel AVX-512. This ISA will be supported on all future Intel processors.
4295 Users are supposed to use the new options ``-mavx10.N`` and ``-mavx10.N-512``
4296 on these processors and should not use traditional AVX512 options anymore.
4298 The ``N`` in ``-mavx10.N`` represents a continuous integer number starting
4299 from ``1``. ``-mavx10.N`` is an alias of ``-mavx10.N-256``, which means to
4300 enable all instructions within AVX10 version N at a maximum vector length of
4301 256 bits. ``-mavx10.N-512`` enables all instructions at a maximum vector
4302 length of 512 bits, which is a superset of instructions ``-mavx10.N`` enabled.
4304 Current binaries built with AVX512 features can run on Intel AVX10/512 capable
4305 processors without re-compile, but cannot run on AVX10/256 capable processors.
4306 Users need to re-compile their code with ``-mavx10.N``, and maybe update some
4307 code that calling to 512-bit X86 specific intrinsics and passing or returning
4308 512-bit vector types in function call, if they want to run on AVX10/256 capable
4309 processors. Binaries built with ``-mavx10.N`` can run on both AVX10/256 and
4310 AVX10/512 capable processors.
4312 Users can add a ``-mno-evex512`` in the command line with AVX512 options if
4313 they want to run the binary on both legacy AVX512 and new AVX10/256 capable
4314 processors. The option has the same constraints as ``-mavx10.N``, i.e.,
4315 cannot call to 512-bit X86 specific intrinsics and pass or return 512-bit vector
4316 types in function call.
4318 Users should avoid using AVX512 features in function target attributes when
4319 developing code for AVX10. If they have to do so, they need to add an explicit
4320 ``evex512`` or ``no-evex512`` together with AVX512 features for 512-bit or
4321 non-512-bit functions respectively to avoid unexpected code generation. Both
4322 command line option and target attribute of EVEX512 feature can only be used
4323 with AVX512. They don't affect vector size of AVX10.
4325 User should not mix the use AVX10 and AVX512 options together at any time,
4326 because the option combinations are conflicting sometimes. For example, a
4327 combination of ``-mavx512f -mavx10.1-256`` doesn't show a clear intention to
4328 compiler, since instructions in AVX512F and AVX10.1/256 intersect but do not
4329 overlap. In this case, compiler will emit warning for it, but the behavior
4330 is determined. It will generate the same code as option ``-mavx10.1-512``.
4331 A similar case is ``-mavx512f -mavx10.2-256``, which equals to
4332 ``-mavx10.1-512 -mavx10.2-256``, because ``avx10.2-256`` implies ``avx10.1-256``
4333 and ``-mavx512f -mavx10.1-256`` equals to ``-mavx10.1-512``.
4335 There are some new macros introduced with AVX10 support. ``-mavx10.1-256`` will
4336 enable ``__AVX10_1__`` and ``__EVEX256__``, while ``-mavx10.1-512`` enables
4337 ``__AVX10_1__``, ``__EVEX256__``, ``__EVEX512__`` and ``__AVX10_1_512__``.
4338 Besides, both ``-mavx10.1-256`` and ``-mavx10.1-512`` will enable all AVX512
4339 feature specific macros. A AVX512 feature will enable both ``__EVEX256__``,
4340 ``__EVEX512__`` and its own macro. So ``__EVEX512__`` can be used to guard code
4341 that can run on both legacy AVX512 and AVX10/512 capable processors but cannot
4342 run on AVX10/256, while a AVX512 macro like ``__AVX512F__`` cannot tell the
4343 difference among the three options. Users need to check additional macros
4344 ``__AVX10_1__`` and ``__EVEX512__`` if they want to make distinction.
4349 The support for ARM (specifically ARMv6 and ARMv7) is considered stable
4350 on Darwin (iOS): it has been tested to correctly compile many large C,
4351 C++, Objective-C, and Objective-C++ codebases. Clang only supports a
4352 limited number of ARM architectures. It does not yet fully support
4358 The support for PowerPC (especially PowerPC64) is considered stable
4359 on Linux and FreeBSD: it has been tested to correctly compile many
4360 large C and C++ codebases. PowerPC (32bit) is still missing certain
4361 features (e.g. PIC code on ELF platforms).
4366 clang currently contains some support for other architectures (e.g. Sparc);
4367 however, significant pieces of code generation are still missing, and they
4368 haven't undergone significant testing.
4370 clang contains limited support for the MSP430 embedded processor, but
4371 both the clang support and the LLVM backend support are highly
4374 Other platforms are completely unsupported at the moment. Adding the
4375 minimal support needed for parsing and semantic analysis on a new
4376 platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
4377 tree. This level of support is also sufficient for conversion to LLVM IR
4378 for simple programs. Proper support for conversion to LLVM IR requires
4379 adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
4380 change soon, though. Generating assembly requires a suitable LLVM
4383 Operating System Features and Limitations
4384 -----------------------------------------
4389 Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
4392 See also :ref:`Microsoft Extensions <c_ms>`.
4397 Clang works on Cygwin-1.7.
4402 Clang works on some mingw32 distributions. Clang assumes directories as
4405 - ``C:/mingw/include``
4407 - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
4409 On MSYS, a few tests might fail.
4414 For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
4417 - ``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)``
4418 - ``some_directory/bin/gcc.exe``
4419 - ``some_directory/bin/clang.exe``
4420 - ``some_directory/bin/clang++.exe``
4421 - ``some_directory/bin/../include/c++/GCC_version``
4422 - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
4423 - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
4424 - ``some_directory/bin/../include/c++/GCC_version/backward``
4425 - ``some_directory/bin/../x86_64-w64-mingw32/include``
4426 - ``some_directory/bin/../i686-w64-mingw32/include``
4427 - ``some_directory/bin/../include``
4429 This directory layout is standard for any toolchain you will find on the
4430 official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
4432 Clang expects the GCC executable "gcc.exe" compiled for
4433 ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
4435 `Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
4436 ``x86_64-w64-mingw32``.
4440 TOC Data Transformation
4441 """""""""""""""""""""""
4442 TOC data transformation is off by default (``-mno-tocdata``).
4443 When ``-mtocdata`` is specified, the TOC data transformation will be applied to
4444 all suitable variables with static storage duration, including static data
4445 members of classes and block-scope static variables (if not marked as exceptions,
4448 Suitable variables must:
4450 - have complete types
4451 - be independently generated (i.e., not placed in a pool)
4452 - be at most as large as a pointer
4453 - not be aligned more strictly than a pointer
4454 - not be structs containing flexible array members
4455 - not have internal linkage
4457 - not have section attributes
4458 - not be thread local storage
4460 The TOC data transformation results in the variable, not its address,
4461 being placed in the TOC. This eliminates the need to load the address of the
4462 variable from the TOC.
4465 If the TOC data transformation is applied to a variable whose definition
4466 is imported, the linker will generate fixup code for reading or writing to the
4469 When multiple toc-data options are used, the last option used has the affect.
4470 For example: -mno-tocdata=g5,g1 -mtocdata=g1,g2 -mno-tocdata=g2 -mtocdata=g3,g4
4471 results in -mtocdata=g1,g3,g4
4473 Names of variables not having external linkage will be ignored.
4477 .. option:: -mno-tocdata
4479 This is the default behaviour. Only variables explicitly specified with
4480 ``-mtocdata=`` will have the TOC data transformation applied.
4482 .. option:: -mtocdata
4484 Apply the TOC data transformation to all suitable variables with static
4485 storage duration (including static data members of classes and block-scope
4486 static variables) that are not explicitly specified with ``-mno-tocdata=``.
4488 .. option:: -mno-tocdata=
4490 Can be used in conjunction with ``-mtocdata`` to mark the comma-separated
4491 list of external linkage variables, specified using their mangled names, as
4492 exceptions to ``-mtocdata``.
4494 .. option:: -mtocdata=
4496 Apply the TOC data transformation to the comma-separated list of external
4497 linkage variables, specified using their mangled names, if they are suitable.
4498 Emit diagnostics for all unsuitable variables specified.
4500 Default Visibility Export Mapping
4501 """""""""""""""""""""""""""""""""
4502 The ``-mdefault-visibility-export-mapping=`` option can be used to control
4503 mapping of default visibility to an explicit shared object export
4504 (i.e. XCOFF exported visibility). Three values are provided for the option:
4506 * ``-mdefault-visibility-export-mapping=none``: no additional export
4507 information is created for entities with default visibility.
4508 * ``-mdefault-visibility-export-mapping=explicit``: mark entities for export
4509 if they have explicit (e.g. via an attribute) default visibility from the
4510 source, including RTTI.
4511 * ``-mdefault-visibility-export-mapping=all``: set XCOFF exported visibility
4512 for all entities with default visibility from any source. This gives a
4513 export behavior similar to ELF platforms where all entities with default
4514 visibility are exported.
4521 Clang supports generation of SPIR-V conformant to `the OpenCL Environment
4523 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Env.html>`_.
4525 To generate SPIR-V binaries, Clang uses the external ``llvm-spirv`` tool from the
4526 `SPIRV-LLVM-Translator repo
4527 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_.
4529 Prior to the generation of SPIR-V binary with Clang, ``llvm-spirv``
4530 should be built or installed. Please refer to `the following instructions
4531 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator#build-instructions>`_
4532 for more details. Clang will look for ``llvm-spirv-<LLVM-major-version>`` and
4533 ``llvm-spirv`` executables, in this order, in the ``PATH`` environment variable.
4534 Clang uses ``llvm-spirv`` with `the widely adopted assembly syntax package
4535 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator/#build-with-spirv-tools>`_.
4538 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator/releases>`_ of
4539 ``llvm-spirv`` is aligned with Clang major releases. The same applies to the
4540 main development branch. It is therefore important to ensure the ``llvm-spirv``
4541 version is in alignment with the Clang version. For troubleshooting purposes
4542 ``llvm-spirv`` can be `tested in isolation
4543 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator#test-instructions>`_.
4545 Example usage for OpenCL kernel compilation:
4547 .. code-block:: console
4549 $ clang --target=spirv32 -c test.cl
4550 $ clang --target=spirv64 -c test.cl
4552 Both invocations of Clang will result in the generation of a SPIR-V binary file
4553 `test.o` for 32 bit and 64 bit respectively. This file can be imported
4554 by an OpenCL driver that support SPIR-V consumption or it can be compiled
4555 further by offline SPIR-V consumer tools.
4557 Converting to SPIR-V produced with the optimization levels other than `-O0` is
4558 currently available as an experimental feature and it is not guaranteed to work
4561 Clang also supports integrated generation of SPIR-V without use of ``llvm-spirv``
4562 tool as an experimental feature when ``-fintegrated-objemitter`` flag is passed in
4565 .. code-block:: console
4567 $ clang --target=spirv32 -fintegrated-objemitter -c test.cl
4569 Note that only very basic functionality is supported at this point and therefore
4570 it is not suitable for arbitrary use cases. This feature is only enabled when clang
4571 build is configured with ``-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=SPIRV`` option.
4573 Linking is done using ``spirv-link`` from `the SPIRV-Tools project
4574 <https://github.com/KhronosGroup/SPIRV-Tools#linker>`_. Similar to other external
4575 linkers, Clang will expect ``spirv-link`` to be installed separately and to be
4576 present in the ``PATH`` environment variable. Please refer to `the build and
4577 installation instructions
4578 <https://github.com/KhronosGroup/SPIRV-Tools#build>`_.
4580 .. code-block:: console
4582 $ clang --target=spirv64 test1.cl test2.cl
4584 More information about the SPIR-V target settings and supported versions of SPIR-V
4585 format can be found in `the SPIR-V target guide
4586 <https://llvm.org/docs/SPIRVUsage.html>`__.
4593 clang-cl is an alternative command-line interface to Clang, designed for
4594 compatibility with the Visual C++ compiler, cl.exe.
4596 To enable clang-cl to find system headers, libraries, and the linker when run
4597 from the command-line, it should be executed inside a Visual Studio Native Tools
4598 Command Prompt or a regular Command Prompt where the environment has been set
4599 up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
4601 clang-cl can also be used from inside Visual Studio by selecting the LLVM
4602 Platform Toolset. The toolset is not part of the installer, but may be installed
4604 `Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_.
4605 To use the toolset, select a project in Solution Explorer, open its Property
4606 Page (Alt+F7), and in the "General" section of "Configuration Properties"
4607 change "Platform Toolset" to LLVM. Doing so enables an additional Property
4608 Page for selecting the clang-cl executable to use for builds.
4610 To use the toolset with MSBuild directly, invoke it with e.g.
4611 ``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain
4612 without modifying your project files.
4614 It's also possible to point MSBuild at clang-cl without changing toolset by
4615 passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.
4617 When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:
4621 cmake -G"Visual Studio 16 2019" -T LLVM ..
4623 When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and
4624 ``CMAKE_CXX_COMPILER`` variables to clang-cl:
4628 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"
4629 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..
4632 Command-Line Options
4633 --------------------
4635 To be compatible with cl.exe, clang-cl supports most of the same command-line
4636 options. Those options can start with either ``/`` or ``-``. It also supports
4637 some of Clang's core options, such as the ``-W`` options.
4639 Options that are known to clang-cl, but not currently supported, are ignored
4640 with a warning. For example:
4644 clang-cl.exe: warning: argument unused during compilation: '/AI'
4646 To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
4648 Options that are not known to clang-cl will be ignored by default. Use the
4649 ``-Werror=unknown-argument`` option in order to treat them as errors. If these
4650 options are spelled with a leading ``/``, they will be mistaken for a filename:
4654 clang-cl.exe: error: no such file or directory: '/foobar'
4656 Please `file a bug <https://github.com/llvm/llvm-project/issues/new?labels=clang-cl>`_
4657 for any valid cl.exe flags that clang-cl does not understand.
4659 Execute ``clang-cl /?`` to see a list of supported options:
4663 CL.EXE COMPATIBILITY OPTIONS:
4664 /? Display available options
4665 /arch:<value> Set architecture for code generation
4666 /Brepro- Emit an object file which cannot be reproduced over time
4667 /Brepro Emit an object file which can be reproduced over time
4668 /clang:<arg> Pass <arg> to the clang driver
4669 /C Don't discard comments when preprocessing
4671 /d1PP Retain macro definitions in /E mode
4672 /d1reportAllClassLayout Dump record layout information
4673 /diagnostics:caret Enable caret and column diagnostics (on by default)
4674 /diagnostics:classic Disable column and caret diagnostics
4675 /diagnostics:column Disable caret diagnostics but keep column info
4676 /D <macro[=value]> Define macro
4677 /EH<value> Exception handling model
4678 /EP Disable linemarker output and preprocess to stdout
4679 /execution-charset:<value>
4680 Runtime encoding, supports only UTF-8
4681 /E Preprocess to stdout
4682 /FA Output assembly code file during compilation
4683 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
4684 /Fe<file or directory> Set output executable file or directory (ends in / or \)
4685 /FI <value> Include file before parsing
4686 /Fi<file> Set preprocess output file name (with /P)
4687 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
4693 /Fp<filename> Set pch filename (with /Yc and /Yu)
4694 /GA Assume thread-local variables are defined in the executable
4695 /Gd Set __cdecl as a default calling convention
4696 /GF- Disable string pooling
4697 /GF Enable string pooling (default)
4698 /GR- Disable emission of RTTI data
4699 /Gregcall Set __regcall as a default calling convention
4700 /GR Enable emission of RTTI data
4701 /Gr Set __fastcall as a default calling convention
4702 /GS- Disable buffer security check
4703 /GS Enable buffer security check (default)
4704 /Gs Use stack probes (default)
4705 /Gs<value> Set stack probe size (default 4096)
4706 /guard:<value> Enable Control Flow Guard with /guard:cf,
4707 or only the table with /guard:cf,nochecks.
4708 Enable EH Continuation Guard with /guard:ehcont
4709 /Gv Set __vectorcall as a default calling convention
4710 /Gw- Don't put each data item in its own section
4711 /Gw Put each data item in its own section
4712 /GX- Disable exception handling
4713 /GX Enable exception handling
4714 /Gy- Don't put each function in its own section (default)
4715 /Gy Put each function in its own section
4716 /Gz Set __stdcall as a default calling convention
4717 /help Display available options
4718 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
4719 /I <dir> Add directory to include search path
4720 /J Make char type unsigned
4721 /LDd Create debug DLL
4723 /link <options> Forward options to the linker
4724 /MDd Use DLL debug run-time
4725 /MD Use DLL run-time
4726 /MTd Use static debug run-time
4727 /MT Use static run-time
4728 /O0 Disable optimization
4729 /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy)
4730 /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy)
4731 /Ob0 Disable function inlining
4732 /Ob1 Only inline functions which are (explicitly or implicitly) marked inline
4733 /Ob2 Inline functions as deemed beneficial by the compiler
4735 /Od Disable optimization
4737 /Oi- Disable use of builtin functions
4738 /Oi Enable use of builtin functions
4739 /Os Optimize for size (like clang -Os)
4740 /Ot Optimize for speed (like clang -O3)
4741 /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead
4742 /Oy- Disable frame pointer omission (x86 only, default)
4743 /Oy Enable frame pointer omission (x86 only)
4744 /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-'
4745 /o <file or directory> Set output file or directory (ends in / or \)
4746 /P Preprocess to file
4747 /Qvec- Disable the loop vectorization passes
4748 /Qvec Enable the loop vectorization passes
4749 /showFilenames- Don't print the name of each compiled file (default)
4750 /showFilenames Print the name of each compiled file
4751 /showIncludes Print info about included files to stderr
4752 /source-charset:<value> Source encoding, supports only UTF-8
4753 /std:<value> Language standard to compile for
4754 /TC Treat all source files as C
4755 /Tc <filename> Specify a C source file
4756 /TP Treat all source files as C++
4757 /Tp <filename> Specify a C++ source file
4758 /utf-8 Set source and runtime encoding to UTF-8 (default)
4759 /U <macro> Undefine macro
4760 /vd<value> Control vtordisp placement
4761 /vmb Use a best-case representation method for member pointers
4762 /vmg Use a most-general representation for member pointers
4763 /vmm Set the default most-general representation to multiple inheritance
4764 /vms Set the default most-general representation to single inheritance
4765 /vmv Set the default most-general representation to virtual inheritance
4766 /volatile:iso Volatile loads and stores have standard semantics
4767 /volatile:ms Volatile loads and stores have acquire and release semantics
4768 /W0 Disable all warnings
4772 /W4 Enable -Wall and -Wextra
4773 /Wall Enable -Weverything
4774 /WX- Do not treat warnings as errors
4775 /WX Treat warnings as errors
4776 /w Disable all warnings
4777 /X Don't add %INCLUDE% to the include search path
4778 /Y- Disable precompiled headers, overrides /Yc and /Yu
4779 /Yc<filename> Generate a pch file for all code up to and including <filename>
4780 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
4781 /Z7 Enable CodeView debug information in object files
4782 /Zc:char8_t Enable C++20 char8_t type
4783 /Zc:char8_t- Disable C++20 char8_t type
4784 /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes
4785 /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default)
4786 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
4787 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
4788 /Zc:strictStrings Treat string literals as const
4789 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
4790 /Zc:threadSafeInit Enable thread-safe initialization of static variables
4791 /Zc:trigraphs- Disable trigraphs (default)
4792 /Zc:trigraphs Enable trigraphs
4793 /Zc:twoPhase- Disable two-phase name lookup in templates
4794 /Zc:twoPhase Enable two-phase name lookup in templates
4795 /Zi Alias for /Z7. Does not produce PDBs.
4796 /Zl Don't mention any default libraries in the object file
4797 /Zp Set the default maximum struct packing alignment to 1
4798 /Zp<value> Specify the default maximum struct packing alignment
4799 /Zs Run the preprocessor, parser and semantic analysis stages
4802 -### Print (but do not run) the commands to run for this compilation
4803 --analyze Run the static analyzer
4804 -faddrsig Emit an address-significance table
4805 -fansi-escape-codes Use ANSI escape codes for diagnostics
4806 -fblocks Enable the 'blocks' language feature
4807 -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none.
4808 -fcf-protection Enable cf-protection in 'full' mode
4809 -fcolor-diagnostics Use colors in diagnostics
4810 -fcomplete-member-pointers
4811 Require member pointer base types to be complete if they would be significant under the Microsoft ABI
4812 -fcoverage-mapping Generate coverage mapping to enable code coverage analysis
4813 -fcrash-diagnostics-dir=<dir>
4814 Put crash-report files in <dir>
4815 -fdebug-macro Emit macro debug information
4816 -fdelayed-template-parsing
4817 Parse templated function definitions at the end of the translation unit
4818 -fdiagnostics-absolute-paths
4819 Print absolute paths in diagnostics
4820 -fdiagnostics-parseable-fixits
4821 Print fix-its in machine parseable form
4822 -flto=<value> Set LTO mode to either 'full' or 'thin'
4823 -flto Enable LTO in 'full' mode
4824 -fmerge-all-constants Allow merging of constants
4825 -fmodule-file=<module_name>=<module-file>
4826 Use the specified module file that provides the module <module_name>
4827 -fmodule-header=<header>
4828 Build <header> as a C++20 header unit
4829 -fmodule-output=<path>
4830 Save intermediate module file results when compiling a standard C++ module unit.
4831 -fms-compatibility-version=<value>
4832 Dot-separated value representing the Microsoft compiler version
4833 number to report in _MSC_VER (0 = don't define it; default is same value as installed cl.exe, or 1933)
4834 -fms-compatibility Enable full Microsoft Visual C++ compatibility
4835 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
4836 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
4837 (0 = don't define it; default is same value as installed cl.exe, or 1933)
4838 -fno-addrsig Don't emit an address-significance table
4839 -fno-builtin-<value> Disable implicit builtin knowledge of a specific function
4840 -fno-builtin Disable implicit builtin knowledge of functions
4841 -fno-complete-member-pointers
4842 Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI
4843 -fno-coverage-mapping Disable code coverage analysis
4844 -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash
4845 -fno-debug-macro Do not emit macro debug information
4846 -fno-delayed-template-parsing
4847 Disable delayed template parsing
4848 -fno-sanitize-address-poison-custom-array-cookie
4849 Disable poisoning array cookies when using custom operator new[] in AddressSanitizer
4850 -fno-sanitize-address-use-after-scope
4851 Disable use-after-scope detection in AddressSanitizer
4852 -fno-sanitize-address-use-odr-indicator
4853 Disable ODR indicator globals
4854 -fno-sanitize-ignorelist Don't use ignorelist file for sanitizers
4855 -fno-sanitize-cfi-cross-dso
4856 Disable control flow integrity (CFI) checks for cross-DSO calls.
4857 -fno-sanitize-coverage=<value>
4858 Disable specified features of coverage instrumentation for Sanitizers
4859 -fno-sanitize-memory-track-origins
4860 Disable origins tracking in MemorySanitizer
4861 -fno-sanitize-memory-use-after-dtor
4862 Disable use-after-destroy detection in MemorySanitizer
4863 -fno-sanitize-recover=<value>
4864 Disable recovery for specified sanitizers
4865 -fno-sanitize-stats Disable sanitizer statistics gathering.
4866 -fno-sanitize-thread-atomics
4867 Disable atomic operations instrumentation in ThreadSanitizer
4868 -fno-sanitize-thread-func-entry-exit
4869 Disable function entry/exit instrumentation in ThreadSanitizer
4870 -fno-sanitize-thread-memory-access
4871 Disable memory access instrumentation in ThreadSanitizer
4872 -fno-sanitize-trap=<value>
4873 Disable trapping for specified sanitizers
4874 -fno-standalone-debug Limit debug information produced to reduce size of debug binary
4875 -fno-strict-aliasing Disable optimizations based on strict aliasing rules (default)
4876 -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version
4877 -fprofile-exclude-files=<value>
4878 Instrument only functions from files where names don't match all the regexes separated by a semi-colon
4879 -fprofile-filter-files=<value>
4880 Instrument only functions from files where names match any regex separated by a semi-colon
4881 -fprofile-generate=<dirname>
4882 Generate instrumented code to collect execution counts into a raw profile file in the directory specified by the argument. The filename uses default_%m.profraw pattern
4883 (overridden by LLVM_PROFILE_FILE env var)
4885 Generate instrumented code to collect execution counts into default_%m.profraw file
4886 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
4887 -fprofile-instr-generate=<file_name_pattern>
4888 Generate instrumented code to collect execution counts into the file whose name pattern is specified as the argument
4889 (overridden by LLVM_PROFILE_FILE env var)
4890 -fprofile-instr-generate
4891 Generate instrumented code to collect execution counts into default.profraw file
4892 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
4893 -fprofile-instr-use=<value>
4894 Use instrumentation data for coverage testing or profile-guided optimization
4895 -fprofile-use=<value>
4896 Use instrumentation data for profile-guided optimization
4897 -fprofile-remapping-file=<file>
4898 Use the remappings described in <file> to match the profile data against names in the program
4899 -fprofile-list=<file>
4900 Filename defining the list of functions/files to instrument
4901 -fsanitize-address-field-padding=<value>
4902 Level of field padding for AddressSanitizer
4903 -fsanitize-address-globals-dead-stripping
4904 Enable linker dead stripping of globals in AddressSanitizer
4905 -fsanitize-address-poison-custom-array-cookie
4906 Enable poisoning array cookies when using custom operator new[] in AddressSanitizer
4907 -fsanitize-address-use-after-return=<mode>
4908 Select the mode of detecting stack use-after-return in AddressSanitizer: never | runtime (default) | always
4909 -fsanitize-address-use-after-scope
4910 Enable use-after-scope detection in AddressSanitizer
4911 -fsanitize-address-use-odr-indicator
4912 Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size
4913 -fsanitize-ignorelist=<value>
4914 Path to ignorelist file for sanitizers
4915 -fsanitize-cfi-cross-dso
4916 Enable control flow integrity (CFI) checks for cross-DSO calls.
4917 -fsanitize-cfi-icall-generalize-pointers
4918 Generalize pointers in CFI indirect call type signature checks
4919 -fsanitize-coverage=<value>
4920 Specify the type of coverage instrumentation for Sanitizers
4921 -fsanitize-hwaddress-abi=<value>
4922 Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor)
4923 -fsanitize-memory-track-origins=<value>
4924 Enable origins tracking in MemorySanitizer
4925 -fsanitize-memory-track-origins
4926 Enable origins tracking in MemorySanitizer
4927 -fsanitize-memory-use-after-dtor
4928 Enable use-after-destroy detection in MemorySanitizer
4929 -fsanitize-recover=<value>
4930 Enable recovery for specified sanitizers
4931 -fsanitize-stats Enable sanitizer statistics gathering.
4932 -fsanitize-thread-atomics
4933 Enable atomic operations instrumentation in ThreadSanitizer (default)
4934 -fsanitize-thread-func-entry-exit
4935 Enable function entry/exit instrumentation in ThreadSanitizer (default)
4936 -fsanitize-thread-memory-access
4937 Enable memory access instrumentation in ThreadSanitizer (default)
4938 -fsanitize-trap=<value> Enable trapping for specified sanitizers
4939 -fsanitize-undefined-strip-path-components=<number>
4940 Strip (or keep only, if negative) a given number of path components when emitting check metadata.
4941 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
4942 behavior. See user manual for available checks
4943 -fsplit-lto-unit Enables splitting of the LTO unit.
4944 -fstandalone-debug Emit full debug info for all types used by the program
4945 -fstrict-aliasing Enable optimizations based on strict aliasing rules
4946 -fsyntax-only Run the preprocessor, parser and semantic analysis stages
4947 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
4948 -gcodeview-ghash Emit type record hashes in a .debug$H section
4949 -gcodeview Generate CodeView debug information
4950 -gline-directives-only Emit debug line info directives only
4951 -gline-tables-only Emit debug line number tables only
4952 -miamcu Use Intel MCU ABI
4953 -mllvm <value> Additional arguments to forward to LLVM's option processing
4954 -nobuiltininc Disable builtin #include directories
4955 -Qunused-arguments Don't emit warning for unused driver arguments
4956 -R<remark> Enable the specified remark
4957 --target=<value> Generate code for the given target
4958 --version Print version information
4959 -v Show commands to run and use verbose output
4960 -W<warning> Enable the specified warning
4961 -Xclang <arg> Pass <arg> to the clang compiler
4966 When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all
4967 of the ``<arg>`` arguments and process them as if they were passed to the clang
4968 driver. This mechanism allows you to pass flags that are not exposed in the
4969 clang-cl options or flags that have a different meaning when passed to the clang
4970 driver. Regardless of where they appear in the command line, the ``/clang:``
4971 arguments are treated as if they were passed at the end of the clang-cl command
4974 The /Zc:dllexportInlines- Option
4975 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4977 This causes the class-level `dllexport` and `dllimport` attributes to not apply
4978 to inline member functions, as they otherwise would. For example, in the code
4979 below `S::foo()` would normally be defined and exported by the DLL, but when
4980 using the ``/Zc:dllexportInlines-`` flag it is not:
4984 struct __declspec(dllexport) S {
4988 This has the benefit that the compiler doesn't need to emit a definition of
4989 `S::foo()` in every translation unit where the declaration is included, as it
4990 would otherwise do to ensure there's a definition in the DLL even if it's not
4991 used there. If the declaration occurs in a header file that's widely used, this
4992 can save significant compilation time and output size. It also reduces the
4993 number of functions exported by the DLL similarly to what
4994 ``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.
4995 Since the function declaration comes with an inline definition, users of the
4996 library can use that definition directly instead of importing it from the DLL.
4998 Note that the Microsoft Visual C++ compiler does not support this option, and
4999 if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the
5000 DLL must be compiled in the same way so that it doesn't attempt to dllimport
5001 the inline member functions. The reverse scenario should generally work though:
5002 a DLL compiled without this flag (such as a system library compiled with Visual
5003 C++) can be referenced from code compiled using the flag, meaning that the
5004 referencing code will use the inline definitions instead of importing them from
5007 Also note that like when using ``-fvisibility-inlines-hidden``, the address of
5008 `S::foo()` will be different inside and outside the DLL, breaking the C/C++
5009 standard requirement that functions have a unique address.
5011 The flag does not apply to explicit class template instantiation definitions or
5012 declarations, as those are typically used to explicitly provide a single
5013 definition in a DLL, (dllexported instantiation definition) or to signal that
5014 the definition is available elsewhere (dllimport instantiation declaration). It
5015 also doesn't apply to inline members with static local variables, to ensure
5016 that the same instance of the variable is used inside and outside the DLL.
5018 Using this flag can cause problems when inline functions that would otherwise
5019 be dllexported refer to internal symbols of a DLL. For example:
5025 struct __declspec(dllimport) S {
5026 void foo() { internal(); }
5029 Normally, references to `S::foo()` would use the definition in the DLL from
5030 which it was exported, and which presumably also has the definition of
5031 `internal()`. However, when using ``/Zc:dllexportInlines-``, the inline
5032 definition of `S::foo()` is used directly, resulting in a link error since
5033 `internal()` is not available. Even worse, if there is an inline definition of
5034 `internal()` containing a static local variable, we will now refer to a
5035 different instance of that variable than in the DLL:
5039 inline int internal() { static int x; return x++; }
5041 struct __declspec(dllimport) S {
5042 int foo() { return internal(); }
5045 This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can
5046 lead to the same issue. To avoid it in this case, make `S::foo()` or
5047 `internal()` non-inline, or mark them `dllimport/dllexport` explicitly.
5049 Finding Clang runtime libraries
5050 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5052 clang-cl supports several features that require runtime library support:
5054 - Address Sanitizer (ASan): ``-fsanitize=address``
5055 - Undefined Behavior Sanitizer (UBSan): ``-fsanitize=undefined``
5056 - Code coverage: ``-fprofile-instr-generate -fcoverage-mapping``
5057 - Profile Guided Optimization (PGO): ``-fprofile-generate``
5058 - Certain math operations (int128 division) require the builtins library
5060 In order to use these features, the user must link the right runtime libraries
5061 into their program. These libraries are distributed alongside Clang in the
5062 library resource directory. Clang searches for the resource directory by
5063 searching relative to the Clang executable. For example, if LLVM is installed
5064 in ``C:\Program Files\LLVM``, then the profile runtime library will be located
5066 ``C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows\clang_rt.profile-x86_64.lib``.
5068 For UBSan, PGO, and coverage, Clang will emit object files that auto-link the
5069 appropriate runtime library, but the user generally needs to help the linker
5070 (whether it is ``lld-link.exe`` or MSVC ``link.exe``) find the library resource
5071 directory. Using the example installation above, this would mean passing
5072 ``/LIBPATH:C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows`` to the linker.
5073 If the user links the program with the ``clang`` or ``clang-cl`` drivers, the
5074 driver will pass this flag for them.
5076 The auto-linking can be disabled with -fno-rtlib-defaultlib. If that flag is
5077 used, pass the complete flag to required libraries as described for ASan below.
5079 If the linker cannot find the appropriate library, it will emit an error like
5082 $ clang-cl -c -fsanitize=undefined t.cpp
5084 $ lld-link t.obj -dll
5085 lld-link: error: could not open 'clang_rt.ubsan_standalone-x86_64.lib': no such file or directory
5086 lld-link: error: could not open 'clang_rt.ubsan_standalone_cxx-x86_64.lib': no such file or directory
5088 $ link t.obj -dll -nologo
5089 LINK : fatal error LNK1104: cannot open file 'clang_rt.ubsan_standalone-x86_64.lib'
5091 To fix the error, add the appropriate ``/libpath:`` flag to the link line.
5093 For ASan, as of this writing, the user is also responsible for linking against
5094 the correct ASan libraries.
5096 If the user is using the dynamic CRT (``/MD``), then they should add
5097 ``clang_rt.asan_dynamic-x86_64.lib`` to the link line as a regular input. For
5098 other architectures, replace x86_64 with the appropriate name here and below.
5100 If the user is using the static CRT (``/MT``), then different runtimes are used
5101 to produce DLLs and EXEs. To link a DLL, pass
5102 ``clang_rt.asan_dll_thunk-x86_64.lib``. To link an EXE, pass
5103 ``-wholearchive:clang_rt.asan-x86_64.lib``.
5105 Windows System Headers and Library Lookup
5106 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5108 clang-cl uses a set of different approaches to locate the right system libraries
5109 to link against when building code. The Windows environment uses libraries from
5110 three distinct sources:
5113 2. UCRT (Universal C Runtime)
5114 3. Visual C++ Tools (VCRuntime)
5116 The Windows SDK provides the import libraries and headers required to build
5117 programs against the Windows system packages. Underlying the Windows SDK is the
5118 UCRT, the universal C runtime.
5120 This difference is best illustrated by the various headers that one would find
5121 in the different categories. The WinSDK would contain headers such as
5122 `WinSock2.h` which is part of the Windows API surface, providing the Windows
5123 socketing interfaces for networking. UCRT provides the C library headers,
5124 including e.g. `stdio.h`. Finally, the Visual C++ tools provides the underlying
5125 Visual C++ Runtime headers such as `stdint.h` or `crtdefs.h`.
5127 There are various controls that allow the user control over where clang-cl will
5128 locate these headers. The default behaviour for the Windows SDK and UCRT is as
5131 1. Consult the command line.
5133 Anything the user specifies is always given precedence. The following
5134 extensions are part of the clang-cl toolset:
5138 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix
5139 environments. It allows the control of an alternate location to be treated
5140 as a system root. When specified, it will be used as the root where the
5141 `Windows Kits` is located.
5146 If `/winsysroot:` is not specified, the `/winsdkdir:` argument is consulted
5147 as a location to identify where the Windows SDK is located. Contrary to
5148 `/winsysroot:`, `/winsdkdir:` is expected to be the complete path rather
5149 than a root to locate `Windows Kits`.
5151 The `/winsdkversion:` flag allows the user to specify a version identifier
5152 for the SDK to prefer. When this is specified, no additional validation is
5153 performed and this version is preferred. If the version is not specified,
5154 the highest detected version number will be used.
5156 2. Consult the environment.
5158 TODO: This is not yet implemented.
5160 This will consult the environment variables:
5165 3. Fallback to the registry.
5167 If no arguments are used to indicate where the SDK is present, and the
5168 compiler is running on Windows, the registry is consulted to locate the
5171 The Visual C++ Toolset has a slightly more elaborate mechanism for detection.
5173 1. Consult the command line.
5177 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix
5178 environments. It allows the control of an alternate location to be treated
5179 as a system root. When specified, it will be used as the root where the
5180 `VC` directory is located.
5183 - `/vctoolsversion:`
5185 If `/winsysroot:` is not specified, the `/vctoolsdir:` argument is consulted
5186 as a location to identify where the Visual C++ Tools are located. If
5187 `/vctoolsversion:` is specified, that version is preferred, otherwise, the
5188 highest version detected is used.
5190 2. Consult the environment.
5192 - `/external:[VARIABLE]`
5194 This specifies a user identified environment variable which is treated as
5195 a path delimiter (`;`) separated list of paths to map into `-imsvc`
5196 arguments which are treated as `-isystem`.
5198 - `INCLUDE` and `EXTERNAL_INCLUDE`
5200 The path delimiter (`;`) separated list of paths will be mapped to
5201 `-imsvc` arguments which are treated as `-isystem`.
5203 - `LIB` (indirectly)
5205 The linker `link.exe` or `lld-link.exe` will honour the environment
5206 variable `LIB` which is a path delimiter (`;`) set of paths to consult for
5207 the import libraries to use when linking the final target.
5209 The following environment variables will be consulted and used to form paths
5210 to validate and load content from as appropriate:
5212 - `VCToolsInstallDir`
5216 3. Consult `ISetupConfiguration` [Windows Only]
5218 Assuming that the toolchain is built with `USE_MSVC_SETUP_API` defined and
5219 is running on Windows, the Visual Studio COM interface `ISetupConfiguration`
5220 will be used to locate the installation of the MSVC toolset.
5222 4. Fallback to the registry [DEPRECATED]
5224 The registry information is used to help locate the installation as a final
5225 fallback. This is only possible for pre-VS2017 installations and is
5226 considered deprecated.
5228 Restrictions and Limitations compared to Clang
5229 ----------------------------------------------
5234 Strict aliasing (TBAA) is always off by default in clang-cl. Whereas in clang,
5235 strict aliasing is turned on by default for all optimization levels.
5237 To enable LLVM optimizations based on strict aliasing rules (e.g., optimizations
5238 based on type of expressions in C/C++), user will need to explicitly pass
5239 `-fstrict-aliasing` to clang-cl.