Debian Codegraph @

clang/docs/UsersManual.rst

raw
1 ============================
2 Clang Compiler User's Manual
3 ============================
4
5 .. include:: <isonum.txt>
6
7 .. contents::
8 :local:
9
10 Introduction
11 ============
12
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>`_.
20
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
26 page.
27
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>`.
31
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
36 specific section:
37
38 - :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, C94 (C89+AMD1), C99 (+TC1,
39 TC2, TC3), C11, C17, C23, and C2y.
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>`: C++98, C++03, C++11, C++14, C++17, C++20, C++23,
43 and C++26.
44 - :ref:`Objective C++ Language <objcxx>`
45 - :ref:`OpenCL Kernel Language <opencl>`: OpenCL C 1.0, 1.1, 1.2, 2.0, 3.0,
46 and C++ for OpenCL 1.0 and 2021.
47
48 In addition to these base languages and their dialects, Clang supports a
49 broad variety of language extensions, which are documented in the
50 corresponding language section. These extensions are provided to be
51 compatible with the GCC, Microsoft, and other popular compilers as well
52 as to improve functionality through Clang-specific features. The Clang
53 driver and language features are intentionally designed to be as
54 compatible with the GNU GCC compiler as reasonably possible, easing
55 migration from GCC to Clang. In most cases, code "just works".
56 Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
57 to be compatible with the Visual C++ compiler, cl.exe.
58
59 In addition to language-specific features, Clang has a variety of
60 features that depend on what CPU architecture or operating system is
61 being compiled for. Please see the :ref:`Target-Specific Features and
62 Limitations <target_features>` section for more details.
63
64 .. _terminology:
65
66 Terminology
67 -----------
68 * Lexer -- the part of the compiler responsible for converting source code into
69 abstract representations called tokens.
70 * Preprocessor -- the part of the compiler responsible for in-place textual
71 replacement of source constructs. When the lexer is required to produce a
72 token, it will run the preprocessor while determining which token to produce.
73 In other words, when the lexer encounters something like `#include` or a macro
74 name, the preprocessor will be used to perform the inclusion or expand the
75 macro name into its replacement list, and return the resulting non-preprocessor
76 token.
77 * Parser -- the part of the compiler responsible for determining syntactic
78 correctness of the source code. The parser will request tokens from the lexer
79 and after performing semantic analysis of the production, generates an
80 abstract representation of the source called an AST.
81 * Sema -- the part of the compiler responsible for determining semantic
82 correctness of the source code. It is closely related to the parser and is
83 where many diagnostics are produced.
84 * Diagnostic -- a message to the user about properties of the source code. For
85 example, errors or warnings and their associated notes.
86 * Undefined behavior -- behavior for which the standard imposes no requirements
87 on how the code behaves. Generally speaking, undefined behavior is a bug in
88 the user's code. However, it can also be a place for the compiler to define
89 the behavior, called an extension.
90 * Optimizer -- the part of the compiler responsible for transforming code to
91 have better performance characteristics without changing the semantics of how
92 the code behaves. Note, the optimizer assumes the code has no undefined
93 behavior, so if the code does contain undefined behavior, it will often behave
94 differently depending on which optimization level is enabled.
95 * Frontend -- the Lexer, Preprocessor, Parser, Sema, and LLVM IR code generation
96 parts of the compiler.
97 * Middle-end -- a term used for the of the subset of the backend that does
98 (typically not target specific) optimizations prior to assembly code
99 generation.
100 * Backend -- the parts of the compiler which run after LLVM IR code generation,
101 such as the optimizer and generation of assembly code.
102
103 See the :doc:`InternalsManual` for more details about the internal construction
104 of the compiler.
105
106 Support
107 -------
108 Clang releases happen roughly `every six months <https://llvm.org/docs/HowToReleaseLLVM.html#annual-release-schedule>`_.
109 Only the current public release is officially supported. Bug-fix releases for
110 the current release will be produced on an as-needed basis, but bug fixes are
111 not backported to releases older than the current one.
112
113
114 Command Line Options
115 ====================
116
117 This section is generally an index into other sections. It does not go
118 into depth on the ones that are covered by other sections. However, the
119 first part introduces the language selection and other high level
120 options like :option:`-c`, :option:`-g`, etc.
121
122 Options to Control Error and Warning Messages
123 ---------------------------------------------
124
125 .. option:: -Werror
126
127 Turn warnings into errors.
128
129 .. This is in plain monospaced font because it generates the same label as
130 .. -Werror, and Sphinx complains.
131
132 ``-Werror=foo``
133
134 Turn warning "foo" into an error.
135
136 .. option:: -Wno-error=foo
137
138 Turn warning "foo" into a warning even if :option:`-Werror` is specified.
139
140 .. option:: -Wfoo
141
142 Enable warning "foo".
143 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
144 list of the warning flags that can be specified in this way.
145
146 .. option:: -Wno-foo
147
148 Disable warning "foo".
149
150 .. option:: -w
151
152 Disable all diagnostics.
153
154 .. option:: -Weverything
155
156 :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
157
158 .. option:: -pedantic
159
160 Warn on language extensions.
161
162 .. option:: -pedantic-errors
163
164 Error on language extensions.
165
166 .. option:: -Wsystem-headers
167
168 Enable warnings from system headers.
169
170 .. option:: -ferror-limit=123
171
172 Stop emitting diagnostics after 123 errors have been produced. The default is
173 20, and the error limit can be disabled with `-ferror-limit=0`.
174
175 .. option:: -ftemplate-backtrace-limit=123
176
177 Only emit up to 123 template instantiation notes within the template
178 instantiation backtrace for a single warning or error. The default is 10, and
179 the limit can be disabled with `-ftemplate-backtrace-limit=0`.
180
181 .. option:: --warning-suppression-mappings=foo.txt
182
183 :ref:`Suppress certain diagnostics for certain files. <warning_suppression_mappings>`
184
185 .. _cl_diag_formatting:
186
187 Formatting of Diagnostics
188 ^^^^^^^^^^^^^^^^^^^^^^^^^
189
190 Clang aims to produce beautiful diagnostics by default, particularly for
191 new users that first come to Clang. However, different people have
192 different preferences, and sometimes Clang is driven not by a human,
193 but by a program that wants consistent and easily parsable output. For
194 these cases, Clang provides a wide range of options to control the exact
195 output format of the diagnostics that it generates.
196
197 .. _opt_fshow-column:
198
199 .. option:: -f[no-]show-column
200
201 Print column number in diagnostic.
202
203 This option, which defaults to on, controls whether or not Clang
204 prints the column number of a diagnostic. For example, when this is
205 enabled, Clang will print something like:
206
207 ::
208
209 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
210 #endif bad
211 ^
212 //
213
214 When this is disabled, Clang will print "test.c:28: warning..." with
215 no column number.
216
217 The printed column numbers count bytes from the beginning of the
218 line; take care if your source contains multibyte characters.
219
220 .. _opt_fshow-source-location:
221
222 .. option:: -f[no-]show-source-location
223
224 Print source file/line/column information in diagnostic.
225
226 This option, which defaults to on, controls whether or not Clang
227 prints the filename, line number and column number of a diagnostic.
228 For example, when this is enabled, Clang will print something like:
229
230 ::
231
232 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
233 #endif bad
234 ^
235 //
236
237 When this is disabled, Clang will not print the "test.c:28:8: "
238 part.
239
240 .. _opt_fcaret-diagnostics:
241
242 .. option:: -f[no-]caret-diagnostics
243
244 Print source line and ranges from source code in diagnostic.
245 This option, which defaults to on, controls whether or not Clang
246 prints the source line, source ranges, and caret when emitting a
247 diagnostic. For example, when this is enabled, Clang will print
248 something like:
249
250 ::
251
252 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
253 #endif bad
254 ^
255 //
256
257 .. option:: -f[no-]color-diagnostics
258
259 This option, which defaults to on when a color-capable terminal is
260 detected, controls whether or not Clang prints diagnostics in color.
261
262 When this option is enabled, Clang will use colors to highlight
263 specific parts of the diagnostic, e.g.,
264
265 .. nasty hack to not lose our dignity
266
267 .. raw:: html
268
269 <pre>
270 <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>
271 #endif bad
272 <span style="color:green">^</span>
273 <span style="color:green">//</span>
274 </pre>
275
276 When this is disabled, Clang will just print:
277
278 ::
279
280 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
281 #endif bad
282 ^
283 //
284
285 If the ``NO_COLOR`` environment variable is defined and not empty
286 (regardless of value), color diagnostics are disabled. If ``NO_COLOR`` is
287 defined and ``-fcolor-diagnostics`` is passed on the command line, Clang
288 will honor the command line argument.
289
290 .. option:: -fansi-escape-codes
291
292 Controls whether ANSI escape codes are used instead of the Windows Console
293 API to output colored diagnostics. This option is only used on Windows and
294 defaults to off.
295
296 .. option:: -fdiagnostics-format=clang/msvc/vi
297
298 Changes diagnostic output format to better match IDEs and command line tools.
299
300 This option controls the output format of the filename, line number,
301 and column printed in diagnostic messages. The options, and their
302 effect on formatting a simple conversion diagnostic, follow:
303
304 **clang** (default)
305 ::
306
307 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
308
309 **msvc**
310 ::
311
312 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
313
314 **vi**
315 ::
316
317 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
318
319 .. _opt_fdiagnostics-show-option:
320
321 .. option:: -f[no-]diagnostics-show-option
322
323 Enable ``[-Woption]`` information in diagnostic line.
324
325 This option, which defaults to on, controls whether or not Clang
326 prints the associated :ref:`warning group <cl_diag_warning_groups>`
327 option name when outputting a warning diagnostic. For example, in
328 this output:
329
330 ::
331
332 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
333 #endif bad
334 ^
335 //
336
337 Passing **-fno-diagnostics-show-option** will prevent Clang from
338 printing the [:option:`-Wextra-tokens`] information in
339 the diagnostic. This information tells you the flag needed to enable
340 or disable the diagnostic, either from the command line or through
341 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
342
343 .. option:: -fdiagnostics-show-category=none/id/name
344
345 Enable printing category information in diagnostic line.
346
347 This option, which defaults to "none", controls whether or not Clang
348 prints the category associated with a diagnostic when emitting it.
349 Each diagnostic may or may not have an associated category, if it
350 has one, it is listed in the diagnostic categorization field of the
351 diagnostic line (in the []'s).
352
353 For example, a format string warning will produce these three
354 renditions based on the setting of this option:
355
356 ::
357
358 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
359 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
360 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
361
362 This category can be used by clients that want to group diagnostics
363 by category, so it should be a high-level category. We want dozens
364 of these, not hundreds or thousands of them.
365
366 .. _opt_fsave-optimization-record:
367
368 .. option:: -f[no-]save-optimization-record[=<format>]
369
370 Enable optimization remarks during compilation and write them to a separate
371 file.
372
373 This option, which defaults to off, controls whether Clang writes
374 optimization reports to a separate file. By recording diagnostics in a file,
375 users can parse or sort the remarks in a convenient way.
376
377 By default, the serialization format is YAML.
378
379 The supported serialization formats are:
380
381 - .. _opt_fsave_optimization_record_yaml:
382
383 ``-fsave-optimization-record=yaml``: A structured YAML format.
384
385 - .. _opt_fsave_optimization_record_bitstream:
386
387 ``-fsave-optimization-record=bitstream``: A binary format based on LLVM
388 Bitstream.
389
390 The output file is controlled by :option:`-foptimization-record-file`.
391
392 In the absence of an explicit output file, the file is chosen using the
393 following scheme:
394
395 ``<base>.opt.<format>``
396
397 where ``<base>`` is based on the output file of the compilation (whether
398 it's explicitly specified through `-o` or not) when used with `-c` or `-S`.
399 For example:
400
401 * ``clang -fsave-optimization-record -c in.c -o out.o`` will generate
402 ``out.opt.yaml``
403
404 * ``clang -fsave-optimization-record -c in.c`` will generate
405 ``in.opt.yaml``
406
407 When targeting (Thin)LTO, the base is derived from the output filename, and
408 the extension is not dropped.
409
410 When targeting ThinLTO, the following scheme is used:
411
412 ``<base>.opt.<format>.thin.<num>.<format>``
413
414 Darwin-only: when used for generating a linked binary from a source file
415 (through an intermediate object file), the driver will invoke `cc1` to
416 generate a temporary object file. The temporary remark file will be emitted
417 next to the object file, which will then be picked up by `dsymutil` and
418 emitted in the .dSYM bundle. This is available for all formats except YAML.
419
420 For example:
421
422 ``clang -fsave-optimization-record=bitstream in.c -o out`` will generate
423
424 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.o``
425
426 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.opt.bitstream``
427
428 * ``out``
429
430 * ``out.dSYM/Contents/Resources/Remarks/out``
431
432 Darwin-only: compiling for multiple architectures will use the following
433 scheme:
434
435 ``<base>-<arch>.opt.<format>``
436
437 Note that this is incompatible with passing the
438 :option:`-foptimization-record-file` option.
439
440 .. option:: -foptimization-record-file
441
442 Control the file to which optimization reports are written. This implies
443 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`.
444
445 On Darwin platforms, this is incompatible with passing multiple
446 ``-arch <arch>`` options.
447
448 .. option:: -foptimization-record-passes
449
450 Only include passes which match a specified regular expression.
451
452 When optimization reports are being output (see
453 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
454 option controls the passes that will be included in the final report.
455
456 If this option is not used, all the passes are included in the optimization
457 record.
458
459 .. _opt_fdiagnostics-show-hotness:
460
461 .. option:: -f[no-]diagnostics-show-hotness
462
463 Enable profile hotness information in diagnostic line.
464
465 This option controls whether Clang prints the profile hotness associated
466 with diagnostics in the presence of profile-guided optimization information.
467 This is currently supported with optimization remarks (see
468 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
469 allows users to focus on the hot optimization remarks that are likely to be
470 more relevant for run-time performance.
471
472 For example, in this output, the block containing the callsite of `foo` was
473 executed 3000 times according to the profile data:
474
475 ::
476
477 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
478 sum += foo(x, x - 2);
479 ^
480
481 This option is implied when
482 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
483 Otherwise, it defaults to off.
484
485 .. option:: -fdiagnostics-hotness-threshold
486
487 Prevent optimization remarks from being output if they do not have at least
488 this hotness value.
489
490 This option, which defaults to zero, controls the minimum hotness an
491 optimization remark would need in order to be output by Clang. This is
492 currently supported with optimization remarks (see :ref:`Options to Emit
493 Optimization Reports <rpass>`) when profile hotness information in
494 diagnostics is enabled (see
495 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
496
497 .. _opt_fdiagnostics-fixit-info:
498
499 .. option:: -f[no-]diagnostics-fixit-info
500
501 Enable "FixIt" information in the diagnostics output.
502
503 This option, which defaults to on, controls whether or not Clang
504 prints the information on how to fix a specific diagnostic
505 underneath it when it knows. For example, in this output:
506
507 ::
508
509 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
510 #endif bad
511 ^
512 //
513
514 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
515 printing the "//" line at the end of the message. This information
516 is useful for users who may not understand what is wrong, but can be
517 confusing for machine parsing.
518
519 .. _opt_fdiagnostics-print-source-range-info:
520
521 .. option:: -fdiagnostics-print-source-range-info
522
523 Print machine parsable information about source ranges.
524 This option makes Clang print information about source ranges in a machine
525 parsable format after the file/line/column number information. The
526 information is a simple sequence of brace enclosed ranges, where each range
527 lists the start and end line/column locations. For example, in this output:
528
529 ::
530
531 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
532 P = (P-42) + Gamma*4;
533 ~~~~~~ ^ ~~~~~~~
534
535 The {}'s are generated by -fdiagnostics-print-source-range-info.
536
537 The printed column numbers count bytes from the beginning of the
538 line; take care if your source contains multibyte characters.
539
540 .. option:: -fdiagnostics-parseable-fixits
541
542 Print Fix-Its in a machine parseable form.
543
544 This option makes Clang print available Fix-Its in a machine
545 parseable format at the end of diagnostics. The following example
546 illustrates the format:
547
548 ::
549
550 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
551
552 The range printed is a half-open range, so in this example the
553 characters at column 25 up to but not including column 29 on line 7
554 in t.cpp should be replaced with the string "Gamma". Either the
555 range or the replacement string may be empty (representing strict
556 insertions and strict erasures, respectively). Both the file name
557 and the insertion string escape backslash (as "\\\\"), tabs (as
558 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
559 non-printable characters (as octal "\\xxx").
560
561 The printed column numbers count bytes from the beginning of the
562 line; take care if your source contains multibyte characters.
563
564 .. option:: -fno-elide-type
565
566 Turns off elision in template type printing.
567
568 The default for template type printing is to elide as many template
569 arguments as possible, removing those which are the same in both
570 template types, leaving only the differences. Adding this flag will
571 print all the template arguments. If supported by the terminal,
572 highlighting will still appear on differing arguments.
573
574 Default:
575
576 ::
577
578 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;
579
580 -fno-elide-type:
581
582 ::
583
584 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;
585
586 .. option:: -fdiagnostics-show-template-tree
587
588 Template type diffing prints a text tree.
589
590 For diffing large templated types, this option will cause Clang to
591 display the templates as an indented text tree, one argument per
592 line, with differences marked inline. This is compatible with
593 -fno-elide-type.
594
595 Default:
596
597 ::
598
599 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;
600
601 With :option:`-fdiagnostics-show-template-tree`:
602
603 ::
604
605 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
606 vector<
607 map<
608 [...],
609 map<
610 [float != double],
611 [...]>>>
612
613
614 .. option:: -fcaret-diagnostics-max-lines:
615
616 Controls how many lines of code clang prints for diagnostics. By default,
617 clang prints a maximum of 16 lines of code.
618
619
620 .. option:: -fdiagnostics-show-line-numbers:
621
622 Controls whether clang will print a margin containing the line number on
623 the left of each line of code it prints for diagnostics.
624
625 Default:
626
627 ::
628
629 test.cpp:5:1: error: 'main' must return 'int'
630 5 | void main() {}
631 | ^~~~
632 | int
633
634
635 With -fno-diagnostics-show-line-numbers:
636
637 ::
638
639 test.cpp:5:1: error: 'main' must return 'int'
640 void main() {}
641 ^~~~
642 int
643
644
645
646 .. _cl_diag_warning_groups:
647
648 Individual Warning Groups
649 ^^^^^^^^^^^^^^^^^^^^^^^^^
650
651 TODO: Generate this from tblgen. Define one anchor per warning group.
652
653 .. option:: -Wextra-tokens
654
655 Warn about excess tokens at the end of a preprocessor directive.
656
657 This option, which defaults to on, enables warnings about extra
658 tokens at the end of preprocessor directives. For example:
659
660 ::
661
662 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
663 #endif bad
664 ^
665
666 These extra tokens are not strictly conforming, and are usually best
667 handled by commenting them out.
668
669 .. option:: -Wambiguous-member-template
670
671 Warn about unqualified uses of a member template whose name resolves to
672 another template at the location of the use.
673
674 This option, which defaults to on, enables a warning in the
675 following code:
676
677 ::
678
679 template<typename T> struct set{};
680 template<typename T> struct trait { typedef const T& type; };
681 struct Value {
682 template<typename T> void set(typename trait<T>::type value) {}
683 };
684 void foo() {
685 Value v;
686 v.set<double>(3.2);
687 }
688
689 C++ [basic.lookup.classref] requires this to be an error, but,
690 because it's hard to work around, Clang downgrades it to a warning
691 as an extension.
692
693 .. option:: -Wbind-to-temporary-copy
694
695 Warn about an unusable copy constructor when binding a reference to a
696 temporary.
697
698 This option enables warnings about binding a
699 reference to a temporary when the temporary doesn't have a usable
700 copy constructor. For example:
701
702 ::
703
704 struct NonCopyable {
705 NonCopyable();
706 private:
707 NonCopyable(const NonCopyable&);
708 };
709 void foo(const NonCopyable&);
710 void bar() {
711 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
712 }
713
714 ::
715
716 struct NonCopyable2 {
717 NonCopyable2();
718 NonCopyable2(NonCopyable2&);
719 };
720 void foo(const NonCopyable2&);
721 void bar() {
722 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
723 }
724
725 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
726 whose instantiation produces a compile error, that error will still
727 be a hard error in C++98 mode even if this warning is turned off.
728
729 Options to Control Clang Crash Diagnostics
730 ------------------------------------------
731
732 As unbelievable as it may sound, Clang does crash from time to time.
733 Generally, this only occurs to those living on the `bleeding
734 edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great
735 lengths to assist you in filing a bug report. Specifically, Clang
736 generates preprocessed source file(s) and associated run script(s) upon
737 a crash. These files should be attached to a bug report to ease
738 reproducibility of the failure. Below are the command line options to
739 control the crash diagnostics.
740
741 .. option:: -fcrash-diagnostics=<val>
742
743 Valid values are:
744
745 * ``off`` (Disable auto-generation of preprocessed source files during a clang crash.)
746 * ``compiler`` (Generate diagnostics for compiler crashes (default))
747 * ``all`` (Generate diagnostics for all tools which support it)
748
749 .. option:: -fno-crash-diagnostics
750
751 Disable auto-generation of preprocessed source files during a clang crash.
752
753 The ``-fno-crash-diagnostics`` flag can be helpful for speeding the process
754 of generating a delta reduced test case.
755
756 .. option:: -fcrash-diagnostics-dir=<dir>
757
758 Specify where to write the crash diagnostics files; defaults to the
759 usual location for temporary files.
760
761 .. envvar:: CLANG_CRASH_DIAGNOSTICS_DIR=<dir>
762
763 Like ``-fcrash-diagnostics-dir=<dir>``, specifies where to write the
764 crash diagnostics files, but with lower precedence than the option.
765
766 Clang is also capable of generating preprocessed source file(s) and associated
767 run script(s) even without a crash. This is especially useful when trying to
768 generate a reproducer for warnings or errors while using modules.
769
770 .. option:: -gen-reproducer
771
772 Generates preprocessed source files, a reproducer script and if relevant, a
773 cache containing: built module pcm's and all headers needed to rebuild the
774 same modules.
775
776 .. _rpass:
777
778 Options to Emit Optimization Reports
779 ------------------------------------
780
781 Optimization reports trace, at a high-level, all the major decisions
782 made by compiler transformations. For instance, when the inliner
783 decides to inline function ``foo()`` into ``bar()``, or the loop unroller
784 decides to unroll a loop N times, or the vectorizer decides to
785 vectorize a loop body.
786
787 Clang offers a family of flags which the optimizers can use to emit
788 a diagnostic in three cases:
789
790 1. When the pass makes a transformation (`-Rpass`).
791
792 2. When the pass fails to make a transformation (`-Rpass-missed`).
793
794 3. When the pass determines whether or not to make a transformation
795 (`-Rpass-analysis`).
796
797 NOTE: Although the discussion below focuses on `-Rpass`, the exact
798 same options apply to `-Rpass-missed` and `-Rpass-analysis`.
799
800 Since there are dozens of passes inside the compiler, each of these flags
801 take a regular expression that identifies the name of the pass which should
802 emit the associated diagnostic. For example, to get a report from the inliner,
803 compile the code with:
804
805 .. code-block:: console
806
807 $ clang -O2 -Rpass=inline code.cc -o code
808 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
809 int bar(int j) { return foo(j, j - 2); }
810 ^
811
812 Note that remarks from the inliner are identified with `[-Rpass=inline]`.
813 To request a report from every optimization pass, you should use
814 `-Rpass=.*` (in fact, you can use any valid POSIX regular
815 expression). However, do not expect a report from every transformation
816 made by the compiler. Optimization remarks do not really make sense
817 outside of the major transformations (e.g., inlining, vectorization,
818 loop optimizations) and not every optimization pass supports this
819 feature.
820
821 Note that when using profile-guided optimization information, profile hotness
822 information can be included in the remarks (see
823 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
824
825 Current limitations
826 ^^^^^^^^^^^^^^^^^^^
827
828 1. Optimization remarks that refer to function names will display the
829 mangled name of the function. Since these remarks are emitted by the
830 back end of the compiler, it does not know anything about the input
831 language, nor its mangling rules.
832
833 2. Some source locations are not displayed correctly. The front end has
834 a more detailed source location tracking than the locations included
835 in the debug info (e.g., the front end can locate code inside macro
836 expansions). However, the locations used by `-Rpass` are
837 translated from debug annotations. That translation can be lossy,
838 which results in some remarks having no location information.
839
840 Options to Emit Resource Consumption Reports
841 --------------------------------------------
842
843 These are options that report execution time and consumed memory of different
844 compilations steps.
845
846 .. option:: -fproc-stat-report=
847
848 This option requests the driver to print used memory and execution time of each
849 compilation step. The ``clang`` driver during execution calls different tools,
850 like compiler, assembler, linker etc. With this option the driver reports
851 total execution time, the execution time spent in user mode and peak memory
852 usage of each called tool. Value of the option specifies where the report
853 is sent to. If it specifies a regular file, the data are saved to this file in
854 CSV format:
855
856 .. code-block:: console
857
858 $ clang -fproc-stat-report=abc foo.c
859 $ cat abc
860 clang-11,"/tmp/foo-123456.o",92000,84000,87536
861 ld,"a.out",900,8000,53568
862
863 The data on each row represent:
864
865 * file name of the tool executable,
866 * output file name in quotes,
867 * total execution time in microseconds,
868 * execution time in user mode in microseconds,
869 * peak memory usage in Kb.
870
871 It is possible to specify this option without any value. In this case statistics
872 are printed on standard output in human-readable format:
873
874 .. code-block:: console
875
876 $ clang -fproc-stat-report foo.c
877 clang-11: output=/tmp/foo-855a8e.o, total=68.000 ms, user=60.000 ms, mem=86920 Kb
878 ld: output=a.out, total=8.000 ms, user=4.000 ms, mem=52320 Kb
879
880 The report file specified in the option is locked for write, so this option
881 can be used to collect statistics in parallel builds. The report file is not
882 cleared, new data is appended to it, thus making possible to accumulate build
883 statistics.
884
885 You can also use environment variables to control the process statistics reporting.
886 Setting ``CC_PRINT_PROC_STAT`` to ``1`` enables the feature, the report goes to
887 stdout in human-readable format.
888 Setting ``CC_PRINT_PROC_STAT_FILE`` to a fully qualified file path makes it report
889 process statistics to the given file in the CSV format. Specifying a relative
890 path will likely lead to multiple files with the same name created in different
891 directories, since the path is relative to a changing working directory.
892
893 These environment variables are handy when you need to request the statistics
894 report without changing your build scripts or alter the existing set of compiler
895 options. Note that ``-fproc-stat-report`` take precedence over ``CC_PRINT_PROC_STAT``
896 and ``CC_PRINT_PROC_STAT_FILE``.
897
898 .. code-block:: console
899
900 $ export CC_PRINT_PROC_STAT=1
901 $ export CC_PRINT_PROC_STAT_FILE=~/project-build-proc-stat.csv
902 $ make
903
904 Other Options
905 -------------
906 Clang options that don't fit neatly into other categories.
907
908 .. option:: -fgnuc-version=
909
910 This flag controls the value of ``__GNUC__`` and related macros. This flag
911 does not enable or disable any GCC extensions implemented in Clang. Setting
912 the version to zero causes Clang to leave ``__GNUC__`` and other
913 GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined.
914
915 .. option:: -MV
916
917 When emitting a dependency file, use formatting conventions appropriate
918 for NMake or Jom. Ignored unless another option causes Clang to emit a
919 dependency file.
920
921 When Clang emits a dependency file (e.g., you supplied the -M option)
922 most filenames can be written to the file without any special formatting.
923 Different Make tools will treat different sets of characters as "special"
924 and use different conventions for telling the Make tool that the character
925 is actually part of the filename. Normally, Clang uses backslash to "escape"
926 a special character, which is the convention used by GNU Make. The -MV
927 option tells Clang to put double-quotes around the entire filename, which
928 is the convention used by NMake and Jom.
929
930 .. option:: -femit-dwarf-unwind=<value>
931
932 When to emit DWARF unwind (EH frame) info. This is a Mach-O-specific option.
933
934 Valid values are:
935
936 * ``no-compact-unwind`` - Only emit DWARF unwind when compact unwind encodings
937 aren't available. This is the default for arm64.
938 * ``always`` - Always emit DWARF unwind regardless.
939 * ``default`` - Use the platform-specific default (``always`` for all
940 non-arm64-platforms).
941
942 ``no-compact-unwind`` is a performance optimization -- Clang will emit smaller
943 object files that are more quickly processed by the linker. This may cause
944 binary compatibility issues on older x86_64 targets, however, so use it with
945 caution.
946
947 .. option:: -fdisable-block-signature-string
948
949 Instruct clang not to emit the signature string for blocks. Disabling the
950 string can potentially break existing code that relies on it. Users should
951 carefully consider this possibility when using the flag.
952
953 .. _configuration-files:
954
955 Configuration files
956 -------------------
957
958 Configuration files group command-line options and allow all of them to be
959 specified just by referencing the configuration file. They may be used, for
960 example, to collect options required to tune compilation for a particular
961 target, such as ``-L``, ``-I``, ``-l``, ``--sysroot``, codegen options, etc.
962
963 Configuration files can be either specified on the command line or loaded
964 from default locations. If both variants are present, the default configuration
965 files are loaded first.
966
967 The command line option ``--config=`` can be used to specify explicit
968 configuration files in a Clang invocation. If the option is used multiple times,
969 all specified files are loaded, in order. For example:
970
971 ::
972
973 clang --config=/home/user/cfgs/testing.txt
974 clang --config=debug.cfg --config=runtimes.cfg
975
976 If the provided argument contains a directory separator, it is considered as
977 a file path, and options are read from that file. Otherwise the argument is
978 treated as a file name and is searched for sequentially in the directories:
979
980 - user directory,
981 - system directory,
982 - the directory where Clang executable resides.
983
984 Both user and system directories for configuration files can be specified
985 either during build or during runtime. At build time, use
986 ``CLANG_CONFIG_FILE_USER_DIR`` and ``CLANG_CONFIG_FILE_SYSTEM_DIR``. At run
987 time use the ``--config-user-dir=`` and ``--config-system-dir=`` command line
988 options. Specifying config directories at runtime overrides the config
989 directories set at build time. The first file found is used. It is an error if
990 the required file cannot be found.
991
992 The default configuration files are searched for in the same directories
993 following the rules described in the next paragraphs. Loading default
994 configuration files can be disabled entirely via passing
995 the ``--no-default-config`` flag.
996
997 First, the algorithm searches for a configuration file named
998 ``<triple>-<driver>.cfg`` where `triple` is the triple for the target being
999 built, and `driver` is the name of the currently used driver. The algorithm
1000 first attempts to use the canonical name for the driver used, then falls back
1001 to the one found in the executable name.
1002
1003 The following canonical driver names are used:
1004
1005 - ``clang`` for the ``gcc`` driver (used to compile C programs)
1006 - ``clang++`` for the ``gxx`` driver (used to compile C++ programs)
1007 - ``clang-cpp`` for the ``cpp`` driver (pure preprocessor)
1008 - ``clang-cl`` for the ``cl`` driver
1009 - ``flang`` for the ``flang`` driver
1010 - ``clang-dxc`` for the ``dxc`` driver
1011
1012 For example, when calling ``x86_64-pc-linux-gnu-clang-g++``,
1013 the driver will first attempt to use the configuration file named::
1014
1015 x86_64-pc-linux-gnu-clang++.cfg
1016
1017 If this file is not found, it will attempt to use the name found
1018 in the executable instead::
1019
1020 x86_64-pc-linux-gnu-clang-g++.cfg
1021
1022 Note that options such as ``--driver-mode=``, ``--target=``, ``-m32`` affect
1023 the search algorithm. For example, the aforementioned executable called with
1024 ``-m32`` argument will instead search for::
1025
1026 i386-pc-linux-gnu-clang++.cfg
1027
1028 If none of the aforementioned files are found, the driver will instead search
1029 for separate driver and target configuration files and attempt to load both.
1030 The former is named ``<driver>.cfg`` while the latter is named
1031 ``<triple>.cfg``. Similarly to the previous variants, the canonical driver name
1032 will be preferred, and the compiler will fall back to the actual name.
1033
1034 For example, ``x86_64-pc-linux-gnu-clang-g++`` will attempt to load two
1035 configuration files named respectively::
1036
1037 clang++.cfg
1038 x86_64-pc-linux-gnu.cfg
1039
1040 with fallback to trying::
1041
1042 clang-g++.cfg
1043 x86_64-pc-linux-gnu.cfg
1044
1045 It is not an error if either of these files is not found.
1046
1047 The configuration file consists of command-line options specified on one or
1048 more lines. Lines composed of whitespace characters only are ignored as well as
1049 lines in which the first non-blank character is ``#``. Long options may be split
1050 between several lines by a trailing backslash. Here is an example of a
1051 configuration file:
1052
1053 ::
1054
1055 # Several options on line
1056 -c --target=x86_64-unknown-linux-gnu
1057
1058 # Long option split between lines
1059 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\
1060 include/c++/5.4.0
1061
1062 # other config files may be included
1063 @linux.options
1064
1065 Files included by ``@file`` directives in configuration files are resolved
1066 relative to the including file. For example, if a configuration file
1067 ``~/.llvm/target.cfg`` contains the directive ``@os/linux.opts``, the file
1068 ``linux.opts`` is searched for in the directory ``~/.llvm/os``. Another way to
1069 include a file content is using the command line option ``--config=``. It works
1070 similarly but the included file is searched for using the rules for configuration
1071 files.
1072
1073 To generate paths relative to the configuration file, the ``<CFGDIR>`` token may
1074 be used. This will expand to the absolute path of the directory containing the
1075 configuration file.
1076
1077 In cases where a configuration file is deployed alongside SDK contents, the
1078 SDK directory can remain fully portable by using ``<CFGDIR>`` prefixed paths.
1079 In this way, the user may only need to specify a root configuration file with
1080 ``--config=`` to establish every aspect of the SDK with the compiler:
1081
1082 ::
1083
1084 --target=foo
1085 -isystem <CFGDIR>/include
1086 -L <CFGDIR>/lib
1087 -T <CFGDIR>/ldscripts/link.ld
1088
1089 Usually, config file options are placed before command-line options, regardless
1090 of the actual operation to be performed. The exception is being made for the
1091 options prefixed with the ``$`` character. These will be used only when the linker
1092 is being invoked, and added after all of the command-line specified linker
1093 inputs. Here is an example of ``$``-prefixed options:
1094
1095 ::
1096
1097 $-Wl,-Bstatic $-lm
1098 $-Wl,-Bshared
1099
1100 Language and Target-Independent Features
1101 ========================================
1102
1103 Freestanding Builds
1104 -------------------
1105 Passing the ``-ffreestanding`` flag causes Clang to build for a freestanding
1106 (rather than a hosted) environment. The flag has the following effects:
1107
1108 * the ``__STDC_HOSTED__`` predefined macro will expand to ``0``,
1109 * builtin functions are disabled by default (``-fno-builtins``),
1110 * unwind tables are disabled by default
1111 (``fno-asynchronous-unwind-tables -fno-unwind-tables``), and
1112 * does not treat the global ``main`` function as a special function.
1113
1114 An implementation of the following runtime library functions must always be
1115 provided with the usual semantics, as Clang will generate calls to them:
1116
1117 * ``memcpy``,
1118 * ``memmove``, and
1119 * ``memset``.
1120
1121 Clang does not, by itself, provide a full "conforming freestanding
1122 implementation". If you wish to have a conforming freestanding implementation,
1123 you must provide a freestanding C library. While Clang provides some of the
1124 required header files, it does not provide all of them, nor any library
1125 implementations.
1126
1127 Conversely, when ``-ffreestanding`` is specified, Clang does not require you to
1128 provide a conforming freestanding implementation library. Clang will not make
1129 any assumptions as to the availability or semantics of standard-library
1130 functions other than those mentioned above.
1131
1132 Controlling Errors and Warnings
1133 -------------------------------
1134
1135 Clang provides a number of ways to control which code constructs cause
1136 it to emit errors and warning messages, and how they are displayed to
1137 the console.
1138
1139 Controlling How Clang Displays Diagnostics
1140 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1141
1142 When Clang emits a diagnostic, it includes rich information in the
1143 output, and gives you fine-grain control over which information is
1144 printed. Clang has the ability to print this information, and these are
1145 the options that control it:
1146
1147 #. A file/line/column indicator that shows exactly where the diagnostic
1148 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
1149 :ref:`-fshow-source-location <opt_fshow-source-location>`].
1150 #. A categorization of the diagnostic as a note, warning, error, or
1151 fatal error.
1152 #. A text string that describes what the problem is.
1153 #. An option that indicates how to control the diagnostic (for
1154 diagnostics that support it)
1155 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
1156 #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
1157 for clients that want to group diagnostics by class (for diagnostics
1158 that support it)
1159 [:option:`-fdiagnostics-show-category`].
1160 #. The line of source code that the issue occurs on, along with a caret
1161 and ranges that indicate the important locations
1162 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
1163 #. "FixIt" information, which is a concise explanation of how to fix the
1164 problem (when Clang is certain it knows)
1165 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
1166 #. A machine-parsable representation of the ranges involved (off by
1167 default)
1168 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
1169
1170 For more information please see :ref:`Formatting of
1171 Diagnostics <cl_diag_formatting>`.
1172
1173 Diagnostic Mappings
1174 ^^^^^^^^^^^^^^^^^^^
1175
1176 All diagnostics are mapped into one of these 6 classes:
1177
1178 - Ignored
1179 - Note
1180 - Remark
1181 - Warning
1182 - Error
1183 - Fatal
1184
1185 .. _diagnostics_categories:
1186
1187 Diagnostic Categories
1188 ^^^^^^^^^^^^^^^^^^^^^
1189
1190 Though not shown by default, diagnostics may each be associated with a
1191 high-level category. This category is intended to make it possible to
1192 triage builds that produce a large number of errors or warnings in a
1193 grouped way.
1194
1195 Categories are not shown by default, but they can be turned on with the
1196 :option:`-fdiagnostics-show-category` option.
1197 When set to "``name``", the category is printed textually in the
1198 diagnostic output. When it is set to "``id``", a category number is
1199 printed. The mapping of category names to category id's can be obtained
1200 by running '``clang --print-diagnostic-categories``'.
1201
1202 Controlling Diagnostics via Command Line Flags
1203 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1204
1205 TODO: -W flags, -pedantic, etc
1206
1207 .. _pragma_gcc_diagnostic:
1208
1209 Controlling Diagnostics via Pragmas
1210 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1211
1212 Clang can also control what diagnostics are enabled through the use of
1213 pragmas in the source code. This is useful for turning off specific
1214 warnings in a section of source code. Clang supports GCC's pragma for
1215 compatibility with existing source code, so ``#pragma GCC diagnostic``
1216 and ``#pragma clang diagnostic`` are synonyms for Clang. GCC will ignore
1217 ``#pragma clang diagnostic``, though.
1218
1219 The pragma may control any warning that can be used from the command
1220 line. Warnings may be set to ignored, warning, error, or fatal. The
1221 following example code will tell Clang or GCC to ignore the ``-Wall``
1222 warnings:
1223
1224 .. code-block:: c
1225
1226 #pragma GCC diagnostic ignored "-Wall"
1227
1228 Clang also allows you to push and pop the current warning state. This is
1229 particularly useful when writing a header file that will be compiled by
1230 other people, because you don't know what warning flags they build with.
1231
1232 In the example below, :option:`-Wextra-tokens` is ignored for only a single line
1233 of code, after which the diagnostics return to whatever state had previously
1234 existed.
1235
1236 .. code-block:: c
1237
1238 #if foo
1239 #endif foo // warning: extra tokens at end of #endif directive
1240
1241 #pragma GCC diagnostic push
1242 #pragma GCC diagnostic ignored "-Wextra-tokens"
1243
1244 #if foo
1245 #endif foo // no warning
1246
1247 #pragma GCC diagnostic pop
1248
1249 The push and pop pragmas will save and restore the full diagnostic state
1250 of the compiler, regardless of how it was set. It should be noted that while Clang
1251 supports the GCC pragma, Clang and GCC do not support the exact same set
1252 of warnings, so even when using GCC-compatible #pragmas there is no
1253 guarantee that they will have identical behaviour on both compilers.
1254
1255 Clang also doesn't yet support GCC behavior for ``#pragma diagnostic pop``
1256 that doesn't have a corresponding ``#pragma diagnostic push``. In this case,
1257 GCC pretends that there is a ``#pragma diagnostic push`` at the very beginning
1258 of the source file, so "unpaired" ``#pragma diagnostic pop`` matches that
1259 implicit push. This makes a difference for ``#pragma GCC diagnostic ignored``
1260 which are not guarded by push and pop. Refer to
1261 `GCC documentation <https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html>`_
1262 for details.
1263
1264 Like GCC, Clang accepts ``ignored``, ``warning``, ``error``, and ``fatal``
1265 severity levels. They can be used to change severity of a particular diagnostic
1266 for a region of source file. A notable difference from GCC is that diagnostic
1267 not enabled via command line arguments can't be enabled this way yet.
1268
1269 Some diagnostics associated with a ``-W`` flag have the error severity by
1270 default. They can be ignored or downgraded to warnings:
1271
1272 .. code-block:: cpp
1273
1274 // C only
1275 #pragma GCC diagnostic warning "-Wimplicit-function-declaration"
1276 int main(void) { puts(""); }
1277
1278 In addition to controlling warnings and errors generated by the compiler, it is
1279 possible to generate custom warning and error messages through the following
1280 pragmas:
1281
1282 .. code-block:: c
1283
1284 // The following will produce warning messages
1285 #pragma message "some diagnostic message"
1286 #pragma GCC warning "TODO: replace deprecated feature"
1287
1288 // The following will produce an error message
1289 #pragma GCC error "Not supported"
1290
1291 These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
1292 directives, except that they may also be embedded into preprocessor macros via
1293 the C99 ``_Pragma`` operator, for example:
1294
1295 .. code-block:: c
1296
1297 #define STR(X) #X
1298 #define DEFER(M,...) M(__VA_ARGS__)
1299 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
1300
1301 CUSTOM_ERROR("Feature not available");
1302
1303 Controlling Diagnostics in System Headers
1304 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1305
1306 Warnings are suppressed when they occur in system headers. By default,
1307 an included file is treated as a system header if it is found in an
1308 include path specified by ``-isystem``, but this can be overridden in
1309 several ways.
1310
1311 The ``system_header`` pragma can be used to mark the current file as
1312 being a system header. No warnings will be produced from the location of
1313 the pragma onwards within the same file.
1314
1315 .. code-block:: c
1316
1317 #if foo
1318 #endif foo // warning: extra tokens at end of #endif directive
1319
1320 #pragma clang system_header
1321
1322 #if foo
1323 #endif foo // no warning
1324
1325 The `--system-header-prefix=` and `--no-system-header-prefix=`
1326 command-line arguments can be used to override whether subsets of an include
1327 path are treated as system headers. When the name in a ``#include`` directive
1328 is found within a header search path and starts with a system prefix, the
1329 header is treated as a system header. The last prefix on the
1330 command-line which matches the specified header name takes precedence.
1331 For instance:
1332
1333 .. code-block:: console
1334
1335 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
1336 --no-system-header-prefix=x/y/
1337
1338 Here, ``#include "x/a.h"`` is treated as including a system header, even
1339 if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
1340 as not including a system header, even if the header is found in
1341 ``bar``.
1342
1343 A ``#include`` directive which finds a file relative to the current
1344 directory is treated as including a system header if the including file
1345 is treated as a system header.
1346
1347 Controlling Deprecation Diagnostics in Clang-Provided C Runtime Headers
1348 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1349
1350 Clang is responsible for providing some of the C runtime headers that cannot be
1351 provided by a platform CRT, such as implementation limits or when compiling in
1352 freestanding mode. Define the ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro
1353 prior to including such a C runtime header to disable the deprecation warnings.
1354 Note that the C Standard Library headers are allowed to transitively include
1355 other standard library headers (see 7.1.2p5), and so the most appropriate use
1356 of this macro is to set it within the build system using ``-D`` or before any
1357 include directives in the translation unit.
1358
1359 .. code-block:: c
1360
1361 #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
1362 #include <stdint.h> // Clang CRT deprecation warnings are disabled.
1363 #include <stdatomic.h> // Clang CRT deprecation warnings are disabled.
1364
1365 .. _diagnostics_enable_everything:
1366
1367 Enabling All Diagnostics
1368 ^^^^^^^^^^^^^^^^^^^^^^^^
1369
1370 In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
1371 by passing :option:`-Weverything`. This works as expected with
1372 :option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some
1373 diagnostics contradict each other, therefore, users of :option:`-Weverything`
1374 often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat`
1375 because they contradict recent C++ standards.
1376
1377 Since :option:`-Weverything` enables every diagnostic, we generally don't
1378 recommend using it. `-Wall` `-Wextra` are a better choice for most projects.
1379 Using :option:`-Weverything` means that updating your compiler is more difficult
1380 because you're exposed to experimental diagnostics which might be of lower
1381 quality than the default ones. If you do use :option:`-Weverything` then we
1382 advise that you address all new compiler diagnostics as they get added to Clang,
1383 either by fixing everything they find or explicitly disabling that diagnostic
1384 with its corresponding `Wno-` option.
1385
1386 Note that when combined with :option:`-w` (which disables all warnings),
1387 disabling all warnings wins.
1388
1389 .. _warning_suppression_mappings:
1390
1391 Controlling Diagnostics via Suppression Mappings
1392 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1393
1394 Warning suppression mappings enable users to suppress Clang's diagnostics at a
1395 per-file granularity. This allows enforcing diagnostics in specific parts of the
1396 project even if there are violations in some headers.
1397
1398 .. code-block:: console
1399
1400 $ cat mappings.txt
1401 [unused]
1402 src:foo/*
1403
1404 $ clang --warning-suppression-mappings=mapping.txt -Wunused foo/bar.cc
1405 # This compilation won't emit any unused findings for sources under foo/
1406 # directory. But it'll still complain for all the other sources, e.g:
1407 $ cat foo/bar.cc
1408 #include "dir/include.h" // Clang flags unused declarations here.
1409 #include "foo/include.h" // but unused warnings under this source are omitted.
1410 #include "next_to_bar_cc.h" // as are unused warnings from this header file.
1411 // Further, unused warnings in the remainder of bar.cc are also omitted.
1412
1413
1414 See :doc:`WarningSuppressionMappings` for details about the file format and
1415 functionality.
1416
1417 Controlling Static Analyzer Diagnostics
1418 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1419
1420 While not strictly part of the compiler, the diagnostics from Clang's
1421 `static analyzer <https://clang-analyzer.llvm.org>`_ can also be
1422 influenced by the user via changes to the source code. See the available
1423 `annotations <analyzer/user-docs/Annotations.html>`_ and the analyzer's
1424 `FAQ page <analyzer/user-docs/FAQ.html#exclude-code>`_ for more information.
1425
1426 .. _usersmanual-precompiled-headers:
1427
1428 Precompiled Headers
1429 -------------------
1430
1431 `Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_
1432 are a general approach employed by many compilers to reduce compilation
1433 time. The underlying motivation of the approach is that it is common for
1434 the same (and often large) header files to be included by multiple
1435 source files. Consequently, compile times can often be greatly improved
1436 by caching some of the (redundant) work done by a compiler to process
1437 headers. Precompiled header files, which represent one of many ways to
1438 implement this optimization, are literally files that represent an
1439 on-disk cache that contains the vital information necessary to reduce
1440 some of the work needed to process a corresponding header file. While
1441 details of precompiled headers vary between compilers, precompiled
1442 headers have been shown to be highly effective at speeding up program
1443 compilation on systems with very large system headers (e.g., macOS).
1444
1445 Generating a PCH File
1446 ^^^^^^^^^^^^^^^^^^^^^
1447
1448 To generate a PCH file using Clang, one invokes Clang with the
1449 `-x <language>-header` option. This mirrors the interface in GCC
1450 for generating PCH files:
1451
1452 .. code-block:: console
1453
1454 $ gcc -x c-header test.h -o test.h.gch
1455 $ clang -x c-header test.h -o test.h.pch
1456
1457 Using a PCH File
1458 ^^^^^^^^^^^^^^^^
1459
1460 A PCH file can then be used as a prefix header when a ``-include-pch``
1461 option is passed to ``clang``:
1462
1463 .. code-block:: console
1464
1465 $ clang -include-pch test.h.pch test.c -o test
1466
1467 The ``clang`` driver will check if the PCH file ``test.h.pch`` is
1468 available; if so, the contents of ``test.h`` (and the files it includes)
1469 will be processed from the PCH file. Otherwise, Clang will report an error.
1470
1471 .. note::
1472
1473 Clang does *not* automatically use PCH files for headers that are directly
1474 included within a source file or indirectly via :option:`-include`.
1475 For example:
1476
1477 .. code-block:: console
1478
1479 $ clang -x c-header test.h -o test.h.pch
1480 $ cat test.c
1481 #include "test.h"
1482 $ clang test.c -o test
1483
1484 In this example, ``clang`` will not automatically use the PCH file for
1485 ``test.h`` since ``test.h`` was included directly in the source file and not
1486 specified on the command line using ``-include-pch``.
1487
1488 Ignoring a PCH File
1489 ^^^^^^^^^^^^^^^^^^^
1490
1491 To ignore PCH options, a `-ignore-pch` option is passed to ``clang``:
1492
1493 .. code-block:: console
1494
1495 $ clang -x c-header test.h -Xclang -ignore-pch -o test.h.pch
1496 $ clang -include-pch test.h.pch -Xclang -ignore-pch test.c -o test
1497
1498 This option disables precompiled headers, overrides -emit-pch and -include-pch.
1499 test.h.pch is not generated and not used as a prefix header.
1500
1501 Relocatable PCH Files
1502 ^^^^^^^^^^^^^^^^^^^^^
1503
1504 It is sometimes necessary to build a precompiled header from headers
1505 that are not yet in their final, installed locations. For example, one
1506 might build a precompiled header within the build tree that is then
1507 meant to be installed alongside the headers. Clang permits the creation
1508 of "relocatable" precompiled headers, which are built with a given path
1509 (into the build directory) and can later be used from an installed
1510 location.
1511
1512 To build a relocatable precompiled header, place your headers into a
1513 subdirectory whose structure mimics the installed location. For example,
1514 if you want to build a precompiled header for the header ``mylib.h``
1515 that will be installed into ``/usr/include``, create a subdirectory
1516 ``build/usr/include`` and place the header ``mylib.h`` into that
1517 subdirectory. If ``mylib.h`` depends on other headers, then they can be
1518 stored within ``build/usr/include`` in a way that mimics the installed
1519 location.
1520
1521 Building a relocatable precompiled header requires two additional
1522 arguments. First, pass the ``--relocatable-pch`` flag to indicate that
1523 the resulting PCH file should be relocatable. Second, pass
1524 ``-isysroot /path/to/build``, which makes all includes for your library
1525 relative to the build directory. For example:
1526
1527 .. code-block:: console
1528
1529 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
1530
1531 When loading the relocatable PCH file, the various headers used in the
1532 PCH file are found from the system header root. For example, ``mylib.h``
1533 can be found in ``/usr/include/mylib.h``. If the headers are installed
1534 in some other system root, the ``-isysroot`` option can be used provide
1535 a different system root from which the headers will be based. For
1536 example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
1537 ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
1538
1539 Relocatable precompiled headers are intended to be used in a limited
1540 number of cases where the compilation environment is tightly controlled
1541 and the precompiled header cannot be generated after headers have been
1542 installed.
1543
1544 .. _controlling-fp-behavior:
1545
1546 Controlling Floating Point Behavior
1547 -----------------------------------
1548
1549 Clang provides a number of ways to control floating point behavior, including
1550 with command line options and source pragmas. This section
1551 describes the various floating point semantic modes and the corresponding options.
1552
1553 .. csv-table:: Floating Point Semantic Modes
1554 :header: "Mode", "Values"
1555 :widths: 15, 30, 30
1556
1557 "ffp-exception-behavior", "{ignore, strict, maytrap}",
1558 "fenv_access", "{off, on}", "(none)"
1559 "frounding-math", "{dynamic, tonearest, downward, upward, towardzero}"
1560 "ffp-contract", "{on, off, fast, fast-honor-pragmas}"
1561 "fdenormal-fp-math", "{IEEE, PreserveSign, PositiveZero}"
1562 "fdenormal-fp-math-fp32", "{IEEE, PreserveSign, PositiveZero}"
1563 "fmath-errno", "{on, off}"
1564 "fhonor-nans", "{on, off}"
1565 "fhonor-infinities", "{on, off}"
1566 "fsigned-zeros", "{on, off}"
1567 "freciprocal-math", "{on, off}"
1568 "fallow-approximate-fns", "{on, off}"
1569 "fassociative-math", "{on, off}"
1570 "fcomplex-arithmetic", "{basic, improved, full, promoted}"
1571
1572 This table describes the option settings that correspond to the three
1573 floating point semantic models: precise (the default), strict, and fast.
1574
1575
1576 .. csv-table:: Floating Point Models
1577 :header: "Mode", "Precise", "Strict", "Fast", "Aggressive"
1578 :widths: 25, 25, 25, 25, 25
1579
1580 "except_behavior", "ignore", "strict", "ignore", "ignore"
1581 "fenv_access", "off", "on", "off", "off"
1582 "rounding_mode", "tonearest", "dynamic", "tonearest", "tonearest"
1583 "contract", "on", "off", "fast", "fast"
1584 "support_math_errno", "on", "on", "off", "off"
1585 "no_honor_nans", "off", "off", "off", "on"
1586 "no_honor_infinities", "off", "off", "off", "on"
1587 "no_signed_zeros", "off", "off", "on", "on"
1588 "allow_reciprocal", "off", "off", "on", "on"
1589 "allow_approximate_fns", "off", "off", "on", "on"
1590 "allow_reassociation", "off", "off", "on", "on"
1591 "complex_arithmetic", "full", "full", "promoted", "basic"
1592
1593 The ``-ffp-model`` option does not modify the ``fdenormal-fp-math``
1594 setting, but it does have an impact on whether ``crtfastmath.o`` is
1595 linked. Because linking ``crtfastmath.o`` has a global effect on the
1596 program, and because the global denormal handling can be changed in
1597 other ways, the state of ``fdenormal-fp-math`` handling cannot
1598 be assumed in any function based on fp-model. See :ref:`crtfastmath.o`
1599 for more details.
1600
1601 .. option:: -ffast-math
1602
1603 Enable fast-math mode. This option lets the
1604 compiler make aggressive, potentially-lossy assumptions about
1605 floating-point math. These include:
1606
1607 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1608 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1609 ``(a + b) * c == a * c + b * c``),
1610 * No ``NaN`` or infinite values will be operands or results of
1611 floating-point operations,
1612 * ``+0`` and ``-0`` may be treated as interchangeable.
1613
1614 ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor
1615 macro. Some math libraries recognize this macro and change their behavior.
1616 With the exception of ``-ffp-contract=fast``, using any of the options
1617 below to disable any of the individual optimizations in ``-ffast-math``
1618 will cause ``__FAST_MATH__`` to no longer be set.
1619 ``-ffast-math`` enables ``-fcx-limited-range``.
1620
1621 This option implies:
1622
1623 * ``-fno-honor-infinities``
1624
1625 * ``-fno-honor-nans``
1626
1627 * ``-fapprox-func``
1628
1629 * ``-fno-math-errno``
1630
1631 * ``-ffinite-math-only``
1632
1633 * ``-fassociative-math``
1634
1635 * ``-freciprocal-math``
1636
1637 * ``-fno-signed-zeros``
1638
1639 * ``-fno-trapping-math``
1640
1641 * ``-fno-rounding-math``
1642
1643 * ``-ffp-contract=fast``
1644
1645 Note: ``-ffast-math`` causes ``crtfastmath.o`` to be linked with code unless
1646 ``-shared`` or ``-mno-daz-ftz`` is present. See
1647 :ref:`crtfastmath.o` for more details.
1648
1649 .. option:: -fno-fast-math
1650
1651 Disable fast-math mode. This option disables unsafe floating-point
1652 optimizations by preventing the compiler from making any transformations that
1653 could affect the results.
1654
1655 This option implies:
1656
1657 * ``-fhonor-infinities``
1658
1659 * ``-fhonor-nans``
1660
1661 * ``-fno-approx-func``
1662
1663 * ``-fno-finite-math-only``
1664
1665 * ``-fno-associative-math``
1666
1667 * ``-fno-reciprocal-math``
1668
1669 * ``-fsigned-zeros``
1670
1671 * ``-ffp-contract=on``
1672
1673 Also, this option resets following options to their target-dependent defaults.
1674
1675 * ``-f[no-]math-errno``
1676
1677 There is ambiguity about how ``-ffp-contract``, ``-ffast-math``,
1678 and ``-fno-fast-math`` behave when combined. To keep the value of
1679 ``-ffp-contract`` consistent, we define this set of rules:
1680
1681 * ``-ffast-math`` sets ``ffp-contract`` to ``fast``.
1682
1683 * ``-fno-fast-math`` sets ``-ffp-contract`` to ``on`` (``fast`` for CUDA and
1684 HIP).
1685
1686 * If ``-ffast-math`` and ``-ffp-contract`` are both seen, but
1687 ``-ffast-math`` is not followed by ``-fno-fast-math``, ``ffp-contract``
1688 will be given the value of whichever option was last seen.
1689
1690 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has been seen at least
1691 once, the ``ffp-contract`` will get the value of the last seen value of
1692 ``-ffp-contract``.
1693
1694 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has not been seen, the
1695 ``-ffp-contract`` setting is determined by the default value of
1696 ``-ffp-contract``.
1697
1698 Note: ``-fno-fast-math`` causes ``crtfastmath.o`` to not be linked with code
1699 unless ``-mdaz-ftz`` is present.
1700
1701 .. option:: -fdenormal-fp-math=<value>
1702
1703 Select which denormal numbers the code is permitted to require.
1704
1705 Valid values are:
1706
1707 * ``ieee`` - IEEE 754 denormal numbers
1708 * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 0
1709 * ``positive-zero`` - denormals are flushed to positive zero
1710
1711 The default value depends on the target. For most targets, it defaults to
1712 ``ieee``.
1713
1714 .. option:: -f[no-]strict-float-cast-overflow
1715
1716 When a floating-point value is not representable in a destination integer
1717 type, the code has undefined behavior according to the language standard.
1718 By default, Clang will not guarantee any particular result in that case.
1719 With the 'no-strict' option, Clang will saturate towards the smallest and
1720 largest representable integer values instead. NaNs will be converted to zero.
1721 Defaults to ``-fstrict-float-cast-overflow``.
1722
1723 .. option:: -f[no-]math-errno
1724
1725 Require math functions to indicate errors by setting errno.
1726 The default varies by ToolChain. ``-fno-math-errno`` allows optimizations
1727 that might cause standard C math functions to not set ``errno``.
1728 For example, on some systems, the math function ``sqrt`` is specified
1729 as setting ``errno`` to ``EDOM`` when the input is negative. On these
1730 systems, the compiler cannot normally optimize a call to ``sqrt`` to use
1731 inline code (e.g. the x86 ``sqrtsd`` instruction) without additional
1732 checking to ensure that ``errno`` is set appropriately.
1733 ``-fno-math-errno`` permits these transformations.
1734
1735 On some targets, math library functions never set ``errno``, and so
1736 ``-fno-math-errno`` is the default. This includes most BSD-derived
1737 systems, including Darwin.
1738
1739 .. option:: -f[no-]trapping-math
1740
1741 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.
1742
1743 - The option ``-ftrapping-math`` behaves identically to ``-ffp-exception-behavior=strict``.
1744 - The option ``-fno-trapping-math`` behaves identically to ``-ffp-exception-behavior=ignore``. This is the default.
1745
1746 .. option:: -ffp-contract=<value>
1747
1748 Specify when the compiler is permitted to form fused floating-point
1749 operations, such as fused multiply-add (FMA). Fused operations are
1750 permitted to produce more precise results than performing the same
1751 operations separately.
1752
1753 The C and C++ standards permit intermediate floating-point results within an
1754 expression to be computed with more precision than their type would
1755 normally allow. This permits operation fusing, and Clang takes advantage
1756 of this by default (``on``). Fusion across statements is not compliant with
1757 the C and C++ standards but can be enabled using ``-ffp-contract=fast``.
1758
1759 Fusion can be controlled with the ``FP_CONTRACT`` and ``clang fp contract``
1760 pragmas. Please note that pragmas will be ignored with
1761 ``-ffp-contract=fast``, and refer to the pragma documentation for a
1762 description of how the pragmas interact with the different ``-ffp-contract``
1763 option values.
1764
1765 Valid values are:
1766
1767 * ``fast``: enable fusion across statements disregarding pragmas, breaking
1768 compliance with the C and C++ standards (default for CUDA).
1769 * ``on``: enable C and C++ standard compliant fusion in the same statement
1770 unless dictated by pragmas (default for languages other than CUDA/HIP)
1771 * ``off``: disable fusion
1772 * ``fast-honor-pragmas``: fuse across statements unless dictated by pragmas
1773 (default for HIP)
1774
1775 .. option:: -f[no-]honor-infinities
1776
1777 Allow floating-point optimizations that assume arguments and results are
1778 not +-Inf.
1779 Defaults to ``-fhonor-infinities``.
1780
1781 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1782 has the same effect as specifying ``-ffinite-math-only``.
1783
1784 .. option:: -f[no-]honor-nans
1785
1786 Allow floating-point optimizations that assume arguments and results are
1787 not NaNs.
1788 Defaults to ``-fhonor-nans``.
1789
1790 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1791 has the same effect as specifying ``-ffinite-math-only``.
1792
1793 .. option:: -f[no-]approx-func
1794
1795 Allow certain math function calls (such as ``log``, ``sqrt``, ``pow``, etc)
1796 to be replaced with an approximately equivalent set of instructions
1797 or alternative math function calls. For example, a ``pow(x, 0.25)``
1798 may be replaced with ``sqrt(sqrt(x))``, despite being an inexact result
1799 in cases where ``x`` is ``-0.0`` or ``-inf``.
1800 Defaults to ``-fno-approx-func``.
1801
1802 .. option:: -f[no-]signed-zeros
1803
1804 Allow optimizations that ignore the sign of floating point zeros.
1805 Defaults to ``-fsigned-zeros``.
1806
1807 .. option:: -f[no-]associative-math
1808
1809 Allow floating point operations to be reassociated.
1810 Defaults to ``-fno-associative-math``.
1811
1812 .. option:: -f[no-]reciprocal-math
1813
1814 Allow division operations to be transformed into multiplication by a
1815 reciprocal. This can be significantly faster than an ordinary division
1816 but can also have significantly less precision. Defaults to
1817 ``-fno-reciprocal-math``.
1818
1819 .. option:: -f[no-]unsafe-math-optimizations
1820
1821 Allow unsafe floating-point optimizations.
1822 ``-funsafe-math-optimizations`` also implies:
1823
1824 * ``-fapprox-func``
1825 * ``-fassociative-math``
1826 * ``-freciprocal-math``
1827 * ``-fno-signed-zeros``
1828 * ``-fno-trapping-math``
1829 * ``-ffp-contract=fast``
1830
1831 ``-fno-unsafe-math-optimizations`` implies:
1832
1833 * ``-fno-approx-func``
1834 * ``-fno-associative-math``
1835 * ``-fno-reciprocal-math``
1836 * ``-fsigned-zeros``
1837 * ``-ffp-contract=on``
1838
1839 There is ambiguity about how ``-ffp-contract``,
1840 ``-funsafe-math-optimizations``, and ``-fno-unsafe-math-optimizations``
1841 behave when combined. Explanation in :option:`-fno-fast-math` also applies
1842 to these options.
1843
1844 Defaults to ``-fno-unsafe-math-optimizations``.
1845
1846 .. option:: -f[no-]finite-math-only
1847
1848 Allow floating-point optimizations that assume arguments and results are
1849 not NaNs or +-Inf. ``-ffinite-math-only`` defines the
1850 ``__FINITE_MATH_ONLY__`` preprocessor macro.
1851 ``-ffinite-math-only`` implies:
1852
1853 * ``-fno-honor-infinities``
1854 * ``-fno-honor-nans``
1855
1856 ``-ffno-inite-math-only`` implies:
1857
1858 * ``-fhonor-infinities``
1859 * ``-fhonor-nans``
1860
1861 Defaults to ``-fno-finite-math-only``.
1862
1863 .. option:: -f[no-]rounding-math
1864
1865 Force floating-point operations to honor the dynamically-set rounding mode by default.
1866
1867 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.
1868
1869 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``.
1870
1871 - The option ``-fno-rounding-math`` allows the compiler to assume that the rounding mode is set to ``FE_TONEAREST``. This is the default.
1872 - 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.
1873
1874 .. option:: -ffp-model=<value>
1875
1876 Specify floating point behavior. ``-ffp-model`` is an umbrella
1877 option that encompasses functionality provided by other, single
1878 purpose, floating point options. Valid values are: ``precise``, ``strict``,
1879 ``fast``, and ``aggressive``.
1880 Details:
1881
1882 * ``precise`` Disables optimizations that are not value-safe on
1883 floating-point data, although FP contraction (FMA) is enabled
1884 (``-ffp-contract=on``). This is the default behavior. This value resets
1885 ``-fmath-errno`` to its target-dependent default.
1886 * ``strict`` Enables ``-frounding-math`` and
1887 ``-ffp-exception-behavior=strict``, and disables contractions (FMA). All
1888 of the ``-ffast-math`` enablements are disabled. Enables
1889 ``STDC FENV_ACCESS``: by default ``FENV_ACCESS`` is disabled. This option
1890 setting behaves as though ``#pragma STDC FENV_ACCESS ON`` appeared at the
1891 top of the source file.
1892 * ``fast`` Behaves identically to specifying ``-funsafe-math-optimizations``,
1893 ``-fno-math-errno`` and ``-fcomplex-arithmetic=promoted``
1894 ``ffp-contract=fast``
1895 * ``aggressive`` Behaves identically to specifying both ``-ffast-math`` and
1896 ``ffp-contract=fast``
1897
1898 Note: If your command line specifies multiple instances
1899 of the ``-ffp-model`` option, or if your command line option specifies
1900 ``-ffp-model`` and later on the command line selects a floating point
1901 option that has the effect of negating part of the ``ffp-model`` that
1902 has been selected, then the compiler will issue a diagnostic warning
1903 that the override has occurred.
1904
1905 .. option:: -ffp-exception-behavior=<value>
1906
1907 Specify the floating-point exception behavior.
1908
1909 Valid values are: ``ignore``, ``maytrap``, and ``strict``.
1910 The default value is ``ignore``. Details:
1911
1912 * ``ignore`` The compiler assumes that the exception status flags will not be read and that floating point exceptions will be masked.
1913 * ``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.
1914 * ``strict`` The compiler ensures that all transformations strictly preserve the floating point exception semantics of the original code.
1915
1916 .. option:: -ffp-eval-method=<value>
1917
1918 Specify the floating-point evaluation method for intermediate results within
1919 a single expression of the code.
1920
1921 Valid values are: ``source``, ``double``, and ``extended``.
1922 For 64-bit targets, the default value is ``source``. For 32-bit x86 targets,
1923 however, in the case of NETBSD 6.99.26 and under, the default value is
1924 ``double``; in the case of NETBSD greater than 6.99.26, with NoSSE, the
1925 default value is ``extended``, with SSE the default value is ``source``.
1926 Details:
1927
1928 * ``source`` The compiler uses the floating-point type declared in the source program as the evaluation method.
1929 * ``double`` The compiler uses ``double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``double``.
1930 * ``extended`` The compiler uses ``long double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``long double``.
1931
1932 .. option:: -f[no-]protect-parens
1933
1934 This option pertains to floating-point types, complex types with
1935 floating-point components, and vectors of these types. Some arithmetic
1936 expression transformations that are mathematically correct and permissible
1937 according to the C and C++ language standards may be incorrect when dealing
1938 with floating-point types, such as reassociation and distribution. Further,
1939 the optimizer may ignore parentheses when computing arithmetic expressions
1940 in circumstances where the parenthesized and unparenthesized expression
1941 express the same mathematical value. For example (a+b)+c is the same
1942 mathematical value as a+(b+c), but the optimizer is free to evaluate the
1943 additions in any order regardless of the parentheses. When enabled, this
1944 option forces the optimizer to honor the order of operations with respect
1945 to parentheses in all circumstances.
1946 Defaults to ``-fno-protect-parens``.
1947
1948 Note that floating-point contraction (option `-ffp-contract=`) is disabled
1949 when `-fprotect-parens` is enabled. Also note that in safe floating-point
1950 modes, such as `-ffp-model=precise` or `-ffp-model=strict`, this option
1951 has no effect because the optimizer is prohibited from making unsafe
1952 transformations.
1953
1954 .. option:: -fexcess-precision:
1955
1956 The C and C++ standards allow floating-point expressions to be computed as if
1957 intermediate results had more precision (and/or a wider range) than the type
1958 of the expression strictly allows. This is called excess precision
1959 arithmetic.
1960 Excess precision arithmetic can improve the accuracy of results (although not
1961 always), and it can make computation significantly faster if the target lacks
1962 direct hardware support for arithmetic in a particular type. However, it can
1963 also undermine strict floating-point reproducibility.
1964
1965 Under the standards, assignments and explicit casts force the operand to be
1966 converted to its formal type, discarding any excess precision. Because data
1967 can only flow between statements via an assignment, this means that the use
1968 of excess precision arithmetic is a reliable local property of a single
1969 statement, and results do not change based on optimization. However, when
1970 excess precision arithmetic is in use, Clang does not guarantee strict
1971 reproducibility, and future compiler releases may recognize more
1972 opportunities to use excess precision arithmetic, e.g. with floating-point
1973 builtins.
1974
1975 Clang does not use excess precision arithmetic for most types or on most
1976 targets. For example, even on pre-SSE X86 targets where ``float`` and
1977 ``double`` computations must be performed in the 80-bit X87 format, Clang
1978 rounds all intermediate results correctly for their type. Clang currently
1979 uses excess precision arithmetic by default only for the following types and
1980 targets:
1981
1982 * ``_Float16`` on X86 targets without ``AVX512-FP16``.
1983
1984 The ``-fexcess-precision=<value>`` option can be used to control the use of
1985 excess precision arithmetic. Valid values are:
1986
1987 * ``standard`` - The default. Allow the use of excess precision arithmetic
1988 under the constraints of the C and C++ standards. Has no effect except on
1989 the types and targets listed above.
1990 * ``fast`` - Accepted for GCC compatibility, but currently treated as an
1991 alias for ``standard``.
1992 * ``16`` - Forces ``_Float16`` operations to be emitted without using excess
1993 precision arithmetic.
1994
1995 .. option:: -fcomplex-arithmetic=<value>:
1996
1997 This option specifies the implementation for complex multiplication and division.
1998
1999 Valid values are: ``basic``, ``improved``, ``full`` and ``promoted``.
2000
2001 * ``basic`` Implementation of complex division and multiplication using
2002 algebraic formulas at source precision. No special handling to avoid
2003 overflow. NaN and infinite values are not handled.
2004 * ``improved`` Implementation of complex division using the Smith algorithm
2005 at source precision. Smith's algorithm for complex division.
2006 See SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
2007 This value offers improved handling for overflow in intermediate
2008 calculations, but overflow may occur. NaN and infinite values are not
2009 handled in some cases.
2010 * ``full`` Implementation of complex division and multiplication using a
2011 call to runtime library functions (generally the case, but the BE might
2012 sometimes replace the library call if it knows enough about the potential
2013 range of the inputs). Overflow and non-finite values are handled by the
2014 library implementation. For the case of multiplication, overflow will occur in
2015 accordance with normal floating-point rules. This is the default value.
2016 * ``promoted`` Implementation of complex division using algebraic formulas at
2017 higher precision. Overflow is handled. Non-finite values are handled in some
2018 cases. If the target does not have native support for a higher-precision
2019 data type, the implementation for the complex operation using the Smith
2020 algorithm will be used. Overflow may still occur in some cases. NaN and
2021 infinite values are not handled.
2022
2023 .. option:: -fcx-limited-range:
2024
2025 This option is aliased to ``-fcomplex-arithmetic=basic``. It enables the
2026 naive mathematical formulas for complex division and multiplication with no
2027 NaN checking of results. The default is ``-fno-cx-limited-range`` aliased to
2028 ``-fcomplex-arithmetic=full``. This option is enabled by the ``-ffast-math``
2029 option.
2030
2031 .. option:: -fcx-fortran-rules:
2032
2033 This option is aliased to ``-fcomplex-arithmetic=improved``. It enables the
2034 naive mathematical formulas for complex multiplication and enables application
2035 of Smith's algorithm for complex division. See SMITH, R. L. Algorithm 116:
2036 Complex division. Commun. ACM 5, 8 (1962).
2037 The default is ``-fno-cx-fortran-rules`` aliased to
2038 ``-fcomplex-arithmetic=full``.
2039
2040 .. _floating-point-environment:
2041
2042 Accessing the floating point environment
2043 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2044 Many targets allow floating point operations to be configured to control things
2045 such as how inexact results should be rounded and how exceptional conditions
2046 should be handled. This configuration is called the floating point environment.
2047 C and C++ restrict access to the floating point environment by default, and the
2048 compiler is allowed to assume that all operations are performed in the default
2049 environment. When code is compiled in this default mode, operations that depend
2050 on the environment (such as floating-point arithmetic and `FLT_ROUNDS`) may have
2051 undefined behavior if the dynamic environment is not the default environment; for
2052 example, `FLT_ROUNDS` may or may not simply return its default value for the target
2053 instead of reading the dynamic environment, and floating-point operations may be
2054 optimized as if the dynamic environment were the default. Similarly, it is undefined
2055 behavior to change the floating point environment in this default mode, for example
2056 by calling the `fesetround` function.
2057 C provides two pragmas to allow code to dynamically modify the floating point environment:
2058
2059 - ``#pragma STDC FENV_ACCESS ON`` allows dynamic changes to the entire floating
2060 point environment.
2061
2062 - ``#pragma STDC FENV_ROUND FE_DYNAMIC`` allows dynamic changes to just the floating
2063 point rounding mode. This may be more optimizable than ``FENV_ACCESS ON`` because
2064 the compiler can still ignore the possibility of floating-point exceptions by default.
2065
2066 Both of these can be used either at the start of a block scope, in which case
2067 they cover all code in that scope (unless they're turned off in a child scope),
2068 or at the top level in a file, in which case they cover all subsequent function
2069 bodies until they're turned off. Note that it is undefined behavior to enter
2070 code that is *not* covered by one of these pragmas from code that *is* covered
2071 by one of these pragmas unless the floating point environment has been restored
2072 to its default state. See the C standard for more information about these pragmas.
2073
2074 The command line option ``-frounding-math`` behaves as if the translation unit
2075 began with ``#pragma STDC FENV_ROUND FE_DYNAMIC``. The command line option
2076 ``-ffp-model=strict`` behaves as if the translation unit began with ``#pragma STDC FENV_ACCESS ON``.
2077
2078 Code that just wants to use a specific rounding mode for specific floating point
2079 operations can avoid most of the hazards of the dynamic floating point environment
2080 by using ``#pragma STDC FENV_ROUND`` with a value other than ``FE_DYNAMIC``.
2081
2082 .. _crtfastmath.o:
2083
2084 A note about ``crtfastmath.o``
2085 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2086 ``-ffast-math`` and ``-funsafe-math-optimizations`` without the ``-shared``
2087 option cause ``crtfastmath.o`` to be
2088 automatically linked, which adds a static constructor that sets the FTZ/DAZ
2089 bits in MXCSR, affecting not only the current compilation unit but all static
2090 and shared libraries included in the program. This decision can be overridden
2091 by using either the flag ``-mdaz-ftz`` or ``-mno-daz-ftz`` to respectively
2092 link or not link ``crtfastmath.o``.
2093
2094 .. _FLT_EVAL_METHOD:
2095
2096 A note about ``__FLT_EVAL_METHOD__``
2097 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2098 The ``__FLT_EVAL_METHOD__`` is not defined as a traditional macro, and so it
2099 will not appear when dumping preprocessor macros. Instead, the value
2100 ``__FLT_EVAL_METHOD__`` expands to is determined at the point of expansion
2101 either from the value set by the ``-ffp-eval-method`` command line option or
2102 from the target. This is because the ``__FLT_EVAL_METHOD__`` macro
2103 cannot expand to the correct evaluation method in the presence of a ``#pragma``
2104 which alters the evaluation method. An error is issued if
2105 ``__FLT_EVAL_METHOD__`` is expanded inside a scope modified by
2106 ``#pragma clang fp eval_method``.
2107
2108 .. _fp-constant-eval:
2109
2110 A note about Floating Point Constant Evaluation
2111 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2112
2113 In C, the only place floating point operations are guaranteed to be evaluated
2114 during translation is in the initializers of variables of static storage
2115 duration, which are all notionally initialized before the program begins
2116 executing (and thus before a non-default floating point environment can be
2117 entered). But C++ has many more contexts where floating point constant
2118 evaluation occurs. Specifically: for static/thread-local variables,
2119 first try evaluating the initializer in a constant context, including in the
2120 constant floating point environment (just like in C), and then, if that fails,
2121 fall back to emitting runtime code to perform the initialization (which might
2122 in general be in a different floating point environment).
2123
2124 Consider this example when compiled with ``-frounding-math``
2125
2126 .. code-block:: console
2127
2128 constexpr float func_01(float x, float y) {
2129 return x + y;
2130 }
2131 float V1 = func_01(1.0F, 0x0.000001p0F);
2132
2133 The C++ rule is that initializers for static storage duration variables are
2134 first evaluated during translation (therefore, in the default rounding mode),
2135 and only evaluated at runtime (and therefore in the runtime rounding mode) if
2136 the compile-time evaluation fails. This is in line with the C rules;
2137 C11 F.8.5 says: *All computation for automatic initialization is done (as if)
2138 at execution time; thus, it is affected by any operative modes and raises
2139 floating-point exceptions as required by IEC 60559 (provided the state for the
2140 FENV_ACCESS pragma is ‘‘on’’). All computation for initialization of objects
2141 that have static or thread storage duration is done (as if) at translation
2142 time.* C++ generalizes this by adding another phase of initialization
2143 (at runtime) if the translation-time initialization fails, but the
2144 translation-time evaluation of the initializer of succeeds, it will be
2145 treated as a constant initializer.
2146
2147
2148 .. _controlling-code-generation:
2149
2150 Controlling Code Generation
2151 ---------------------------
2152
2153 Clang provides a number of ways to control code generation. The options
2154 are listed below.
2155
2156 .. option:: -f[no-]sanitize=check1,check2,...
2157
2158 Turn on runtime checks or mitigations for various forms of undefined or
2159 suspicious behavior. These are disabled by default.
2160
2161 The following options enable runtime checks for various forms of undefined
2162 or suspicious behavior:
2163
2164 - .. _opt_fsanitize_address:
2165
2166 ``-fsanitize=address``:
2167 :doc:`AddressSanitizer`, a memory error
2168 detector.
2169 - .. _opt_fsanitize_thread:
2170
2171 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
2172 - .. _opt_fsanitize_memory:
2173
2174 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
2175 a detector of uninitialized reads. Requires instrumentation of all
2176 program code.
2177 - .. _opt_fsanitize_undefined:
2178
2179 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
2180 a fast and compatible undefined behavior checker.
2181 - .. _opt_fsanitize_type:
2182
2183 ``-fsanitize=type``: :doc:`TypeSanitizer`, a detector for strict
2184 aliasing violations.
2185 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
2186 flow analysis.
2187 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
2188 checks. Requires ``-flto``.
2189 - ``-fsanitize=kcfi``: kernel indirect call forward-edge control flow
2190 integrity.
2191 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
2192 protection against stack-based memory corruption errors.
2193 - ``-fsanitize=realtime``: :doc:`RealtimeSanitizer`,
2194 a real-time safety checker.
2195
2196 The following options enable runtime mitigations for various forms of
2197 undefined or suspicious behavior:
2198
2199 - ``-fsanitize=alloc-token``: Enables :doc:`allocation tokens <AllocToken>`
2200 for allocator-level heap organization strategies, such as for security
2201 hardening. It passes type-derived token IDs to a compatible memory
2202 allocator. Requires linking against a token-aware allocator.
2203
2204 There are more fine-grained checks available: see
2205 the :ref:`list <ubsan-checks>` of specific kinds of
2206 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
2207 of control flow integrity schemes.
2208
2209 The ``-fsanitize=`` argument must also be provided when linking, in
2210 order to link to the appropriate runtime library.
2211
2212 It is not possible to combine more than one of the ``-fsanitize=address``,
2213 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
2214 program.
2215
2216 .. option:: -f[no-]sanitize-recover=check1,check2,...
2217
2218 .. option:: -f[no-]sanitize-recover[=all]
2219
2220 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
2221 If the check is fatal, program will halt after the first error
2222 of this kind is detected and error report is printed.
2223
2224 By default, non-fatal checks are those enabled by
2225 :doc:`UndefinedBehaviorSanitizer`,
2226 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
2227 sanitizers may not support recovery (or not support it by default
2228 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
2229 is detected.
2230
2231 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
2232 This means that if a check has been configured to trap elsewhere on the
2233 command line, or if the check traps by default, this flag will not have
2234 any effect unless that sanitizer's trapping behavior is disabled with
2235 ``-fno-sanitize-trap``.
2236
2237 For example, if a command line contains the flags ``-fsanitize=undefined
2238 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
2239 will have no effect on its own; it will need to be accompanied by
2240 ``-fno-sanitize-trap=alignment``.
2241
2242 .. option:: -f[no-]sanitize-trap=check1,check2,...
2243
2244 .. option:: -f[no-]sanitize-trap[=all]
2245
2246 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
2247 option is intended for use in cases where the sanitizer runtime cannot
2248 be used (for instance, when building libc or a kernel module), or where
2249 the binary size increase caused by the sanitizer runtime is a concern.
2250
2251 This flag is only compatible with :doc:`control flow integrity
2252 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
2253 checks other than ``vptr``.
2254
2255 This flag is enabled by default for sanitizers in the ``cfi`` group.
2256
2257 .. option:: -fsanitize-ignorelist=/path/to/ignorelist/file
2258
2259 Disable or modify sanitizer checks for objects (source files, functions,
2260 variables, types) listed in the file. See
2261 :doc:`SanitizerSpecialCaseList` for file format description.
2262
2263 .. option:: -fno-sanitize-ignorelist
2264
2265 Don't use ignorelist file, if it was specified earlier in the command line.
2266
2267 .. option:: -f[no-]sanitize-coverage=[type,features,...]
2268
2269 Enable simple code coverage in addition to certain sanitizers.
2270 See :doc:`SanitizerCoverage` for more details.
2271
2272 .. option:: -f[no-]sanitize-address-outline-instrumentation
2273
2274 Controls how address sanitizer code is generated. If enabled will always use
2275 a function call instead of inlining the code. Turning this option on could
2276 reduce the binary size, but might result in a worse run-time performance.
2277
2278 See :doc: `AddressSanitizer` for more details.
2279
2280 .. option:: -f[no-]sanitize-type-outline-instrumentation
2281
2282 Controls how type sanitizer code is generated. If enabled will always use
2283 a function call instead of inlining the code. Turning this option off may
2284 result in better run-time performance, but will increase binary size and
2285 compilation overhead.
2286
2287 See :doc: `TypeSanitizer` for more details.
2288
2289 .. option:: -f[no-]sanitize-stats
2290
2291 Enable simple statistics gathering for the enabled sanitizers.
2292 See :doc:`SanitizerStats` for more details.
2293
2294 .. option:: -fsanitize-undefined-trap-on-error
2295
2296 Deprecated alias for ``-fsanitize-trap=undefined``.
2297
2298 .. option:: -fsanitize-cfi-cross-dso
2299
2300 Enable cross-DSO control flow integrity checks. This flag modifies
2301 the behavior of sanitizers in the ``cfi`` group to allow checking
2302 of cross-DSO virtual and indirect calls.
2303
2304 .. option:: -fsanitize-cfi-icall-generalize-pointers
2305
2306 Generalize pointers in return and argument types in function type signatures
2307 checked by Control Flow Integrity indirect call checking. See
2308 :doc:`ControlFlowIntegrity` for more details.
2309
2310 .. option:: -fsanitize-cfi-icall-experimental-normalize-integers
2311
2312 Normalize integers in return and argument types in function type signatures
2313 checked by Control Flow Integrity indirect call checking. See
2314 :doc:`ControlFlowIntegrity` for more details.
2315
2316 This option is currently experimental.
2317
2318 .. option:: -fsanitize-kcfi-arity
2319
2320 Extends kernel indirect call forward-edge control flow integrity with
2321 additional function arity information (for supported targets). See
2322 :doc:`ControlFlowIntegrity` for more details.
2323
2324 .. option:: -fstrict-vtable-pointers
2325
2326 Enable optimizations based on the strict rules for overwriting polymorphic
2327 C++ objects, i.e. the vptr is invariant during an object's lifetime.
2328 This enables better devirtualization. Turned off by default, because it is
2329 still experimental.
2330
2331 .. option:: -fwhole-program-vtables
2332
2333 Enable whole-program vtable optimizations, such as single-implementation
2334 devirtualization and virtual constant propagation, for classes with
2335 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
2336
2337 .. option:: -f[no-]split-lto-unit
2338
2339 Controls splitting the :doc:`LTO unit <LTOVisibility>` into regular LTO and
2340 :doc:`ThinLTO` portions, when compiling with -flto=thin. Defaults to false
2341 unless ``-fsanitize=cfi`` or ``-fwhole-program-vtables`` are specified, in
2342 which case it defaults to true. Splitting is required with ``fsanitize=cfi``,
2343 and it is an error to disable via ``-fno-split-lto-unit``. Splitting is
2344 optional with ``-fwhole-program-vtables``, however, it enables more
2345 aggressive whole program vtable optimizations (specifically virtual constant
2346 propagation).
2347
2348 When enabled, vtable definitions and select virtual functions are placed
2349 in the split regular LTO module, enabling more aggressive whole program
2350 vtable optimizations required for CFI and virtual constant propagation.
2351 However, this can increase the LTO link time and memory requirements over
2352 pure ThinLTO, as all split regular LTO modules are merged and LTO linked
2353 with regular LTO.
2354
2355 .. option:: -fdevirtualize-speculatively
2356
2357 Enable speculative devirtualization optimization where a virtual call
2358 can be transformed into a direct call under the assumption that its
2359 object is of a particular type. A runtime check is inserted to validate
2360 the assumption before making the direct call, and if the check fails,
2361 the original virtual call is made instead. This optimization can enable
2362 more inlining opportunities and better optimization of the direct call.
2363 This is different from whole program devirtualization optimization
2364 that rely on global analysis and hidden visibility of the objects to prove
2365 that the object is always of a particular type at a virtual call site.
2366 This optimization doesn't require global analysis or hidden visibility.
2367 This optimization doesn't devirtualize all virtual calls, but only
2368 when there's a single implementation of the virtual function in the module.
2369 There could be a single implementation of the virtual function
2370 either because the function is not overridden in any derived class,
2371 or because all objects are instances of the same class/type.
2372
2373 Ex of IR before the optimization:
2374
2375 .. code-block:: llvm
2376
2377 %vtable = load ptr, ptr %BV, align 8, !tbaa !6
2378 %0 = tail call i1 @llvm.public.type.test(ptr %vtable, metadata !"_ZTS4Base")
2379 tail call void @llvm.assume(i1 %0)
2380 %0 = load ptr, ptr %vtable, align 8
2381 tail call void %0(ptr noundef nonnull align 8 dereferenceable(8) %BV)
2382 ret void
2383
2384 IR after the optimization:
2385
2386 .. code-block:: llvm
2387
2388 %vtable = load ptr, ptr %BV, align 8, !tbaa !12
2389 %0 = load ptr, ptr %vtable, align 8
2390 %1 = icmp eq ptr %0, @_ZN4Base17virtual_function1Ev
2391 br i1 %1, label %if.true.direct_targ, label %if.false.orig_indirect, !prof !15
2392 if.true.direct_targ: ; preds = %entry
2393 tail call void @_ZN4Base17virtual_function1Ev(ptr noundef nonnull align 8 dereferenceable(8) %BV)
2394 br label %if.end.icp
2395 if.false.orig_indirect: ; preds = %entry
2396 tail call void %0(ptr noundef nonnull align 8 dereferenceable(8) %BV)
2397 br label %if.end.icp
2398 if.end.icp: ; preds = %if.false.orig_indirect, %if.true.direct_targ
2399 ret void
2400
2401 This feature is temporarily ignored at the LLVM side when LTO is enabled.
2402 TODO: Update the comment when the LLVM side supports this feature for LTO.
2403 This feature is turned off by default.
2404
2405 .. option:: -f[no-]unique-source-file-names
2406
2407 When enabled, allows the compiler to assume that each object file
2408 passed to the linker has a unique identifier. The identifier for
2409 an object file is either the source file path or the value of the
2410 argument `-funique-source-file-identifier` if specified. This is
2411 useful for reducing link times when doing ThinLTO in combination with
2412 whole-program devirtualization or CFI.
2413
2414 The full source path or identifier passed to the compiler must be
2415 unique. This means that, for example, the following is a usage error:
2416
2417 .. code-block:: console
2418
2419 $ cd foo
2420 $ clang -funique-source-file-names -c foo.c
2421 $ cd ../bar
2422 $ clang -funique-source-file-names -c foo.c
2423 $ cd ..
2424 $ clang foo/foo.o bar/foo.o
2425
2426 but this is not:
2427
2428 .. code-block:: console
2429
2430 $ clang -funique-source-file-names -c foo/foo.c
2431 $ clang -funique-source-file-names -c bar/foo.c
2432 $ clang foo/foo.o bar/foo.o
2433
2434 A misuse of this flag may result in a duplicate symbol error at
2435 link time.
2436
2437 .. option:: -funique-source-file-identifier=IDENTIFIER
2438
2439 Used with `-funique-source-file-names` to specify a source file
2440 identifier.
2441
2442 .. option:: -fforce-emit-vtables
2443
2444 In order to improve devirtualization, forces emitting of vtables even in
2445 modules where it isn't necessary. It causes more inline virtual functions
2446 to be emitted.
2447
2448 .. option:: -fno-assume-sane-operator-new
2449
2450 Don't assume that the C++'s new operator is sane.
2451
2452 This option tells the compiler to do not assume that C++'s global
2453 new operator will always return a pointer that does not alias any
2454 other pointer when the function returns.
2455
2456 .. option:: -fassume-nothrow-exception-dtor
2457
2458 Assume that an exception object' destructor will not throw, and generate
2459 less code for catch handlers. A throw expression of a type with a
2460 potentially-throwing destructor will lead to an error.
2461
2462 By default, Clang assumes that the exception object may have a throwing
2463 destructor. For the Itanium C++ ABI, Clang generates a landing pad to
2464 destroy local variables and call ``_Unwind_Resume`` for the code
2465 ``catch (...) { ... }``. This option tells Clang that an exception object's
2466 destructor will not throw and code simplification is possible.
2467
2468 .. option:: -ftrap-function=[name]
2469
2470 Instruct code generator to emit a function call to the specified
2471 function name for ``__builtin_trap()``.
2472
2473 LLVM code generator translates ``__builtin_trap()`` to a trap
2474 instruction if it is supported by the target ISA. Otherwise, the
2475 builtin is translated into a call to ``abort``. If this option is
2476 set, then the code generator will always lower the builtin to a call
2477 to the specified function regardless of whether the target ISA has a
2478 trap instruction. This option is useful for environments (e.g.
2479 deeply embedded) where a trap cannot be properly handled, or when
2480 some custom behavior is desired.
2481
2482 .. option:: -ftls-model=[model]
2483
2484 Select which TLS model to use.
2485
2486 Valid values are: ``global-dynamic``, ``local-dynamic``,
2487 ``initial-exec`` and ``local-exec``. The default value is
2488 ``global-dynamic``. The compiler may use a different model if the
2489 selected model is not supported by the target, or if a more
2490 efficient model can be used. The TLS model can be overridden per
2491 variable using the ``tls_model`` attribute.
2492
2493 .. option:: -femulated-tls
2494
2495 Select emulated TLS model, which overrides all -ftls-model choices.
2496
2497 In emulated TLS mode, all access to TLS variables are converted to
2498 calls to __emutls_get_address in the runtime library.
2499
2500 .. option:: -mhwdiv=[values]
2501
2502 Select the ARM modes (arm or thumb) that support hardware division
2503 instructions.
2504
2505 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
2506 This option is used to indicate which mode (arm or thumb) supports
2507 hardware division instructions. This only applies to the ARM
2508 architecture.
2509
2510 .. option:: -m[no-]crc
2511
2512 Enable or disable CRC instructions.
2513
2514 This option is used to indicate whether CRC instructions are to
2515 be generated. This only applies to the ARM architecture.
2516
2517 CRC instructions are enabled by default on ARMv8.
2518
2519 .. option:: -mgeneral-regs-only
2520
2521 Generate code which only uses the general purpose registers.
2522
2523 This option restricts the generated code to use general registers
2524 only. This only applies to the AArch64 architecture.
2525
2526 .. option:: -mcompact-branches=[values]
2527
2528 Control the usage of compact branches for MIPSR6.
2529
2530 Valid values are: ``never``, ``optimal`` and ``always``.
2531 The default value is ``optimal`` which generates compact branches
2532 when a delay slot cannot be filled. ``never`` disables the usage of
2533 compact branches and ``always`` generates compact branches whenever
2534 possible.
2535
2536 .. option:: -f[no-]max-type-align=[number]
2537
2538 Instruct the code generator to not enforce a higher alignment than the given
2539 number (of bytes) when accessing memory via an opaque pointer or reference.
2540 This cap is ignored when directly accessing a variable or when the pointee
2541 type has an explicit “aligned” attribute.
2542
2543 The value should usually be determined by the properties of the system allocator.
2544 Some builtin types, especially vector types, have very high natural alignments;
2545 when working with values of those types, Clang usually wants to use instructions
2546 that take advantage of that alignment. However, many system allocators do
2547 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
2548 this option to limit the alignment that the compiler can assume for an arbitrary
2549 pointer, which may point onto the heap.
2550
2551 This option does not affect the ABI alignment of types; the layout of structs and
2552 unions and the value returned by the alignof operator remain the same.
2553
2554 This option can be overridden on a case-by-case basis by putting an explicit
2555 “aligned” alignment on a struct, union, or typedef. For example:
2556
2557 .. code-block:: console
2558
2559 #include <immintrin.h>
2560 // Make an aligned typedef of the AVX-512 16-int vector type.
2561 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
2562
2563 void initialize_vector(__aligned_v16si *v) {
2564 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
2565 // value of -fmax-type-align.
2566 }
2567
2568 .. option:: -faddrsig, -fno-addrsig
2569
2570 Controls whether Clang emits an address-significance table into the object
2571 file. Address-significance tables allow linkers to implement `safe ICF
2572 <https://research.google.com/pubs/archive/36912.pdf>`_ without the false
2573 positives that can result from other implementation techniques such as
2574 relocation scanning. Address-significance tables are enabled by default
2575 on ELF targets when using the integrated assembler. This flag currently
2576 only has an effect on ELF targets.
2577
2578 .. _funique_internal_linkage_names:
2579
2580 .. option:: -f[no-]unique-internal-linkage-names
2581
2582 Controls whether Clang emits a unique (best-effort) symbol name for internal
2583 linkage symbols. When this option is set, compiler hashes the main source
2584 file path from the command line and appends it to all internal symbols. If a
2585 program contains multiple objects compiled with the same command-line source
2586 file path, the symbols are not guaranteed to be unique. This option is
2587 particularly useful in attributing profile information to the correct
2588 function when multiple functions with the same private linkage name exist
2589 in the binary.
2590
2591 It should be noted that this option cannot guarantee uniqueness and the
2592 following is an example where it is not unique when two modules contain
2593 symbols with the same private linkage name:
2594
2595 .. code-block:: console
2596
2597 $ cd $P/foo && clang -c -funique-internal-linkage-names name_conflict.c
2598 $ cd $P/bar && clang -c -funique-internal-linkage-names name_conflict.c
2599 $ cd $P && clang foo/name_conflict.o && bar/name_conflict.o
2600
2601 .. option:: -f[no-]basic-block-address-map:
2602 Emits a ``SHT_LLVM_BB_ADDR_MAP`` section which includes address offsets for each
2603 basic block in the program, relative to the parent function address.
2604
2605
2606 .. option:: -fbasic-block-sections=[all, list=<arg>, none]
2607
2608 Controls how Clang emits text sections for basic blocks. With values ``all``
2609 and ``list=<arg>``, each basic block or a subset of basic blocks can be placed
2610 in its own unique section.
2611
2612 With the ``list=<arg>`` option, a file containing the subset of basic blocks
2613 that need to placed in unique sections can be specified. The format of the
2614 file is as follows. For example, ``list=spec.txt`` where ``spec.txt`` is the
2615 following:
2616
2617 ::
2618
2619 !foo
2620 !!2
2621 !_Z3barv
2622
2623 will place the machine basic block with ``id 2`` in function ``foo`` in a
2624 unique section. It will also place all basic blocks of functions ``bar``
2625 in unique sections.
2626
2627 Further, section clusters can also be specified using the ``list=<arg>``
2628 option. For example, ``list=spec.txt`` where ``spec.txt`` contains:
2629
2630 ::
2631
2632 !foo
2633 !!1 !!3 !!5
2634 !!2 !!4 !!6
2635
2636 will create two unique sections for function ``foo`` with the first
2637 containing the odd numbered basic blocks and the second containing the
2638 even numbered basic blocks.
2639
2640 Basic block sections allow the linker to reorder basic blocks and enables
2641 link-time optimizations like whole program inter-procedural basic block
2642 reordering.
2643
2644 .. option:: -fcodegen-data-generate[=<path>]
2645
2646 Emit the raw codegen (CG) data into custom sections in the object file.
2647 Currently, this option also combines the raw CG data from the object files
2648 into an indexed CG data file specified by the <path>, for LLD MachO only.
2649 When the <path> is not specified, `default.cgdata` is created.
2650 The CG data file combines all the outlining instances that occurred locally
2651 in each object file.
2652
2653 .. code-block:: console
2654
2655 $ clang -fuse-ld=lld -Oz -fcodegen-data-generate code.cc
2656
2657 For linkers that do not yet support this feature, `llvm-cgdata` can be used
2658 manually to merge this CG data in object files.
2659
2660 .. code-block:: console
2661
2662 $ clang -c -fuse-ld=lld -Oz -fcodegen-data-generate code.cc
2663 $ llvm-cgdata --merge -o default.cgdata code.o
2664
2665 .. option:: -fcodegen-data-use[=<path>]
2666
2667 Read the codegen data from the specified path to more effectively outline
2668 functions across compilation units. When the <path> is not specified,
2669 `default.cgdata` is used. This option can create many identically outlined
2670 functions that can be optimized by the conventional linker’s identical code
2671 folding (ICF).
2672
2673 .. code-block:: console
2674
2675 $ clang -fuse-ld=lld -Oz -Wl,--icf=safe -fcodegen-data-use code.cc
2676
2677 .. _strict_aliasing:
2678
2679 Strict Aliasing
2680 ---------------
2681
2682 The C and C++ standards require accesses to objects in memory to use l-values of
2683 an appropriate type for the object. This is called *strict aliasing* or
2684 *type-based alias analysis*. Strict aliasing enhances a variety of powerful
2685 memory optimizations, including reordering, combining, and eliminating memory
2686 accesses. These optimizations can lead to unexpected behavior in code that
2687 violates the strict aliasing rules. For example:
2688
2689 .. code-block:: c++
2690
2691 void advance(size_t *index, double *data) {
2692 double value = data[*index];
2693 /* Clang may assume that this store does not change the contents of `data`. */
2694 *index += 1;
2695 /* Clang may assume that this store does not change the contents of `index`. */
2696 data[*index] = value;
2697 /* Either of these facts may create significant optimization opportunities
2698 if Clang is able to inline this function. */
2699 }
2700
2701 Strict aliasing can be explicitly enabled with ``-fstrict-aliasing`` and
2702 disabled with ``-fno-strict-aliasing``. ``clang-cl`` defaults to
2703 ``-fno-strict-aliasing``. Otherwise, Clang defaults to ``-fstrict-aliasing``.
2704
2705 C and C++ specify slightly different rules for strict aliasing. To improve
2706 language interoperability, Clang allows two types to alias if either language
2707 would permit it. This includes applying the C++ similar types rule to C,
2708 allowing ``int **`` to alias ``int const * const *``. Clang also relaxes the
2709 standard aliasing rules in the following ways:
2710
2711 * All integer types of the same size are permitted to alias each other,
2712 including signed and unsigned types.
2713 * ``void*`` is permitted to alias any pointer type, ``void**`` is permitted to
2714 alias any pointer to pointer type, and so on.
2715
2716 Code which violates strict aliasing has undefined behavior. A program that
2717 works in one version of Clang may not work in another because of changes to the
2718 optimizer. Clang provides a :doc:`TypeSanitizer` to help detect
2719 violations of the strict aliasing rules, but it is currently still experimental.
2720 Code that is known to violate strict aliasing should generally be built with
2721 ``-fno-strict-aliasing`` if the violation cannot be fixed.
2722
2723 Clang supports several ways to fix a violation of strict aliasing:
2724
2725 * L-values of the character types ``char`` and ``unsigned char`` (as well as
2726 other types, depending on the standard) are permitted to access objects of
2727 any type.
2728
2729 * Library functions such as ``memcpy`` and ``memset`` are specified as treating
2730 memory as characters and therefore are not limited by strict aliasing. If a
2731 value of one type must be reinterpreted as another (e.g. to read the bits of a
2732 floating-point number), use ``memcpy`` to copy the representation to an object
2733 of the destination type. This has no overhead over a direct l-value access
2734 because Clang should reliably optimize calls to these functions to use simple
2735 loads and stores when they are used with small constant sizes.
2736
2737 * The attribute ``may_alias`` can be added to a ``typedef`` to give l-values of
2738 that type the same aliasing power as the character types.
2739
2740 Clang makes a best effort to avoid obvious miscompilations from strict aliasing
2741 by only considering type information when it cannot prove that two accesses must
2742 refer to the same memory. However, it is not recommended that programmers
2743 intentionally rely on this instead of using one of the solutions above because
2744 it is too easy for the compiler's analysis to be blocked in surprising ways.
2745
2746 In Clang 20, Clang strengthened its implementation of strict aliasing for
2747 accesses of pointer type. Previously, all accesses of pointer type were
2748 permitted to alias each other, but Clang now distinguishes different pointers
2749 by their pointee type, except as limited by the relaxations around qualifiers
2750 and ``void*`` described above. The previous behavior of treating all pointers as
2751 aliasing can be restored using ``-fno-pointer-tbaa``.
2752
2753 Profile Guided Optimization
2754 ---------------------------
2755
2756 Profile information enables better optimization. For example, knowing that a
2757 branch is taken very frequently helps the compiler make better decisions when
2758 ordering basic blocks. Knowing that a function ``foo`` is called more
2759 frequently than another function ``bar`` helps the inliner. Optimization
2760 levels ``-O2`` and above are recommended for use of profile guided optimization.
2761
2762 Clang supports profile guided optimization with two different kinds of
2763 profiling. A sampling profiler can generate a profile with very low runtime
2764 overhead, or you can build an instrumented version of the code that collects
2765 more detailed profile information. Both kinds of profiles can provide execution
2766 counts for instructions in the code and information on branches taken and
2767 function invocation.
2768
2769 Regardless of which kind of profiling you use, be careful to collect profiles
2770 by running your code with inputs that are representative of the typical
2771 behavior. Code that is not exercised in the profile will be optimized as if it
2772 is unimportant, and the compiler may make poor optimization choices for code
2773 that is disproportionately used while profiling.
2774
2775 Differences Between Sampling and Instrumentation
2776 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2777
2778 Although both techniques are used for similar purposes, there are important
2779 differences between the two:
2780
2781 1. Profile data generated with one cannot be used by the other, and there is no
2782 conversion tool that can convert one to the other. So, a profile generated
2783 via ``-fprofile-generate`` or ``-fprofile-instr-generate`` must be used with
2784 ``-fprofile-use`` or ``-fprofile-instr-use``. Similarly, sampling profiles
2785 generated by external profilers must be converted and used with ``-fprofile-sample-use``
2786 or ``-fauto-profile``.
2787
2788 2. Instrumentation profile data can be used for code coverage analysis and
2789 optimization.
2790
2791 3. Sampling profiles can only be used for optimization. They cannot be used for
2792 code coverage analysis. Although it would be technically possible to use
2793 sampling profiles for code coverage, sample-based profiles are too
2794 coarse-grained for code coverage purposes; it would yield poor results.
2795
2796 4. Sampling profiles must be generated by an external tool. The profile
2797 generated by that tool must then be converted into a format that can be read
2798 by LLVM. The section on sampling profilers describes one of the supported
2799 sampling profile formats.
2800
2801
2802 Using Sampling Profilers
2803 ^^^^^^^^^^^^^^^^^^^^^^^^
2804
2805 Sampling profilers are used to collect runtime information, such as
2806 hardware counters, while your application executes. They are typically
2807 very efficient and do not incur a large runtime overhead. The
2808 sample data collected by the profiler can be used during compilation
2809 to determine what the most executed areas of the code are.
2810
2811 Using the data from a sample profiler requires some changes in the way
2812 a program is built. Before the compiler can use profiling information,
2813 the code needs to execute under the profiler. The following is the
2814 usual build cycle when using sample profilers for optimization:
2815
2816 1. Build the code with source line table information. You can use all the
2817 usual build flags that you always build your application with. The only
2818 requirement is that DWARF debug info including source line information is
2819 generated. This DWARF information is important for the profiler to be able
2820 to map instructions back to source line locations. The usefulness of this
2821 DWARF information can be improved with the ``-fdebug-info-for-profiling``
2822 and ``-funique-internal-linkage-names`` options.
2823
2824 On Linux:
2825
2826 .. code-block:: console
2827
2828 $ clang++ -O2 -gline-tables-only \
2829 -fdebug-info-for-profiling -funique-internal-linkage-names \
2830 code.cc -o code
2831
2832 While MSVC-style targets default to CodeView debug information, DWARF debug
2833 information is required to generate source-level LLVM profiles. Use
2834 ``-gdwarf`` to include DWARF debug information:
2835
2836 .. code-block:: winbatch
2837
2838 > clang-cl /O2 -gdwarf -gline-tables-only ^
2839 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2840 code.cc /Fe:code -fuse-ld=lld /link /debug:dwarf
2841
2842 [OPTIONAL] Pseudo instrumentation can be used as the anchor for accurate
2843 profile mapping with the ``-fpseudo-probe-for-profiling`` option.
2844
2845 On Linux:
2846
2847 .. code-block:: console
2848
2849 $ clang++ -O2 -gline-tables-only \
2850 -fpseudo-probe-for-profiling -funique-internal-linkage-names \
2851 code.cc -o code
2852
2853 On Windows:
2854
2855 .. code-block:: winbatch
2856
2857 > clang-cl /O2 -gdwarf -gline-tables-only ^
2858 -fpseudo-probe-for-profiling /clang:-funique-internal-linkage-names ^
2859 code.cc /Fe:code -fuse-ld=lld /link /debug:dwarf
2860
2861 .. note::
2862
2863 :ref:`-funique-internal-linkage-names <funique_internal_linkage_names>`
2864 generates unique names based on given command-line source file paths. If
2865 your build system uses absolute source paths and these paths may change
2866 between steps 1 and 4, then the uniqued function names may change and result
2867 in unused profile data. Consider omitting this option in such cases.
2868
2869 2. Run the executable under a sampling profiler. The specific profiler
2870 you use does not really matter, as long as its output can be converted
2871 into the format that the LLVM optimizer understands.
2872
2873 Two such profilers are the Linux Perf profiler
2874 (https://perf.wiki.kernel.org/) and Intel's Sampling Enabling Product (SEP),
2875 available as part of `Intel VTune
2876 <https://software.intel.com/content/www/us/en/develop/tools/oneapi/components/vtune-profiler.html>`_.
2877 While Perf is Linux-specific, SEP can be used on Linux, Windows, and FreeBSD.
2878
2879 The LLVM tool ``llvm-profgen`` can convert output of either Perf or SEP. An
2880 external project, `AutoFDO <https://github.com/google/autofdo>`_, also
2881 provides a ``create_llvm_prof`` tool which supports Linux Perf output.
2882
2883 When using Perf:
2884
2885 .. code-block:: console
2886
2887 $ perf record -b -e BR_INST_RETIRED.NEAR_TAKEN:uppp ./code
2888
2889 If the event above is unavailable, ``branches:u`` is probably next-best.
2890
2891 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
2892 Record (LBR) to record call chains. While this is not strictly required,
2893 it provides better call information, which improves the accuracy of
2894 the profile data.
2895
2896 When using SEP:
2897
2898 .. code-block:: console
2899
2900 $ sep -start -out code.tb7 -ec BR_INST_RETIRED.NEAR_TAKEN:precise=yes:pdir -lbr no_filter:usr -perf-script brstack -app ./code
2901
2902 This produces a ``code.perf.data.script`` output which can be used with
2903 ``llvm-profgen``'s ``--perfscript`` input option.
2904
2905 3. Convert the collected profile data to LLVM's sample profile format. This is
2906 currently supported via the `AutoFDO <https://github.com/google/autofdo>`_
2907 converter ``create_llvm_prof``. Once built and installed, you can convert
2908 the ``perf.data`` file to LLVM using the command:
2909
2910 .. code-block:: console
2911
2912 $ create_llvm_prof --binary=./code --out=code.prof
2913
2914 This will read ``perf.data`` and the binary file ``./code`` and emit
2915 the profile data in ``code.prof``. Note that if you ran ``perf``
2916 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
2917 calling ``create_llvm_prof``.
2918
2919 Alternatively, the LLVM tool ``llvm-profgen`` can also be used to generate
2920 the LLVM sample profile:
2921
2922 .. code-block:: console
2923
2924 $ llvm-profgen --binary=./code --output=code.prof --perfdata=perf.data
2925
2926 Please note, ``perf.data`` must be collected with ``-b`` flag to Linux ``perf``
2927 for the above step to work.
2928
2929 When using SEP the output is in the textual format corresponding to
2930 ``llvm-profgen --perfscript``. For example:
2931
2932 .. code-block:: console
2933
2934 $ llvm-profgen --binary=./code --output=code.prof --perfscript=code.perf.data.script
2935
2936
2937 4. Build the code again using the collected profile. This step feeds
2938 the profile back to the optimizers. This should result in a binary
2939 that executes faster than the original one. Note that you are not
2940 required to build the code with the exact same arguments that you
2941 used in the first step. The only requirement is that you build the code
2942 with the same debug info options and ``-fprofile-sample-use``. ``-gdwarf``
2943 and ``-gline-tables-only`` can be omitted if you do not need debug info
2944 in the final binary.
2945
2946 On Linux:
2947
2948 .. code-block:: console
2949
2950 $ clang++ -O2 \
2951 -fdebug-info-for-profiling -funique-internal-linkage-names \
2952 -fprofile-sample-use=code.prof code.cc -o code
2953
2954 On Windows:
2955
2956 .. code-block:: winbatch
2957
2958 > clang-cl /O2 ^
2959 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2960 -fprofile-sample-use=code.prof code.cc /Fe:code
2961
2962 [OPTIONAL] Pseudo instrumentation can be used as the anchor for accurate
2963 profile mapping with the ``-fpseudo-probe-for-profiling`` option.
2964
2965 On Linux:
2966
2967 .. code-block:: console
2968
2969 $ clang++ -O2 \
2970 -fpseudo-probe-for-profiling -funique-internal-linkage-names \
2971 -fprofile-sample-use=code.prof code.cc -o code
2972
2973 On Windows:
2974
2975 .. code-block:: winbatch
2976
2977 > clang-cl /O2 ^
2978 -fpseudo-probe-for-profiling /clang:-funique-internal-linkage-names ^
2979 -fprofile-sample-use=code.prof code.cc /Fe:code
2980
2981 [OPTIONAL] Sampling-based profiles can have inaccuracies or missing block/
2982 edge counters. The profile inference algorithm (profi) can be used to infer
2983 missing blocks and edge counts, and improve the quality of profile data.
2984 Enable it with ``-fsample-profile-use-profi``. For example, on Linux:
2985
2986 .. code-block:: console
2987
2988 $ clang++ -fsample-profile-use-profi -O2 \
2989 -fdebug-info-for-profiling -funique-internal-linkage-names \
2990 -fprofile-sample-use=code.prof code.cc -o code
2991
2992 On Windows:
2993
2994 .. code-block:: winbatch
2995
2996 > clang-cl /clang:-fsample-profile-use-profi /O2 ^
2997 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2998 -fprofile-sample-use=code.prof code.cc /Fe:code
2999
3000 Sample Profile Formats
3001 """"""""""""""""""""""
3002
3003 Since external profilers generate profile data in a variety of custom formats,
3004 the data generated by the profiler must be converted into a format that can be
3005 read by the backend. LLVM supports three different sample profile formats:
3006
3007 1. ASCII text. This is the easiest one to generate. The file is divided into
3008 sections, which correspond to each of the functions with profile
3009 information. The format is described below. It can also be generated from
3010 the binary or gcov formats using the ``llvm-profdata`` tool.
3011
3012 2. Binary encoding. This uses a more efficient encoding that yields smaller
3013 profile files. This is the format generated by the ``create_llvm_prof`` tool
3014 in https://github.com/google/autofdo.
3015
3016 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
3017 is only interesting in environments where GCC and Clang co-exist. This
3018 encoding is only generated by the ``create_gcov`` tool in
3019 https://github.com/google/autofdo. It can be read by LLVM and
3020 ``llvm-profdata``, but it cannot be generated by either.
3021
3022 If you are using Linux Perf to generate sampling profiles, you can use the
3023 conversion tool ``create_llvm_prof`` described in the previous section.
3024 Otherwise, you will need to write a conversion tool that converts your
3025 profiler's native format into one of these three.
3026
3027
3028 Sample Profile Text Format
3029 """"""""""""""""""""""""""
3030
3031 This section describes the ASCII text format for sampling profiles. It is,
3032 arguably, the easiest one to generate. If you are interested in generating any
3033 of the other two, consult the ``ProfileData`` library in LLVM's source tree
3034 (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
3035
3036 .. code-block:: console
3037
3038 function1:total_samples:total_head_samples
3039 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
3040 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
3041 ...
3042 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
3043 offsetA[.discriminator]: fnA:num_of_total_samples
3044 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
3045 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
3046 offsetB[.discriminator]: fnB:num_of_total_samples
3047 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
3048
3049 This is a nested tree in which the indentation represents the nesting level
3050 of the inline stack. There are no blank lines in the file. And the spacing
3051 within a single line is fixed. Additional spaces will result in an error
3052 while reading the file.
3053
3054 Any line starting with the '#' character is completely ignored.
3055
3056 Inlined calls are represented with indentation. The Inline stack is a
3057 stack of source locations in which the top of the stack represents the
3058 leaf function, and the bottom of the stack represents the actual
3059 symbol to which the instruction belongs.
3060
3061 Function names must be mangled in order for the profile loader to
3062 match them in the current translation unit. The two numbers in the
3063 function header specify how many total samples were accumulated in the
3064 function (first number), and the total number of samples accumulated
3065 in the prologue of the function (second number). This head sample
3066 count provides an indicator of how frequently the function is invoked.
3067
3068 There are two types of lines in the function body.
3069
3070 - Sampled line represents the profile information of a source location.
3071 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
3072
3073 - Callsite line represents the profile information of an inlined callsite.
3074 ``offsetA[.discriminator]: fnA:num_of_total_samples``
3075
3076 Each sampled line may contain several items. Some are optional (marked
3077 below):
3078
3079 a. Source line offset. This number represents the line number
3080 in the function where the sample was collected. The line number is
3081 always relative to the line where symbol of the function is
3082 defined. So, if the function has its header at line 280, the offset
3083 13 is at line 293 in the file.
3084
3085 Note that this offset should never be a negative number. This could
3086 happen in cases like macros. The debug machinery will register the
3087 line number at the point of macro expansion. So, if the macro was
3088 expanded in a line before the start of the function, the profile
3089 converter should emit a 0 as the offset (this means that the optimizers
3090 will not be able to associate a meaningful weight to the instructions
3091 in the macro).
3092
3093 b. [OPTIONAL] Discriminator. This is used if the sampled program
3094 was compiled with DWARF discriminator support
3095 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
3096 DWARF discriminators are unsigned integer values that allow the
3097 compiler to distinguish between multiple execution paths on the
3098 same source line location.
3099
3100 For example, consider the line of code ``if (cond) foo(); else bar();``.
3101 If the predicate ``cond`` is true 80% of the time, then the edge
3102 into function ``foo`` should be considered to be taken most of the
3103 time. But both calls to ``foo`` and ``bar`` are at the same source
3104 line, so a sample count at that line is not sufficient. The
3105 compiler needs to know which part of that line is taken more
3106 frequently.
3107
3108 This is what discriminators provide. In this case, the calls to
3109 ``foo`` and ``bar`` will be at the same line, but will have
3110 different discriminator values. This allows the compiler to correctly
3111 set edge weights into ``foo`` and ``bar``.
3112
3113 c. Number of samples. This is an integer quantity representing the
3114 number of samples collected by the profiler at this source
3115 location.
3116
3117 d. [OPTIONAL] Potential call targets and samples. If present, this
3118 line contains a call instruction. This models both direct and
3119 number of samples. For example,
3120
3121 .. code-block:: console
3122
3123 130: 7 foo:3 bar:2 baz:7
3124
3125 The above means that at relative line offset 130 there is a call
3126 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
3127 with ``baz()`` being the relatively more frequently called target.
3128
3129 As an example, consider a program with the call chain ``main -> foo -> bar``.
3130 When built with optimizations enabled, the compiler may inline the
3131 calls to ``bar`` and ``foo`` inside ``main``. The generated profile
3132 could then be something like this:
3133
3134 .. code-block:: console
3135
3136 main:35504:0
3137 1: _Z3foov:35504
3138 2: _Z32bari:31977
3139 1.1: 31977
3140 2: 0
3141
3142 This profile indicates that there were a total of 35,504 samples
3143 collected in main. All of those were at line 1 (the call to ``foo``).
3144 Of those, 31,977 were spent inside the body of ``bar``. The last line
3145 of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
3146 samples were collected there.
3147
3148 .. _prof_instr:
3149
3150 Profiling with Instrumentation
3151 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3152
3153 Clang also supports profiling via instrumentation. This requires building a
3154 special instrumented version of the code and has some runtime
3155 overhead during the profiling, but it provides more detailed results than a
3156 sampling profiler. It also provides reproducible results, at least to the
3157 extent that the code behaves consistently across runs.
3158
3159 Clang supports two types of instrumentation: frontend-based and IR-based.
3160 Frontend-based instrumentation can be enabled with the option ``-fprofile-instr-generate``,
3161 and IR-based instrumentation can be enabled with the option ``-fprofile-generate``.
3162 For best performance with PGO, IR-based instrumentation should be used. It has
3163 the benefits of lower instrumentation overhead, smaller raw profile size, and
3164 better runtime performance. Frontend-based instrumentation, on the other hand,
3165 has better source correlation, so it should be used with source line-based
3166 coverage testing.
3167
3168 The flag ``-fcs-profile-generate`` also instruments programs using the same
3169 instrumentation method as ``-fprofile-generate``. However, it performs a
3170 post-inline late instrumentation and can produce context-sensitive profiles.
3171
3172
3173 Here are the steps for using profile guided optimization with
3174 instrumentation:
3175
3176 1. Build an instrumented version of the code by compiling and linking with the
3177 ``-fprofile-generate`` or ``-fprofile-instr-generate`` option.
3178
3179 .. code-block:: console
3180
3181 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
3182
3183 2. Run the instrumented executable with inputs that reflect the typical usage.
3184 By default, the profile data will be written to a ``default.profraw`` file
3185 in the current directory. You can override that default by using option
3186 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
3187 environment variable to specify an alternate file. If non-default file name
3188 is specified by both the environment variable and the command line option,
3189 the environment variable takes precedence. The file name pattern specified
3190 can include different modifiers: ``%p``, ``%h``, ``%m``, ``%b``, ``%t``, and
3191 ``%c``.
3192
3193 Any instance of ``%p`` in that file name will be replaced by the process
3194 ID, so that you can easily distinguish the profile output from multiple
3195 runs.
3196
3197 .. code-block:: console
3198
3199 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
3200
3201 The modifier ``%h`` can be used in scenarios where the same instrumented
3202 binary is run in multiple different host machines dumping profile data
3203 to a shared network based storage. The ``%h`` specifier will be substituted
3204 with the hostname so that profiles collected from different hosts do not
3205 clobber each other.
3206
3207 While the use of ``%p`` specifier can reduce the likelihood for the profiles
3208 dumped from different processes to clobber each other, such clobbering can still
3209 happen because of the ``pid`` re-use by the OS. Another side-effect of using
3210 ``%p`` is that the storage requirement for raw profile data files is greatly
3211 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
3212 name. When this specifier is used, the profiler runtime will substitute ``%m``
3213 with an integer identifier associated with the instrumented binary. Additionally,
3214 multiple raw profiles dumped from different processes that share a file system (can be
3215 on different hosts) will be automatically merged by the profiler runtime during the
3216 dumping. If the program links in multiple instrumented shared libraries, each library
3217 will dump the profile data into its own profile data file (with its integer
3218 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
3219 profile data generated by profiler runtime. The resulting merged "raw" profile data
3220 file still needs to be converted to a different format expected by the compiler (
3221 see step 3 below).
3222
3223 .. code-block:: console
3224
3225 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
3226
3227 Although rare, binary signatures used by the ``%m`` specifier can have
3228 collisions. In this case, the ``%b`` specifier, which expands to the binary
3229 ID (build ID in ELF and COFF), can be added. To use it, the program should be
3230 compiled with the build ID linker option (``--build-id`` for GNU ld or LLD,
3231 ``/build-id`` for lld-link on Windows). Linux, Windows and AIX are supported.
3232
3233 See `this <SourceBasedCodeCoverage.html#running-the-instrumented-program>`_ section
3234 about the ``%t``, and ``%c`` modifiers.
3235
3236 3. Combine profiles from multiple runs and convert the "raw" profile format to
3237 the input expected by clang. Use the ``merge`` command of the
3238 ``llvm-profdata`` tool to do this.
3239
3240 .. code-block:: console
3241
3242 $ llvm-profdata merge -output=code.profdata code-*.profraw
3243
3244 Note that this step is necessary even when there is only one "raw" profile,
3245 since the merge operation also changes the file format.
3246
3247 4. Build the code again using the ``-fprofile-use`` or ``-fprofile-instr-use``
3248 option to specify the collected profile data.
3249
3250 .. code-block:: console
3251
3252 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
3253
3254 You can repeat step 4 as often as you like without regenerating the
3255 profile. As you make changes to your code, clang may no longer be able to
3256 use the profile data. It will warn you when this happens.
3257
3258 Note that ``-fprofile-use`` option is semantically equivalent to
3259 its GCC counterpart, it *does not* handle profile formats produced by GCC.
3260 Both ``-fprofile-use`` and ``-fprofile-instr-use`` accept profiles in the
3261 indexed format, regardeless whether it is produced by frontend or the IR pass.
3262
3263 .. option:: -fprofile-generate[=<dirname>]
3264
3265 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
3266 an alternative instrumentation method for profile generation. When
3267 given a directory name, it generates the profile file
3268 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
3269 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
3270 will be substituted with a unique id documented in step 2 above. In other words,
3271 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
3272 merging is turned on by default, so there will no longer any risk of profile
3273 clobbering from different running processes. For example,
3274
3275 .. code-block:: console
3276
3277 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
3278
3279 When ``code`` is executed, the profile will be written to the file
3280 ``yyy/zzz/default_xxxx.profraw``.
3281
3282 To generate the profile data file with the compiler readable format, the
3283 ``llvm-profdata`` tool can be used with the profile directory as the input:
3284
3285 .. code-block:: console
3286
3287 $ llvm-profdata merge -output=code.profdata yyy/zzz/
3288
3289 If the user wants to turn off the auto-merging feature, or simply override the
3290 the profile dumping path specified at command line, the environment variable
3291 ``LLVM_PROFILE_FILE`` can still be used to override
3292 the directory and filename for the profile file at runtime.
3293 To override the path and filename at compile time, use
3294 ``-Xclang -fprofile-instrument-path=/path/to/file_pattern.profraw``.
3295
3296 .. option:: -fcs-profile-generate[=<dirname>]
3297
3298 The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use
3299 the same instrumentation method, and generate the same profile as in the
3300 ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is
3301 that the instrumentation is performed after inlining so that the resulted
3302 profile has a better context sensitive information. They cannot be used
3303 together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags.
3304 They are typically used in conjunction with ``-fprofile-use`` flag.
3305 The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate``
3306 can be merged by llvm-profdata. A use example:
3307
3308 .. code-block:: console
3309
3310 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
3311 $ ./code
3312 $ llvm-profdata merge -output=code.profdata yyy/zzz/
3313
3314 The first few steps are the same as that in ``-fprofile-generate``
3315 compilation. Then perform a second round of instrumentation.
3316
3317 .. code-block:: console
3318
3319 $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \
3320 -o cs_code
3321 $ ./cs_code
3322 $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata
3323
3324 The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile
3325 generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by
3326 ``-fprofile-use`` compilation.
3327
3328 .. code-block:: console
3329
3330 $ clang++ -O2 -fprofile-use=cs_code.profdata
3331
3332 The above command will read both profiles to the compiler at the identical
3333 point of instrumentations.
3334
3335 .. option:: -fprofile-use[=<pathname>]
3336
3337 Without any other arguments, ``-fprofile-use`` behaves identically to
3338 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
3339 profile file, it reads from that file. If ``pathname`` is a directory name,
3340 it reads from ``pathname/default.profdata``.
3341
3342 .. option:: -fprofile-update[=<method>]
3343
3344 Unless ``-fsanitize=thread`` is specified, the default is ``single``, which
3345 uses non-atomic increments. The counters can be inaccurate under thread
3346 contention. ``atomic`` uses atomic increments which is accurate but has
3347 overhead. ``prefer-atomic`` will be transformed to ``atomic`` when supported
3348 by the target, or ``single`` otherwise.
3349
3350 .. option:: -fprofile-continuous
3351
3352 Enables the continuous instrumentation profiling where profile counter updates
3353 are continuously synced to a file. This option sets any necessary modifiers
3354 (currently ``%c``) in the default profile filename and passes any necessary
3355 flags to the middle-end to support this mode. Value profiling is not supported
3356 in continuous mode.
3357
3358 .. code-block:: console
3359
3360 $ clang++ -O2 -fprofile-generate -fprofile-continuous code.cc -o code
3361
3362 Running ``./code`` will collect the profile and write it to the
3363 ``default_xxxx.profraw`` file. However, if ``./code`` abruptly terminates or
3364 does not call ``exit()``, in continuous mode the profile collected up to the
3365 point of termination will be available in ``default_xxxx.profraw`` while in
3366 the non-continuous mode, no profile file is generated.
3367
3368 .. option:: -ftemporal-profile
3369
3370 Enables the temporal profiling extension for IRPGO to improve startup time by
3371 reducing ``.text`` section page faults. To do this, we instrument function
3372 timestamps to measure when each function is called for the first time and use
3373 this data to generate a function order to improve startup.
3374
3375 The profile is generated as normal.
3376
3377 .. code-block:: console
3378
3379 $ clang++ -O2 -fprofile-generate -ftemporal-profile code.cc -o code
3380 $ ./code
3381 $ llvm-profdata merge -o code.profdata yyy/zzz
3382
3383 Using the resulting profile, we can generate a function order to pass to the
3384 linker via ``--symbol-ordering-file`` for ELF or ``-order_file`` for Mach-O.
3385
3386 .. code-block:: console
3387
3388 $ llvm-profdata order code.profdata -o code.orderfile
3389 $ clang++ -O2 -Wl,--symbol-ordering-file=code.orderfile code.cc -o code
3390
3391 Or the profile can be passed to LLD directly.
3392
3393 .. code-block:: console
3394
3395 $ clang++ -O2 -fuse-ld=lld -Wl,--irpgo-profile=code.profdata,--bp-startup-sort=function code.cc -o code
3396
3397 For more information, please read the RFC:
3398 https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/68068
3399
3400 Fine Tuning Profile Collection
3401 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3402
3403 The PGO infrastructure provides user program knobs to fine tune profile
3404 collection. Specifically, the PGO runtime provides the following functions
3405 that can be used to control the regions in the program where profiles should
3406 be collected.
3407
3408 * ``void __llvm_profile_set_filename(const char *Name)``: changes the name of
3409 the profile file to ``Name``.
3410 * ``void __llvm_profile_reset_counters(void)``: resets all counters to zero.
3411 * ``int __llvm_profile_dump(void)``: write the profile data to disk.
3412
3413 For example, the following pattern can be used to skip profiling program
3414 initialization, profile two specific hot regions, and skip profiling program
3415 cleanup:
3416
3417 .. code-block:: c
3418
3419 int main() {
3420 initialize();
3421
3422 // Reset all profile counters to 0 to omit profile collected during
3423 // initialize()'s execution.
3424 __llvm_profile_reset_counters();
3425 ... hot region 1
3426 // Dump the profile for hot region 1.
3427 __llvm_profile_set_filename("region1.profraw");
3428 __llvm_profile_dump();
3429
3430 // Reset counters before proceeding to hot region 2.
3431 __llvm_profile_reset_counters();
3432 ... hot region 2
3433 // Dump the profile for hot region 2.
3434 __llvm_profile_set_filename("region2.profraw");
3435 __llvm_profile_dump();
3436
3437 // Since the profile has been dumped, no further profile data
3438 // will be collected beyond the above __llvm_profile_dump().
3439 cleanup();
3440 return 0;
3441 }
3442
3443 These APIs' names can be introduced to user programs in two ways.
3444 They can be declared as weak symbols on platforms which support
3445 treating weak symbols as ``null`` during linking. For example, the user can
3446 have
3447
3448 .. code-block:: c
3449
3450 __attribute__((weak)) int __llvm_profile_dump(void);
3451
3452 // Then later in the same source file
3453 if (__llvm_profile_dump)
3454 if (__llvm_profile_dump() != 0) { ... }
3455 // The first if condition tests if the symbol is actually defined.
3456 // Profile dumping only happens if the symbol is defined. Hence,
3457 // the user program works correctly during normal (not profile-generate)
3458 // executions.
3459
3460 Alternatively, the user program can include the header
3461 ``profile/instr_prof_interface.h``, which contains the API names. For example,
3462
3463 .. code-block:: c
3464
3465 #include "profile/instr_prof_interface.h"
3466
3467 // Then later in the same source file
3468 if (__llvm_profile_dump() != 0) { ... }
3469
3470 The user code does not need to check if the API names are defined, because
3471 these names are automatically replaced by ``(0)`` or the equivalence of noop
3472 if the ``clang`` is not compiling for profile generation.
3473
3474 Such replacement can happen because ``clang`` adds one of two macros depending
3475 on the ``-fprofile-generate`` and the ``-fprofile-use`` flags.
3476
3477 * ``__LLVM_INSTR_PROFILE_GENERATE``: defined when one of
3478 ``-fprofile[-instr]-generate``/``-fcs-profile-generate`` is in effect.
3479 * ``__LLVM_INSTR_PROFILE_USE``: defined when one of
3480 ``-fprofile-use``/``-fprofile-instr-use`` is in effect.
3481
3482 The two macros can be used to provide more flexibility so a user program
3483 can execute code specifically intended for profile generate or profile use.
3484 For example, a user program can have special logging during profile generate:
3485
3486 .. code-block:: c
3487
3488 #if __LLVM_INSTR_PROFILE_GENERATE
3489 expensive_logging_of_full_program_state();
3490 #endif
3491
3492 The logging is automatically excluded during a normal build of the program,
3493 hence it does not impact performance during a normal execution.
3494
3495 It is advised to use such fine tuning only in a program's cold regions. The weak
3496 symbols can introduce extra control flow (the ``if`` checks), while the macros
3497 (hence declarations they guard in ``profile/instr_prof_interface.h``)
3498 can change the control flow of the functions that use them between profile
3499 generation and profile use (which can lead to discarded counters in such
3500 functions). Using these APIs in the program's cold regions introduces less
3501 overhead and leads to more optimized code.
3502
3503 Disabling Instrumentation
3504 ^^^^^^^^^^^^^^^^^^^^^^^^^
3505
3506 In certain situations, it may be useful to disable profile generation or use
3507 for specific files in a build, without affecting the main compilation flags
3508 used for the other files in the project.
3509
3510 In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
3511 ``-fno-profile-generate``) to disable profile generation, and
3512 ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
3513
3514 Note that these flags should appear after the corresponding profile
3515 flags to have an effect.
3516
3517 .. note::
3518
3519 When none of the translation units inside a binary is instrumented, in the
3520 case of Fuchsia the profile runtime will not be linked into the binary and
3521 no profile will be produced, while on other platforms the profile runtime
3522 will be linked and profile will be produced but there will not be any
3523 counters.
3524
3525 Instrumenting only selected files or functions
3526 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3527
3528 Sometimes it's useful to only instrument certain files or functions. For
3529 example in automated testing infrastructure, it may be desirable to only
3530 instrument files or functions that were modified by a patch to reduce the
3531 overhead of instrumenting a full system.
3532
3533 This can be done using the ``-fprofile-list`` option.
3534
3535 .. option:: -fprofile-list=<pathname>
3536
3537 This option can be used to apply profile instrumentation only to selected
3538 files or functions. ``pathname`` should point to a file in the
3539 :doc:`SanitizerSpecialCaseList` format which selects which files and
3540 functions to instrument.
3541
3542 .. code-block:: console
3543
3544 $ clang++ -O2 -fprofile-instr-generate -fprofile-list=fun.list code.cc -o code
3545
3546 The option can be specified multiple times to pass multiple files.
3547
3548 .. code-block:: console
3549
3550 $ clang++ -O2 -fprofile-instr-generate -fcoverage-mapping -fprofile-list=fun.list -fprofile-list=code.list code.cc -o code
3551
3552 Supported sections are ``[clang]``, ``[llvm]``, ``[csllvm]``, and ``[sample-coldcov]`` representing
3553 clang PGO, IRPGO, CSIRPGO and sample PGO based cold function coverage, respectively. Supported prefixes
3554 are ``function`` and ``source``. Supported categories are ``allow``, ``skip``, and ``forbid``.
3555 ``skip`` adds the ``skipprofile`` attribute while ``forbid`` adds the
3556 ``noprofile`` attribute to the appropriate function. Use
3557 ``default:<allow|skip|forbid>`` to specify the default category.
3558
3559 .. code-block:: console
3560
3561 $ cat fun.list
3562 # The following cases are for clang instrumentation.
3563 [clang]
3564
3565 # We might not want to profile functions that are inlined in many places.
3566 function:inlinedLots=skip
3567
3568 # We want to forbid profiling where it might be dangerous.
3569 source:lib/unsafe/*.cc=forbid
3570
3571 # Otherwise we allow profiling.
3572 default:allow
3573
3574 Older Prefixes
3575 """"""""""""""
3576 An older format is also supported, but it is only able to add the
3577 ``noprofile`` attribute.
3578 To filter individual functions or entire source files use ``fun:<name>`` or
3579 ``src:<file>`` respectively. To exclude a function or a source file, use
3580 ``!fun:<name>`` or ``!src:<file>`` respectively. The format also supports
3581 wildcard expansion. The compiler generated functions are assumed to be located
3582 in the main source file. It is also possible to restrict the filter to a
3583 particular instrumentation type by using a named section.
3584
3585 .. code-block:: none
3586
3587 # all functions whose name starts with foo will be instrumented.
3588 fun:foo*
3589
3590 # except for foo1 which will be excluded from instrumentation.
3591 !fun:foo1
3592
3593 # every function in path/to/foo.cc will be instrumented.
3594 src:path/to/foo.cc
3595
3596 # bar will be instrumented only when using backend instrumentation.
3597 # Recognized section names are clang, llvm and csllvm.
3598 [llvm]
3599 fun:bar
3600
3601 When the file contains only excludes, all files and functions except for the
3602 excluded ones will be instrumented. Otherwise, only the files and functions
3603 specified will be instrumented.
3604
3605 Instrument function groups
3606 ^^^^^^^^^^^^^^^^^^^^^^^^^^
3607
3608 Sometimes it is desirable to minimize the size overhead of instrumented
3609 binaries. One way to do this is to partition functions into groups and only
3610 instrument functions in a specified group. This can be done using the
3611 `-fprofile-function-groups` and `-fprofile-selected-function-group` options.
3612
3613 .. option:: -fprofile-function-groups=<N>, -fprofile-selected-function-group=<i>
3614
3615 The following uses 3 groups
3616
3617 .. code-block:: console
3618
3619 $ clang++ -Oz -fprofile-generate=group_0/ -fprofile-function-groups=3 -fprofile-selected-function-group=0 code.cc -o code.0
3620 $ clang++ -Oz -fprofile-generate=group_1/ -fprofile-function-groups=3 -fprofile-selected-function-group=1 code.cc -o code.1
3621 $ clang++ -Oz -fprofile-generate=group_2/ -fprofile-function-groups=3 -fprofile-selected-function-group=2 code.cc -o code.2
3622
3623 After collecting raw profiles from the three binaries, they can be merged into
3624 a single profile like normal.
3625
3626 .. code-block:: console
3627
3628 $ llvm-profdata merge -output=code.profdata group_*/*.profraw
3629
3630
3631 Profile remapping
3632 ^^^^^^^^^^^^^^^^^
3633
3634 When the program is compiled after a change that affects many symbol names,
3635 pre-existing profile data may no longer match the program. For example:
3636
3637 * switching from libstdc++ to libc++ will result in the mangled names of all
3638 functions taking standard library types to change
3639 * renaming a widely-used type in C++ will result in the mangled names of all
3640 functions that have parameters involving that type to change
3641 * moving from a 32-bit compilation to a 64-bit compilation may change the
3642 underlying type of ``size_t`` and similar types, resulting in changes to
3643 manglings
3644
3645 Clang allows use of a profile remapping file to specify that such differences
3646 in mangled names should be ignored when matching the profile data against the
3647 program.
3648
3649 .. option:: -fprofile-remapping-file=<file>
3650
3651 Specifies a file containing profile remapping information, that will be
3652 used to match mangled names in the profile data to mangled names in the
3653 program.
3654
3655 The profile remapping file is a text file containing lines of the form
3656
3657 .. code-block:: text
3658
3659 fragmentkind fragment1 fragment2
3660
3661 where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``,
3662 indicating whether the following mangled name fragments are
3663 <`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s,
3664 <`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or
3665 <`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s,
3666 respectively.
3667 Blank lines and lines starting with ``#`` are ignored.
3668
3669 For convenience, built-in <substitution>s such as ``St`` and ``Ss``
3670 are accepted as <name>s (even though they technically are not <name>s).
3671
3672 For example, to specify that ``absl::string_view`` and ``std::string_view``
3673 should be treated as equivalent when matching profile data, the following
3674 remapping file could be used:
3675
3676 .. code-block:: text
3677
3678 # absl::string_view is considered equivalent to std::string_view
3679 type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE
3680
3681 # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++
3682 name 3std St3__1
3683 name 3std St7__cxx11
3684
3685 Matching profile data using a profile remapping file is supported on a
3686 best-effort basis. For example, information regarding indirect call targets is
3687 currently not remapped. For best results, you are encouraged to generate new
3688 profile data matching the updated program, or to remap the profile data
3689 using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools.
3690
3691 .. note::
3692
3693 Profile data remapping is currently only supported for C++ mangled names
3694 following the Itanium C++ ABI mangling scheme. This covers all C++ targets
3695 supported by Clang other than Windows.
3696
3697 GCOV-based Profiling
3698 --------------------
3699
3700 GCOV is a test coverage program, it helps to know how often a line of code
3701 is executed. When instrumenting the code with ``--coverage`` option, some
3702 counters are added for each edge linking basic blocks.
3703
3704 At compile time, gcno files are generated containing information about
3705 blocks and edges between them. At runtime the counters are incremented and at
3706 exit the counters are dumped in gcda files.
3707
3708 The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate
3709 a report ``.c.gcov``.
3710
3711 .. option:: -fprofile-filter-files=[regexes]
3712
3713 Define a list of regexes separated by a semi-colon.
3714 If a file name matches any of the regexes then the file is instrumented.
3715
3716 .. code-block:: console
3717
3718 $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c
3719
3720 For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files.
3721
3722 .. option:: -fprofile-exclude-files=[regexes]
3723
3724 Define a list of regexes separated by a semi-colon.
3725 If a file name doesn't match all the regexes then the file is instrumented.
3726
3727 .. code-block:: console
3728
3729 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c
3730
3731 For example, this will instrument all the files except the ones in ``/usr/include``.
3732
3733 If both options are used then a file is instrumented if its name matches any
3734 of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes
3735 from ``-fprofile-exclude-list``.
3736
3737 .. code-block:: console
3738
3739 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \
3740 -fprofile-filter-files="^/usr/.*$"
3741
3742 In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and
3743 doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches
3744 the exclude regex.
3745
3746 Controlling Debug Information
3747 -----------------------------
3748
3749 Controlling Size of Debug Information
3750 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3751
3752 Debug info kind generated by Clang can be set by one of the flags listed
3753 below. If multiple flags are present, the last one is used.
3754
3755 .. option:: -g0
3756
3757 Don't generate any debug info (default).
3758
3759 .. option:: -gline-tables-only
3760
3761 Generate line number tables only.
3762
3763 This kind of debug info allows to obtain stack traces with function names,
3764 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
3765 doesn't contain any other data (e.g. description of local variables or
3766 function parameters).
3767
3768 .. option:: -fstandalone-debug
3769
3770 Clang supports a number of optimizations to reduce the size of debug
3771 information in the binary. They work based on the assumption that
3772 the debug type information can be spread out over multiple
3773 compilation units. Specifically, the optimizations are:
3774
3775 - will not emit type definitions for types that are not needed by a
3776 module and could be replaced with a forward declaration.
3777 - will only emit type info for a dynamic C++ class in the module that
3778 contains the vtable for the class.
3779 - will only emit type info for a C++ class (non-trivial, non-aggregate)
3780 in the modules that contain a definition for one of its constructors.
3781 - will only emit type definitions for types that are the subject of explicit
3782 template instantiation declarations in the presence of an explicit
3783 instantiation definition for the type.
3784
3785 The **-fstandalone-debug** option turns off these optimizations.
3786 This is useful when working with 3rd-party libraries that don't come
3787 with debug information. Note that Clang will never emit type
3788 information for types that are not referenced at all by the program.
3789
3790 .. option:: -fno-standalone-debug
3791
3792 On Darwin **-fstandalone-debug** is enabled by default. The
3793 **-fno-standalone-debug** option can be used to get to turn on the
3794 vtable-based optimization described above.
3795
3796 .. option:: -g
3797
3798 Generate complete debug info.
3799
3800 .. option:: -feliminate-unused-debug-types
3801
3802 By default, Clang does not emit type information for types that are defined
3803 but not used in a program. To retain the debug info for these unused types,
3804 the negation **-fno-eliminate-unused-debug-types** can be used.
3805 This can be particularly useful on Windows, when using NATVIS files that
3806 can reference const symbols that would otherwise be stripped, even in full
3807 debug or standalone debug modes.
3808
3809 Controlling Macro Debug Info Generation
3810 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3811
3812 Debug info for C preprocessor macros increases the size of debug information in
3813 the binary. Macro debug info generated by Clang can be controlled by the flags
3814 listed below.
3815
3816 .. option:: -fdebug-macro
3817
3818 Generate debug info for preprocessor macros. This flag is discarded when
3819 **-g0** is enabled.
3820
3821 .. option:: -fno-debug-macro
3822
3823 Do not generate debug info for preprocessor macros (default).
3824
3825 Controlling Debugger "Tuning"
3826 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3827
3828 While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
3829 different debuggers may know how to take advantage of different specific DWARF
3830 features. You can "tune" the debug info for one of several different debuggers.
3831
3832 .. option:: -ggdb, -glldb, -gsce, -gdbx
3833
3834 Tune the debug info for the ``gdb``, ``lldb``, Sony PlayStation\ |reg|
3835 debugger, or ``dbx``, respectively. Each of these options implies **-g**.
3836 (Therefore, if you want both **-gline-tables-only** and debugger tuning, the
3837 tuning option must come first.)
3838
3839 Controlling LLVM IR Output
3840 --------------------------
3841
3842 Controlling Value Names in LLVM IR
3843 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3844
3845 Emitting value names in LLVM IR increases the size and verbosity of the IR.
3846 By default, value names are only emitted in assertion-enabled builds of Clang.
3847 However, when reading IR it can be useful to re-enable the emission of value
3848 names to improve readability.
3849
3850 .. option:: -fdiscard-value-names
3851
3852 Discard value names when generating LLVM IR.
3853
3854 .. option:: -fno-discard-value-names
3855
3856 Do not discard value names when generating LLVM IR. This option can be used
3857 to re-enable names for release builds of Clang.
3858
3859
3860 Comment Parsing Options
3861 -----------------------
3862
3863 Clang parses Doxygen and non-Doxygen style documentation comments and attaches
3864 them to the appropriate declaration nodes. By default, it only parses
3865 Doxygen-style comments and ignores ordinary comments starting with ``//`` and
3866 ``/*``.
3867
3868 .. option:: -Wdocumentation
3869
3870 Emit warnings about use of documentation comments. This warning group is off
3871 by default.
3872
3873 This includes checking that ``\param`` commands name parameters that actually
3874 present in the function signature, checking that ``\returns`` is used only on
3875 functions that actually return a value etc.
3876
3877 .. option:: -Wno-documentation-unknown-command
3878
3879 Don't warn when encountering an unknown Doxygen command.
3880
3881 .. option:: -fparse-all-comments
3882
3883 Parse all comments as documentation comments (including ordinary comments
3884 starting with ``//`` and ``/*``).
3885
3886 .. option:: -fcomment-block-commands=[commands]
3887
3888 Define custom documentation commands as block commands. This allows Clang to
3889 construct the correct AST for these custom commands, and silences warnings
3890 about unknown commands. Several commands must be separated by a comma
3891 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
3892 custom commands ``\foo`` and ``\bar``.
3893
3894 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
3895 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
3896 as above.
3897
3898 .. _ccc-override-options:
3899
3900 CCC_OVERRIDE_OPTIONS
3901 --------------------
3902 The environment variable ``CCC_OVERRIDE_OPTIONS`` can be used to edit clang's
3903 command line arguments. The value of this variable is a space-separated list of
3904 edits to perform. The edits are applied in the order in which they appear in
3905 ``CCC_OVERRIDE_OPTIONS``. Each edit should be one of the following forms:
3906
3907 - ``#``: Silence information about the changes to the command line arguments.
3908
3909 - ``^FOO``: Add ``FOO`` as a new argument at the beginning of the command line
3910 right after the name of the compiler executable.
3911
3912 - ``+FOO``: Add ``FOO`` as a new argument at the end of the command line.
3913
3914 - ``s/XXX/YYY/``: Substitute the regular expression ``XXX`` with ``YYY`` in the
3915 command line.
3916
3917 - ``xOPTION``: Removes all instances of the literal argument ``OPTION``.
3918
3919 - ``XOPTION``: Removes all instances of the literal argument ``OPTION``, and the
3920 following argument.
3921
3922 - ``Ox``: Removes all flags matching ``O`` or ``O[sz0-9]`` and adds ``Ox`` at
3923 the end of the command line.
3924
3925 This environment variable does not affect the options added by the config files.
3926
3927 .. _c:
3928
3929 C Language Features
3930 ===================
3931
3932 The support for standard C in Clang is mostly feature-complete, see the `C
3933 status page <https://clang.llvm.org/c_status.html>`_ for more details.
3934
3935 Extensions supported by clang
3936 -----------------------------
3937
3938 See :doc:`LanguageExtensions`.
3939
3940 Differences between various standard modes
3941 ------------------------------------------
3942
3943 clang supports the ``-std`` option, which changes what language mode clang uses.
3944 The supported modes for C are c89, gnu89, c94, c99, gnu99, c11, gnu11, c17,
3945 gnu17, c23, gnu23, c2y, gnu2y, and various aliases for those modes. If no ``-std``
3946 option is specified, clang defaults to gnu17 mode. Many C99 and C11 features
3947 are supported in earlier modes as a conforming extension, with a warning. Use
3948 ``-pedantic-errors`` to request an error if a feature from a later standard
3949 revision is used in an earlier mode.
3950
3951 Differences between all ``c*`` and ``gnu*`` modes:
3952
3953 - ``c*`` modes define "``__STRICT_ANSI__``".
3954 - Target-specific defines not prefixed by underscores, like ``linux``,
3955 are defined in ``gnu*`` modes.
3956 - Trigraphs default to being off in ``gnu*`` modes; they can be enabled
3957 by the ``-trigraphs`` option.
3958 - The parser recognizes ``asm`` and ``typeof`` as keywords in ``gnu*`` modes;
3959 the variants ``__asm__`` and ``__typeof__`` are recognized in all modes.
3960 - The parser recognizes ``inline`` as a keyword in ``gnu*`` mode, in
3961 addition to recognizing it in the ``*99`` and later modes for which it is
3962 part of the ISO C standard. The variant ``__inline__`` is recognized in all
3963 modes.
3964 - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
3965 on some platforms; it can be enabled in any mode with the ``-fblocks``
3966 option.
3967
3968 Differences between ``*89`` and ``*94`` modes:
3969
3970 - Digraphs are not recognized in c89 mode.
3971
3972 Differences between ``*94`` and ``*99`` modes:
3973
3974 - The ``*99`` modes default to implementing ``inline`` / ``__inline__``
3975 as specified in C99, while the ``*89`` modes implement the GNU version.
3976 This can be overridden for individual functions with the ``__gnu_inline__``
3977 attribute.
3978 - The scope of names defined inside a ``for``, ``if``, ``switch``, ``while``,
3979 or ``do`` statement is different. (example: ``if ((struct x {int x;}*)0) {}``.)
3980 - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
3981 - ``inline`` is not recognized as a keyword in ``c89`` mode.
3982 - ``restrict`` is not recognized as a keyword in ``*89`` modes.
3983 - Commas are allowed in integer constant expressions in ``*99`` modes.
3984 - Arrays which are not lvalues are not implicitly promoted to pointers
3985 in ``*89`` modes.
3986 - Some warnings are different.
3987
3988 Differences between ``*99`` and ``*11`` modes:
3989
3990 - Warnings for use of C11 features are disabled.
3991 - ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
3992
3993 Differences between ``*11`` and ``*17`` modes:
3994
3995 - ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.
3996
3997 Differences between ``*17`` and ``*23`` modes:
3998
3999 - ``__STDC_VERSION__`` is defined to ``202311L`` rather than ``201710L``.
4000 - ``nullptr`` and ``nullptr_t`` are supported, only in ``*23`` mode.
4001 - ``ATOMIC_VAR_INIT`` is removed from ``*23`` mode.
4002 - ``bool``, ``true``, ``false``, ``alignas``, ``alignof``, ``static_assert``,
4003 and ``thread_local`` are now first-class keywords, only in ``*23`` mode.
4004 - ``typeof`` and ``typeof_unqual`` are supported, only ``*23`` mode.
4005 - Bit-precise integers (``_BitInt(N)``) are supported by default in ``*23``
4006 mode, and as an extension in ``*17`` and earlier modes.
4007 - ``[[]]`` attributes are supported by default in ``*23`` mode, and as an
4008 extension in ``*17`` and earlier modes.
4009
4010 Differences between ``*23`` and ``*2y`` modes:
4011
4012 - ``__STDC_VERSION__`` is defined to ``202400L`` rather than ``202311L``.
4013
4014 GCC extensions not implemented yet
4015 ----------------------------------
4016
4017 clang tries to be compatible with gcc as much as possible, but some gcc
4018 extensions are not implemented:
4019
4020 - clang does not support decimal floating point types (``_Decimal32`` and
4021 friends) yet.
4022 - clang only supports global register variables when the register specified
4023 is non-allocatable (e.g. the stack pointer). Support for general global
4024 register variables is unlikely to be implemented soon because it requires
4025 additional LLVM backend support.
4026 - clang does not support static initialization of flexible array
4027 members. This appears to be a rarely used extension, but could be
4028 implemented pending user demand.
4029 - clang does not support
4030 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
4031 used rarely, but in some potentially interesting places, like the
4032 glibc headers, so it may be implemented pending user demand. Note
4033 that because clang pretends to be like GCC 4.2, and this extension
4034 was introduced in 4.3, the glibc headers will not try to use this
4035 extension with clang at the moment.
4036
4037 This is not a complete list; if you find an unsupported extension
4038 missing from this list, please file a `feature request <https://github.com/llvm/llvm-project/issues/>`_.
4039 This list currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also,
4040 this list does not include bugs in mostly-implemented features; please see the
4041 `issues list <https://github.com/llvm/llvm-project/issues/>`_ for known existing
4042 bugs.
4043
4044 Intentionally unsupported GCC extensions
4045 ----------------------------------------
4046
4047 - clang does not support the gcc extension that allows variable-length
4048 arrays in structures. This is for a few reasons: one, it is tricky to
4049 implement, two, the extension is completely undocumented, and three,
4050 the extension appears to be rarely used. Note that clang *does*
4051 support flexible array members (arrays with a zero or unspecified
4052 size at the end of a structure).
4053 - GCC accepts many expression forms that are not valid integer constant
4054 expressions in bit-field widths, enumerator constants, case labels,
4055 and in array bounds at global scope. Clang also accepts additional
4056 expression forms in these contexts, but constructs that GCC accepts due to
4057 simplifications GCC performs while parsing, such as ``x - x`` (where ``x`` is a
4058 variable) will likely never be accepted by Clang.
4059 - clang does not support ``__builtin_apply`` and friends; this extension
4060 is extremely obscure and difficult to implement reliably.
4061 - clang does not support the gcc extension for forward-declaring
4062 function parameters.
4063 - clang does not support nested functions; this is a complex feature which is
4064 infrequently used, so it is unlikely to be implemented. In C++11 it can be
4065 emulated by assigning lambda functions to local variables, e.g:
4066
4067 .. code-block:: cpp
4068
4069 auto const local_function = [&](int parameter) {
4070 // Do something
4071 };
4072 ...
4073 local_function(1);
4074
4075
4076 .. _c_ms:
4077
4078 Microsoft extensions
4079 --------------------
4080
4081 clang has support for many extensions from Microsoft Visual C++. To enable these
4082 extensions, use the ``-fms-extensions`` command-line option. This is the default
4083 for Windows targets. Clang does not implement every pragma or declspec provided
4084 by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
4085 comment(lib)`` are well supported.
4086
4087 clang has a ``-fms-compatibility`` flag that makes clang accept enough
4088 invalid C++ to be able to parse most Microsoft headers. For example, it
4089 allows `unqualified lookup of dependent base class members
4090 <https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
4091 a common compatibility issue with clang. This flag is enabled by default
4092 for Windows targets.
4093
4094 ``-fdelayed-template-parsing`` lets clang delay parsing of function template
4095 definitions until the end of a translation unit. This flag is enabled by
4096 default for Windows targets.
4097
4098 For compatibility with existing code that compiles with MSVC, clang defines the
4099 ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. When on Windows, these default to
4100 either the same value as the currently installed version of cl.exe, or ``1933``
4101 and ``193300000`` (respectively). The ``-fms-compatibility-version=`` flag
4102 overrides these values. It accepts a dotted version tuple, such as 19.00.23506.
4103 Changing the MSVC compatibility version makes clang behave more like that
4104 version of MSVC. For example, ``-fms-compatibility-version=19`` will enable
4105 C++14 features and define ``char16_t`` and ``char32_t`` as builtin types.
4106
4107 .. _cxx:
4108
4109 C++ Language Features
4110 =====================
4111
4112 clang fully implements all of standard C++98 except for exported
4113 templates (which were removed in C++11), all of standard C++11,
4114 C++14, and C++17, and most of C++20 and C++23.
4115
4116 See the `C++ support in Clang <https://clang.llvm.org/cxx_status.html>`_ page
4117 for detailed information on C++ feature support across Clang versions.
4118
4119 Controlling implementation limits
4120 ---------------------------------
4121
4122 .. option:: -fbracket-depth=N
4123
4124 Sets the limit for nested parentheses, brackets, and braces to N. The
4125 default is 256.
4126
4127 .. option:: -fconstexpr-depth=N
4128
4129 Sets the limit for constexpr function invocations to N. The default is 512.
4130
4131 .. option:: -fconstexpr-steps=N
4132
4133 Sets the limit for the number of full-expressions evaluated in a single
4134 constant expression evaluation. This also controls the maximum size
4135 of array and dynamic array allocation that can be constant evaluated.
4136 The default is 1048576, and the limit can be disabled with `-fconstexpr-steps=0`.
4137
4138 .. option:: -ftemplate-depth=N
4139
4140 Sets the limit for recursively nested template instantiations to N. The
4141 default is 1024.
4142
4143 .. option:: -foperator-arrow-depth=N
4144
4145 Sets the limit for iterative calls to 'operator->' functions to N. The
4146 default is 256.
4147
4148 .. _objc:
4149
4150 Objective-C Language Features
4151 =============================
4152
4153 .. _objcxx:
4154
4155 Objective-C++ Language Features
4156 ===============================
4157
4158 .. _openmp:
4159
4160 OpenMP Features
4161 ===============
4162
4163 Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport`
4164 for additional details.
4165
4166 Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
4167 `-fno-openmp`.
4168
4169 Use `-fopenmp-simd` to enable OpenMP simd features only, without linking
4170 the runtime library; for combined constructs
4171 (e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses
4172 will be ignored. This can be disabled with `-fno-openmp-simd`.
4173
4174 Controlling implementation limits
4175 ---------------------------------
4176
4177 .. option:: -fopenmp-use-tls
4178
4179 Controls code generation for OpenMP threadprivate variables. In presence of
4180 this option all threadprivate variables are generated the same way as thread
4181 local variables, using TLS support. If `-fno-openmp-use-tls`
4182 is provided or target does not support TLS, code generation for threadprivate
4183 variables relies on OpenMP runtime library.
4184
4185 .. _opencl:
4186
4187 OpenCL Features
4188 ===============
4189
4190 Clang can be used to compile OpenCL kernels for execution on a device
4191 (e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMDGPU)
4192 that can be uploaded to run directly on a device (e.g. using
4193 `clCreateProgramWithBinary
4194 <https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
4195 into generic bitcode files loadable into other toolchains.
4196
4197 Compiling to a binary using the default target from the installation can be done
4198 as follows:
4199
4200 .. code-block:: console
4201
4202 $ echo "kernel void k(){}" > test.cl
4203 $ clang test.cl
4204
4205 Compiling for a specific target can be done by specifying the triple corresponding
4206 to the target, for example:
4207
4208 .. code-block:: console
4209
4210 $ clang --target=nvptx64-unknown-unknown test.cl
4211 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
4212
4213 Compiling to bitcode can be done as follows:
4214
4215 .. code-block:: console
4216
4217 $ clang -c -emit-llvm test.cl
4218
4219 This will produce a file `test.bc` that can be used in vendor toolchains
4220 to perform machine code generation.
4221
4222 Note that if compiled to bitcode for generic targets such as SPIR/SPIR-V,
4223 portable IR is produced that can be used with various vendor
4224 tools as well as open source tools such as `SPIRV-LLVM Translator
4225 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_
4226 to produce SPIR-V binary. More details are provided in `the offline
4227 compilation from OpenCL kernel sources into SPIR-V using open source
4228 tools
4229 <https://github.com/KhronosGroup/OpenCL-Guide/blob/main/chapters/os_tooling.md>`_.
4230 From clang 14 onwards SPIR-V can be generated directly as detailed in
4231 :ref:`the SPIR-V support section <spir-v>`.
4232
4233 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
4234 supports full profile. There is only very limited support of the embedded
4235 profile.
4236 From clang 9 a C++ mode is available for OpenCL (see
4237 :ref:`C++ for OpenCL <cxx_for_opencl>`).
4238
4239 OpenCL v3.0 support is complete but it remains in experimental state, see more
4240 details about the experimental features and limitations in :doc:`OpenCLSupport`
4241 page.
4242
4243 OpenCL Specific Options
4244 -----------------------
4245
4246 Most of the OpenCL build options from `the specification v2.0 section 5.8.4
4247 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
4248
4249 Examples:
4250
4251 .. code-block:: console
4252
4253 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
4254
4255
4256 Many flags used for the compilation for C sources can also be passed while
4257 compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
4258
4259 Some extra options are available to support special OpenCL features.
4260
4261 .. option:: -cl-no-stdinc
4262
4263 Allows to disable all extra types and functions that are not native to the compiler.
4264 This might reduce the compilation speed marginally but many declarations from the
4265 OpenCL standard will not be accessible. For example, the following will fail to
4266 compile.
4267
4268 .. code-block:: console
4269
4270 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
4271 $ clang -cl-std=CL2.0 -cl-no-stdinc test.cl
4272 error: use of undeclared identifier 'get_enqueued_local_size'
4273 error: use of undeclared identifier 'get_local_size'
4274
4275 More information about the standard types and functions is provided in :ref:`the
4276 section on the OpenCL Header <opencl_header>`.
4277
4278 .. _opencl_cl_ext:
4279
4280 .. option:: -cl-ext
4281
4282 Enables/Disables support of OpenCL extensions and optional features. All OpenCL
4283 targets set a list of extensions that they support. Clang allows to amend this using
4284 the ``-cl-ext`` flag with a comma-separated list of extensions prefixed with
4285 ``'+'`` or ``'-'``. The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where
4286 extensions can be either one of `the OpenCL published extensions
4287 <https://www.khronos.org/registry/OpenCL>`_
4288 or any vendor extension. Alternatively, ``'all'`` can be used to enable
4289 or disable all known extensions.
4290
4291 Example disabling double support for the 64-bit SPIR-V target:
4292
4293 .. code-block:: console
4294
4295 $ clang -c --target=spirv64 -cl-ext=-cl_khr_fp64 test.cl
4296
4297 Enabling all extensions except double support in R600 AMD GPU can be done using:
4298
4299 .. code-block:: console
4300
4301 $ clang --target=r600 -cl-ext=-all,+cl_khr_fp16 test.cl
4302
4303 Note that some generic targets e.g. SPIR/SPIR-V enable all extensions/features in
4304 clang by default.
4305
4306 OpenCL Targets
4307 --------------
4308
4309 OpenCL targets are derived from the regular Clang target classes. The OpenCL
4310 specific parts of the target representation provide address space mapping as
4311 well as a set of supported extensions.
4312
4313 Specific Targets
4314 ^^^^^^^^^^^^^^^^
4315
4316 There is a set of concrete HW architectures that OpenCL can be compiled for.
4317
4318 - For AMD target:
4319
4320 .. code-block:: console
4321
4322 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
4323
4324 - For Nvidia architectures:
4325
4326 .. code-block:: console
4327
4328 $ clang --target=nvptx64-unknown-unknown test.cl
4329
4330
4331 Generic Targets
4332 ^^^^^^^^^^^^^^^
4333
4334 - A SPIR-V binary can be produced for 32- or 64-bit targets.
4335
4336 .. code-block:: console
4337
4338 $ clang --target=spirv32 -c test.cl
4339 $ clang --target=spirv64 -c test.cl
4340
4341 More details can be found in :ref:`the SPIR-V support section <spir-v>`.
4342
4343 - SPIR is available as a generic target to allow portable bitcode to be produced
4344 that can be used across GPU toolchains. The implementation follows `the SPIR
4345 specification <https://www.khronos.org/spir>`_. There are two flavors
4346 available for 32 and 64 bits.
4347
4348 .. code-block:: console
4349
4350 $ clang --target=spir test.cl -emit-llvm -c
4351 $ clang --target=spir64 test.cl -emit-llvm -c
4352
4353 Clang will generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and
4354 SPIR v2.0 for OpenCL v2.0 or C++ for OpenCL.
4355
4356 - x86 is used by some implementations that are x86 compatible and currently
4357 remains for backwards compatibility (with older implementations prior to
4358 SPIR target support). For "non-SPMD" targets which cannot spawn multiple
4359 work-items on the fly using hardware, which covers practically all non-GPU
4360 devices such as CPUs and DSPs, additional processing is needed for the kernels
4361 to support multiple work-item execution. For this, a 3rd party toolchain,
4362 such as for example `POCL <http://portablecl.org/>`_, can be used.
4363
4364 This target does not support multiple memory segments and, therefore, the fake
4365 address space map can be added using the :ref:`-ffake-address-space-map
4366 <opencl_fake_address_space_map>` flag.
4367
4368 All known OpenCL extensions and features are set to supported in the generic targets,
4369 however :option:`-cl-ext` flag can be used to toggle individual extensions and
4370 features.
4371
4372 .. _opencl_header:
4373
4374 OpenCL Header
4375 -------------
4376
4377 By default Clang will include standard headers and therefore most of OpenCL
4378 builtin functions and types are available during compilation. The
4379 default declarations of non-native compiler types and functions can be disabled
4380 by using flag :option:`-cl-no-stdinc`.
4381
4382 The following example demonstrates that OpenCL kernel sources with various
4383 standard builtin functions can be compiled without the need for an explicit
4384 includes or compiler flags.
4385
4386 .. code-block:: console
4387
4388 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
4389 $ clang -cl-std=CL2.0 test.cl
4390
4391 More information about the default headers is provided in :doc:`OpenCLSupport`.
4392
4393 OpenCL Extensions
4394 -----------------
4395
4396 Most of the ``cl_khr_*`` extensions to OpenCL C from `the official OpenCL
4397 registry <https://www.khronos.org/registry/OpenCL/>`_ are available and
4398 configured per target depending on the support available in the specific
4399 architecture.
4400
4401 It is possible to alter the default extensions setting per target using
4402 ``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
4403
4404 Vendor extensions can be added flexibly by declaring the list of types and
4405 functions associated with each extensions enclosed within the following
4406 compiler pragma directives:
4407
4408 .. code-block:: c
4409
4410 #pragma OPENCL EXTENSION the_new_extension_name : begin
4411 // declare types and functions associated with the extension here
4412 #pragma OPENCL EXTENSION the_new_extension_name : end
4413
4414 For example, parsing the following code adds ``my_t`` type and ``my_func``
4415 function to the custom ``my_ext`` extension.
4416
4417 .. code-block:: c
4418
4419 #pragma OPENCL EXTENSION my_ext : begin
4420 typedef struct{
4421 int a;
4422 }my_t;
4423 void my_func(my_t);
4424 #pragma OPENCL EXTENSION my_ext : end
4425
4426 There is no conflict resolution for identifier clashes among extensions.
4427 It is therefore recommended that the identifiers are prefixed with a
4428 double underscore to avoid clashing with user space identifiers. Vendor
4429 extension should use reserved identifier prefix e.g. amd, arm, intel.
4430
4431 Clang also supports language extensions documented in `The OpenCL C Language
4432 Extensions Documentation
4433 <https://github.com/KhronosGroup/Khronosdotorg/blob/main/api/opencl/assets/OpenCL_LangExt.pdf>`_.
4434
4435 OpenCL-Specific Attributes
4436 --------------------------
4437
4438 OpenCL support in Clang contains a set of attribute taken directly from the
4439 specification as well as additional attributes.
4440
4441 See also :doc:`AttributeReference`.
4442
4443 nosvm
4444 ^^^^^
4445
4446 Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
4447 does not have any effect on the IR. For more details refer to the specification
4448 `section 6.7.2
4449 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
4450
4451
4452 opencl_unroll_hint
4453 ^^^^^^^^^^^^^^^^^^
4454
4455 The implementation of this feature mirrors the unroll hint for C.
4456 More details on the syntax can be found in the specification
4457 `section 6.11.5
4458 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
4459
4460 convergent
4461 ^^^^^^^^^^
4462
4463 To make sure no invalid optimizations occur for single program multiple data
4464 (SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
4465 can be used for special functions that have cross work item semantics.
4466 An example is the subgroup operations such as `intel_sub_group_shuffle
4467 <https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
4468
4469 .. code-block:: c
4470
4471 // Define custom my_sub_group_shuffle(data, c)
4472 // that makes use of intel_sub_group_shuffle
4473 r1 = ...
4474 if (r0) r1 = computeA();
4475 // Shuffle data from r1 into r3
4476 // of threads id r2.
4477 r3 = my_sub_group_shuffle(r1, r2);
4478 if (r0) r3 = computeB();
4479
4480 with non-SPMD semantics this is optimized to the following equivalent code:
4481
4482 .. code-block:: c
4483
4484 r1 = ...
4485 if (!r0)
4486 // Incorrect functionality! The data in r1
4487 // have not been computed by all threads yet.
4488 r3 = my_sub_group_shuffle(r1, r2);
4489 else {
4490 r1 = computeA();
4491 r3 = my_sub_group_shuffle(r1, r2);
4492 r3 = computeB();
4493 }
4494
4495 Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
4496 would prevent this:
4497
4498 .. code-block:: c
4499
4500 my_sub_group_shuffle() __attribute__((convergent));
4501
4502 Using ``convergent`` guarantees correct execution by keeping CFG equivalence
4503 wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
4504 node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
4505 respect to ``Ni`` remain the same in both ``G`` and ``G´``.
4506
4507 noduplicate
4508 ^^^^^^^^^^^
4509
4510 ``noduplicate`` is more restrictive with respect to optimizations than
4511 ``convergent`` because a convergent function only preserves CFG equivalence.
4512 This allows some optimizations to happen as long as the control flow remains
4513 unmodified.
4514
4515 .. code-block:: c
4516
4517 for (int i=0; i<4; i++)
4518 my_sub_group_shuffle()
4519
4520 can be modified to:
4521
4522 .. code-block:: c
4523
4524 my_sub_group_shuffle();
4525 my_sub_group_shuffle();
4526 my_sub_group_shuffle();
4527 my_sub_group_shuffle();
4528
4529 while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
4530 have the same safe semantics of CFG as ``convergent`` and can cause changes in
4531 CFG that modify semantics of the original program.
4532
4533 ``noduplicate`` is kept for backwards compatibility only and it considered to be
4534 deprecated for future uses.
4535
4536 .. _cxx_for_opencl:
4537
4538 C++ for OpenCL
4539 --------------
4540
4541 Starting from clang 9 kernel code can contain C++17 features: classes, templates,
4542 function overloading, type deduction, etc. Please note that this is not an
4543 implementation of `OpenCL C++
4544 <https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and
4545 there is no plan to support it in clang in any new releases in the near future.
4546
4547 Clang currently supports C++ for OpenCL 1.0 and 2021.
4548 For detailed information about this language refer to the C++ for OpenCL
4549 Programming Language Documentation available
4550 in `the latest build
4551 <https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html>`_
4552 or in `the official release
4553 <https://github.com/KhronosGroup/OpenCL-Docs/releases/tag/cxxforopencl-docrev2021.12>`_.
4554
4555 To enable the C++ for OpenCL mode, pass one of following command line options when
4556 compiling ``.clcpp`` file:
4557
4558 - C++ for OpenCL 1.0: ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-cl-std=clc++1.0``,
4559 ``-cl-std=CLC++1.0``, ``-std=clc++``, ``-std=CLC++``, ``-std=clc++1.0`` or
4560 ``-std=CLC++1.0``.
4561
4562 - C++ for OpenCL 2021: ``-cl-std=clc++2021``, ``-cl-std=CLC++2021``,
4563 ``-std=clc++2021``, ``-std=CLC++2021``.
4564
4565 Example of use:
4566 .. code-block:: c++
4567
4568 template<class T> T add( T x, T y )
4569 {
4570 return x + y;
4571 }
4572
4573 __kernel void test( __global float* a, __global float* b)
4574 {
4575 auto index = get_global_id(0);
4576 a[index] = add(b[index], b[index+1]);
4577 }
4578
4579
4580 .. code-block:: console
4581
4582 clang -cl-std=clc++1.0 test.clcpp
4583 clang -cl-std=clc++ -c --target=spirv64 test.cl
4584
4585
4586 By default, files with ``.clcpp`` extension are compiled with the C++ for
4587 OpenCL 1.0 mode.
4588
4589 .. code-block:: console
4590
4591 clang test.clcpp
4592
4593 For backward compatibility files with ``.cl`` extensions can also be compiled
4594 in C++ for OpenCL mode but the desirable language mode must be activated with
4595 a flag.
4596
4597 .. code-block:: console
4598
4599 clang -cl-std=clc++ test.cl
4600
4601 Support of C++ for OpenCL 2021 is currently in experimental phase, refer to
4602 :doc:`OpenCLSupport` for more details.
4603
4604 C++ for OpenCL kernel sources can also be compiled online in drivers supporting
4605 `cl_ext_cxx_for_opencl
4606 <https://www.khronos.org/registry/OpenCL/extensions/ext/cl_ext_cxx_for_opencl.html>`_
4607 extension.
4608
4609 Constructing and destroying global objects
4610 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4611
4612 Global objects with non-trivial constructors require the constructors to be run
4613 before the first kernel using the global objects is executed. Similarly global
4614 objects with non-trivial destructors require destructor invocation just after
4615 the last kernel using the program objects is executed.
4616 In OpenCL versions earlier than v2.2 there is no support for invoking global
4617 constructors. However, an easy workaround is to manually enqueue the
4618 constructor initialization kernel that has the following name scheme
4619 ``_GLOBAL__sub_I_<compiled file name>``.
4620 This kernel is only present if there are global objects with non-trivial
4621 constructors present in the compiled binary. One way to check this is by
4622 passing ``CL_PROGRAM_KERNEL_NAMES`` to ``clGetProgramInfo`` (OpenCL v2.0
4623 s5.8.7) and then checking whether any kernel name matches the naming scheme of
4624 global constructor initialization kernel above.
4625
4626 Note that if multiple files are compiled and linked into libraries, multiple
4627 kernels that initialize global objects for multiple modules would have to be
4628 invoked.
4629
4630 Applications are currently required to run initialization of global objects
4631 manually before running any kernels in which the objects are used.
4632
4633 .. code-block:: console
4634
4635 clang -cl-std=clc++ test.cl
4636
4637 If there are any global objects to be initialized, the final binary will
4638 contain the ``_GLOBAL__sub_I_test.cl`` kernel to be enqueued.
4639
4640 Note that the manual workaround only applies to objects declared at the
4641 program scope. There is no manual workaround for the construction of static
4642 objects with non-trivial constructors inside functions.
4643
4644 Global destructors can not be invoked manually in the OpenCL v2.0 drivers.
4645 However, all memory used for program scope objects should be released on
4646 ``clReleaseProgram``.
4647
4648 Libraries
4649 ^^^^^^^^^
4650 Limited experimental support of C++ standard libraries for OpenCL is
4651 described in :doc:`OpenCLSupport` page.
4652
4653 .. _target_features:
4654
4655 Target-Specific Features and Limitations
4656 ========================================
4657
4658 CPU Architectures Features and Limitations
4659 ------------------------------------------
4660
4661 X86
4662 ^^^
4663
4664 The support for X86 (both 32-bit and 64-bit) is considered stable on
4665 Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested
4666 to correctly compile many large C, C++, Objective-C, and Objective-C++
4667 codebases.
4668
4669 On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
4670 Microsoft x64 calling convention. You might need to tweak
4671 ``WinX86_64ABIInfo::classify()`` in ``lib/CodeGen/Targets/X86.cpp``.
4672
4673 For the X86 target, clang supports the `-m16` command line
4674 argument which enables 16-bit code output. This is broadly similar to
4675 using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
4676 and the ABI remains 32-bit but the assembler emits instructions
4677 appropriate for a CPU running in 16-bit mode, with address-size and
4678 operand-size prefixes to enable 32-bit addressing and operations.
4679
4680 Several micro-architecture levels as specified by the x86-64 psABI are defined.
4681 They are cumulative in the sense that features from previous levels are
4682 implicitly included in later levels.
4683
4684 - ``-march=x86-64``: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
4685 - ``-march=x86-64-v2``: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
4686 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
4687 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
4688
4689 `Intel AVX10 ISA <https://cdrdv2.intel.com/v1/dl/getContent/784343>`_ is
4690 a major new vector ISA incorporating the modern vectorization aspects of
4691 Intel AVX-512. This ISA will be supported on all future Intel processors.
4692 Users are supposed to use the new options ``-mavx10.N`` on these processors
4693 and should not use traditional AVX512 options anymore. The ``N`` in
4694 ``-mavx10.N`` represents a continuous integer number starting
4695 from ``1``. Current binaries built with AVX512 features can run on Intel AVX10
4696 capable processors without re-compile.
4697
4698 ARM
4699 ^^^
4700
4701 The support for ARM (specifically ARMv6 and ARMv7) is considered stable
4702 on Darwin (iOS): it has been tested to correctly compile many large C,
4703 C++, Objective-C, and Objective-C++ codebases. Clang only supports a
4704 limited number of ARM architectures. It does not yet fully support
4705 ARMv5, for example.
4706
4707 PowerPC
4708 ^^^^^^^
4709
4710 The support for PowerPC (especially PowerPC64) is considered stable
4711 on Linux and FreeBSD: it has been tested to correctly compile many
4712 large C and C++ codebases. PowerPC (32bit) is still missing certain
4713 features (e.g. PIC code on ELF platforms).
4714
4715 Other platforms
4716 ^^^^^^^^^^^^^^^
4717
4718 clang currently contains some support for other architectures (e.g. Sparc);
4719 however, significant pieces of code generation are still missing, and they
4720 haven't undergone significant testing.
4721
4722 clang contains limited support for the MSP430 embedded processor, but
4723 both the clang support and the LLVM backend support are highly
4724 experimental.
4725
4726 Other platforms are completely unsupported at the moment. Adding the
4727 minimal support needed for parsing and semantic analysis on a new
4728 platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
4729 tree. This level of support is also sufficient for conversion to LLVM IR
4730 for simple programs. Proper support for conversion to LLVM IR requires
4731 adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
4732 change soon, though. Generating assembly requires a suitable LLVM
4733 backend.
4734
4735 Operating System Features and Limitations
4736 -----------------------------------------
4737
4738 Windows
4739 ^^^^^^^
4740
4741 Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
4742 platforms.
4743
4744 See also :ref:`Microsoft Extensions <c_ms>`.
4745
4746 Cygwin
4747 """"""
4748
4749 Clang works on Cygwin-1.7.
4750
4751 MinGW32
4752 """""""
4753
4754 Clang works on some mingw32 distributions. Clang assumes directories as
4755 below;
4756
4757 - ``C:/mingw/include``
4758 - ``C:/mingw/lib``
4759 - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
4760
4761 On MSYS, a few tests might fail.
4762
4763 MinGW-w64
4764 """""""""
4765
4766 For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
4767 assumes as below;
4768
4769 - ``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)``
4770 - ``some_directory/bin/gcc.exe``
4771 - ``some_directory/bin/clang.exe``
4772 - ``some_directory/bin/clang++.exe``
4773 - ``some_directory/bin/../include/c++/GCC_version``
4774 - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
4775 - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
4776 - ``some_directory/bin/../include/c++/GCC_version/backward``
4777 - ``some_directory/bin/../x86_64-w64-mingw32/include``
4778 - ``some_directory/bin/../i686-w64-mingw32/include``
4779 - ``some_directory/bin/../include``
4780
4781 This directory layout is standard for any toolchain you will find on the
4782 official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
4783
4784 Clang expects the GCC executable "gcc.exe" compiled for
4785 ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
4786
4787 `Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
4788 ``x86_64-w64-mingw32``.
4789
4790 AIX
4791 ^^^
4792 TOC Data Transformation
4793 """""""""""""""""""""""
4794 TOC data transformation is off by default (``-mno-tocdata``).
4795 When ``-mtocdata`` is specified, the TOC data transformation will be applied to
4796 all suitable variables with static storage duration, including static data
4797 members of classes and block-scope static variables (if not marked as exceptions,
4798 see further below).
4799
4800 Suitable variables must:
4801
4802 - have complete types
4803 - be independently generated (i.e., not placed in a pool)
4804 - be at most as large as a pointer
4805 - not be aligned more strictly than a pointer
4806 - not be structs containing flexible array members
4807 - not have internal linkage
4808 - not have aliases
4809 - not have section attributes
4810 - not be thread local storage
4811
4812 The TOC data transformation results in the variable, not its address,
4813 being placed in the TOC. This eliminates the need to load the address of the
4814 variable from the TOC.
4815
4816 Note:
4817 If the TOC data transformation is applied to a variable whose definition
4818 is imported, the linker will generate fixup code for reading or writing to the
4819 variable.
4820
4821 When multiple toc-data options are used, the last option used has the affect.
4822 For example: ``-mno-tocdata=g5,g1 -mtocdata=g1,g2 -mno-tocdata=g2 -mtocdata=g3,g4``
4823 results in ``-mtocdata=g1,g3,g4``
4824
4825 Names of variables not having external linkage will be ignored.
4826
4827 **Options:**
4828
4829 .. option:: -mno-tocdata
4830
4831 This is the default behaviour. Only variables explicitly specified with
4832 ``-mtocdata=`` will have the TOC data transformation applied.
4833
4834 .. option:: -mtocdata
4835
4836 Apply the TOC data transformation to all suitable variables with static
4837 storage duration (including static data members of classes and block-scope
4838 static variables) that are not explicitly specified with ``-mno-tocdata=``.
4839
4840 .. option:: -mno-tocdata=
4841
4842 Can be used in conjunction with ``-mtocdata`` to mark the comma-separated
4843 list of external linkage variables, specified using their mangled names, as
4844 exceptions to ``-mtocdata``.
4845
4846 .. option:: -mtocdata=
4847
4848 Apply the TOC data transformation to the comma-separated list of external
4849 linkage variables, specified using their mangled names, if they are suitable.
4850 Emit diagnostics for all unsuitable variables specified.
4851
4852 Default Visibility Export Mapping
4853 """""""""""""""""""""""""""""""""
4854 The ``-mdefault-visibility-export-mapping=`` option can be used to control
4855 mapping of default visibility to an explicit shared object export
4856 (i.e. XCOFF exported visibility). Three values are provided for the option:
4857
4858 * ``-mdefault-visibility-export-mapping=none``: no additional export
4859 information is created for entities with default visibility.
4860 * ``-mdefault-visibility-export-mapping=explicit``: mark entities for export
4861 if they have explicit (e.g. via an attribute) default visibility from the
4862 source, including RTTI.
4863 * ``-mdefault-visibility-export-mapping=all``: set XCOFF exported visibility
4864 for all entities with default visibility from any source. This gives a
4865 export behavior similar to ELF platforms where all entities with default
4866 visibility are exported.
4867
4868 .. _spir-v:
4869
4870 SPIR-V support
4871 --------------
4872
4873 Clang supports generation of SPIR-V conformant to `the OpenCL Environment
4874 Specification
4875 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Env.html>`_.
4876
4877 To generate SPIR-V binaries, Clang uses the in-tree LLVM SPIR-V backend.
4878
4879 Example usage for OpenCL kernel compilation:
4880
4881 .. code-block:: console
4882
4883 $ clang --target=spirv32 -c test.cl
4884 $ clang --target=spirv64 -c test.cl
4885
4886 Both invocations of Clang will result in the generation of a SPIR-V binary file
4887 `test.o` for 32 bit and 64 bit respectively. This file can be imported
4888 by an OpenCL driver that support SPIR-V consumption or it can be compiled
4889 further by offline SPIR-V consumer tools.
4890
4891 Converting to SPIR-V produced with the optimization levels other than `-O0` is
4892 currently available as an experimental feature and it is not guaranteed to work
4893 in all cases.
4894
4895 Linking is done using ``spirv-link`` from `the SPIRV-Tools project
4896 <https://github.com/KhronosGroup/SPIRV-Tools#linker>`_. Similar to other external
4897 linkers, Clang will expect ``spirv-link`` to be installed separately and to be
4898 present in the ``PATH`` environment variable. Please refer to `the build and
4899 installation instructions
4900 <https://github.com/KhronosGroup/SPIRV-Tools#build>`_.
4901
4902 .. code-block:: console
4903
4904 $ clang --target=spirv64 test1.cl test2.cl
4905
4906 More information about the SPIR-V target settings and supported versions of SPIR-V
4907 format can be found in `the SPIR-V target guide
4908 <https://llvm.org/docs/SPIRVUsage.html>`__.
4909
4910 .. _clang-cl:
4911
4912 clang-cl
4913 ========
4914
4915 clang-cl is an alternative command-line interface to Clang, designed for
4916 compatibility with the Visual C++ compiler, cl.exe.
4917
4918 To enable clang-cl to find system headers, libraries, and the linker when run
4919 from the command-line, it should be executed inside a Visual Studio Native Tools
4920 Command Prompt or a regular Command Prompt where the environment has been set
4921 up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
4922
4923 clang-cl can also be used from inside Visual Studio by selecting the LLVM
4924 Platform Toolset. The toolset is not part of the installer, but may be installed
4925 separately from the
4926 `Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_.
4927 To use the toolset, select a project in Solution Explorer, open its Property
4928 Page (Alt+F7), and in the "General" section of "Configuration Properties"
4929 change "Platform Toolset" to LLVM. Doing so enables an additional Property
4930 Page for selecting the clang-cl executable to use for builds.
4931
4932 To use the toolset with MSBuild directly, invoke it with e.g.
4933 ``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain
4934 without modifying your project files.
4935
4936 It's also possible to point MSBuild at clang-cl without changing toolset by
4937 passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.
4938
4939 When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:
4940
4941 ::
4942
4943 cmake -G"Visual Studio 16 2019" -T LLVM ..
4944
4945 When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and
4946 ``CMAKE_CXX_COMPILER`` variables to clang-cl:
4947
4948 ::
4949
4950 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"
4951 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..
4952
4953
4954 Command-Line Options
4955 --------------------
4956
4957 To be compatible with cl.exe, clang-cl supports most of the same command-line
4958 options. Those options can start with either ``/`` or ``-``. It also supports
4959 some of Clang's core options, such as the ``-W`` options.
4960
4961 Options that are known to clang-cl, but not currently supported, are ignored
4962 with a warning. For example:
4963
4964 ::
4965
4966 clang-cl.exe: warning: argument unused during compilation: '/AI'
4967
4968 To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
4969
4970 Options that are not known to clang-cl will be ignored by default. Use the
4971 ``-Werror=unknown-argument`` option in order to treat them as errors. If these
4972 options are spelled with a leading ``/``, they will be mistaken for a filename:
4973
4974 ::
4975
4976 clang-cl.exe: error: no such file or directory: '/foobar'
4977
4978 Please `file a bug <https://github.com/llvm/llvm-project/issues/new?labels=clang-cl>`_
4979 for any valid cl.exe flags that clang-cl does not understand.
4980
4981 Execute ``clang-cl /?`` to see a list of supported options:
4982
4983 ::
4984
4985 CL.EXE COMPATIBILITY OPTIONS:
4986 /? Display available options
4987 /arch:<value> Set architecture for code generation
4988 /Brepro- Emit an object file which cannot be reproduced over time
4989 /Brepro Emit an object file which can be reproduced over time
4990 /clang:<arg> Pass <arg> to the clang driver
4991 /C Don't discard comments when preprocessing
4992 /c Compile only
4993 /d1PP Retain macro definitions in /E mode
4994 /d1reportAllClassLayout Dump record layout information
4995 /diagnostics:caret Enable caret and column diagnostics (on by default)
4996 /diagnostics:classic Disable column and caret diagnostics
4997 /diagnostics:column Disable caret diagnostics but keep column info
4998 /D <macro[=value]> Define macro
4999 /EH<value> Exception handling model
5000 /EP Disable linemarker output and preprocess to stdout
5001 /execution-charset:<value>
5002 Runtime encoding, supports only UTF-8
5003 /E Preprocess to stdout
5004 /FA Output assembly code file during compilation
5005 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
5006 /Fe<file or directory> Set output executable file or directory (ends in / or \)
5007 /FI <value> Include file before parsing
5008 /Fi<file> Set preprocess output file name (with /P)
5009 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
5010 /fp:except-
5011 /fp:except
5012 /fp:fast
5013 /fp:precise
5014 /fp:strict
5015 /Fp<filename> Set pch filename (with /Yc and /Yu)
5016 /GA Assume thread-local variables are defined in the executable
5017 /Gd Set __cdecl as a default calling convention
5018 /GF- Disable string pooling
5019 /GF Enable string pooling (default)
5020 /GR- Disable emission of RTTI data
5021 /Gregcall Set __regcall as a default calling convention
5022 /GR Enable emission of RTTI data
5023 /Gr Set __fastcall as a default calling convention
5024 /GS- Disable buffer security check
5025 /GS Enable buffer security check (default)
5026 /Gs Use stack probes (default)
5027 /Gs<value> Set stack probe size (default 4096)
5028 /guard:<value> Enable Control Flow Guard with /guard:cf,
5029 or only the table with /guard:cf,nochecks.
5030 Enable EH Continuation Guard with /guard:ehcont
5031 /Gv Set __vectorcall as a default calling convention
5032 /Gw- Don't put each data item in its own section
5033 /Gw Put each data item in its own section
5034 /GX- Disable exception handling
5035 /GX Enable exception handling
5036 /Gy- Don't put each function in its own section (default)
5037 /Gy Put each function in its own section
5038 /Gz Set __stdcall as a default calling convention
5039 /help Display available options
5040 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
5041 /I <dir> Add directory to include search path
5042 /J Make char type unsigned
5043 /LDd Create debug DLL
5044 /LD Create DLL
5045 /link <options> Forward options to the linker
5046 /MDd Use DLL debug run-time
5047 /MD Use DLL run-time
5048 /MTd Use static debug run-time
5049 /MT Use static run-time
5050 /O0 Disable optimization
5051 /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy)
5052 /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy)
5053 /Ob0 Disable function inlining
5054 /Ob1 Only inline functions which are (explicitly or implicitly) marked inline
5055 /Ob2 Inline functions as deemed beneficial by the compiler
5056 /Ob3 Same as /Ob2
5057 /Od Disable optimization
5058 /Og No effect
5059 /Oi- Disable use of builtin functions
5060 /Oi Enable use of builtin functions
5061 /Os Optimize for size (like clang -Os)
5062 /Ot Optimize for speed (like clang -O3)
5063 /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead
5064 /Oy- Disable frame pointer omission (x86 only, default)
5065 /Oy Enable frame pointer omission (x86 only)
5066 /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-'
5067 /o <file or directory> Set output file or directory (ends in / or \)
5068 /P Preprocess to file
5069 /Qvec- Disable the loop vectorization passes
5070 /Qvec Enable the loop vectorization passes
5071 /showFilenames- Don't print the name of each compiled file (default)
5072 /showFilenames Print the name of each compiled file
5073 /showIncludes Print info about included files to stderr
5074 /source-charset:<value> Source encoding, supports only UTF-8
5075 /std:<value> Language standard to compile for
5076 /TC Treat all source files as C
5077 /Tc <filename> Specify a C source file
5078 /TP Treat all source files as C++
5079 /Tp <filename> Specify a C++ source file
5080 /utf-8 Set source and runtime encoding to UTF-8 (default)
5081 /U <macro> Undefine macro
5082 /vd<value> Control vtordisp placement
5083 /vmb Use a best-case representation method for member pointers
5084 /vmg Use a most-general representation for member pointers
5085 /vmm Set the default most-general representation to multiple inheritance
5086 /vms Set the default most-general representation to single inheritance
5087 /vmv Set the default most-general representation to virtual inheritance
5088 /volatile:iso Volatile loads and stores have standard semantics
5089 /volatile:ms Volatile loads and stores have acquire and release semantics
5090 /W0 Disable all warnings
5091 /W1 Enable -Wall
5092 /W2 Enable -Wall
5093 /W3 Enable -Wall
5094 /W4 Enable -Wall and -Wextra
5095 /Wall Enable -Weverything
5096 /WX- Do not treat warnings as errors
5097 /WX Treat warnings as errors
5098 /w Disable all warnings
5099 /X Don't add %INCLUDE% to the include search path
5100 /Y- Disable precompiled headers, overrides /Yc and /Yu
5101 /Yc<filename> Generate a pch file for all code up to and including <filename>
5102 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
5103 /Z7 Enable CodeView debug information in object files
5104 /Zc:char8_t Enable C++20 char8_t type
5105 /Zc:char8_t- Disable C++20 char8_t type
5106 /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes
5107 /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default)
5108 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
5109 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
5110 /Zc:strictStrings Treat string literals as const
5111 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
5112 /Zc:threadSafeInit Enable thread-safe initialization of static variables
5113 /Zc:trigraphs- Disable trigraphs (default)
5114 /Zc:trigraphs Enable trigraphs
5115 /Zc:twoPhase- Disable two-phase name lookup in templates
5116 /Zc:twoPhase Enable two-phase name lookup in templates
5117 /Zi Alias for /Z7. Does not produce PDBs.
5118 /Zl Don't mention any default libraries in the object file
5119 /Zp Set the default maximum struct packing alignment to 1
5120 /Zp<value> Specify the default maximum struct packing alignment
5121 /Zs Run the preprocessor, parser and semantic analysis stages
5122
5123 OPTIONS:
5124 -### Print (but do not run) the commands to run for this compilation
5125 --analyze Run the static analyzer
5126 -faddrsig Emit an address-significance table
5127 -fansi-escape-codes Use ANSI escape codes for diagnostics
5128 -fblocks Enable the 'blocks' language feature
5129 -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none.
5130 -fcf-protection Enable cf-protection in 'full' mode
5131 -fcolor-diagnostics Use colors in diagnostics
5132 -fcomplete-member-pointers
5133 Require member pointer base types to be complete if they would be significant under the Microsoft ABI
5134 -fcoverage-mapping Generate coverage mapping to enable code coverage analysis
5135 -fcrash-diagnostics-dir=<dir>
5136 Put crash-report files in <dir>
5137 -fdebug-macro Emit macro debug information
5138 -fdelayed-template-parsing
5139 Parse templated function definitions at the end of the translation unit
5140 -fdiagnostics-absolute-paths
5141 Print absolute paths in diagnostics
5142 -fdiagnostics-parseable-fixits
5143 Print fix-its in machine parseable form
5144 -flto=<value> Set LTO mode to either 'full' or 'thin'
5145 -flto Enable LTO in 'full' mode
5146 -fmerge-all-constants Allow merging of constants
5147 -fmodule-file=<module_name>=<module-file>
5148 Use the specified module file that provides the module <module_name>
5149 -fmodule-header=<header>
5150 Build <header> as a C++20 header unit
5151 -fmodule-output=<path>
5152 Save intermediate module file results when compiling a standard C++ module unit.
5153 -fms-compatibility-version=<value>
5154 Dot-separated value representing the Microsoft compiler version
5155 number to report in _MSC_VER (0 = don't define it; default is same value as installed cl.exe, or 1933)
5156 -fms-compatibility Enable full Microsoft Visual C++ compatibility
5157 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
5158 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
5159 (0 = don't define it; default is same value as installed cl.exe, or 1933)
5160 -fno-addrsig Don't emit an address-significance table
5161 -fno-builtin-<value> Disable implicit builtin knowledge of a specific function
5162 -fno-builtin Disable implicit builtin knowledge of functions
5163 -fno-complete-member-pointers
5164 Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI
5165 -fno-coverage-mapping Disable code coverage analysis
5166 -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash
5167 -fno-debug-macro Do not emit macro debug information
5168 -fno-delayed-template-parsing
5169 Disable delayed template parsing
5170 -fno-sanitize-address-poison-custom-array-cookie
5171 Disable poisoning array cookies when using custom operator new[] in AddressSanitizer
5172 -fno-sanitize-address-use-after-scope
5173 Disable use-after-scope detection in AddressSanitizer
5174 -fno-sanitize-address-use-odr-indicator
5175 Disable ODR indicator globals
5176 -fno-sanitize-ignorelist Don't use ignorelist file for sanitizers
5177 -fno-sanitize-cfi-cross-dso
5178 Disable control flow integrity (CFI) checks for cross-DSO calls.
5179 -fno-sanitize-coverage=<value>
5180 Disable specified features of coverage instrumentation for Sanitizers
5181 -fno-sanitize-memory-track-origins
5182 Disable origins tracking in MemorySanitizer
5183 -fno-sanitize-memory-use-after-dtor
5184 Disable use-after-destroy detection in MemorySanitizer
5185 -fno-sanitize-recover=<value>
5186 Disable recovery for specified sanitizers
5187 -fno-sanitize-stats Disable sanitizer statistics gathering.
5188 -fno-sanitize-thread-atomics
5189 Disable atomic operations instrumentation in ThreadSanitizer
5190 -fno-sanitize-thread-func-entry-exit
5191 Disable function entry/exit instrumentation in ThreadSanitizer
5192 -fno-sanitize-thread-memory-access
5193 Disable memory access instrumentation in ThreadSanitizer
5194 -fno-sanitize-trap=<value>
5195 Disable trapping for specified sanitizers
5196 -fno-standalone-debug Limit debug information produced to reduce size of debug binary
5197 -fno-strict-aliasing Disable optimizations based on strict aliasing rules (default)
5198 -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version
5199 -fprofile-exclude-files=<value>
5200 Instrument only functions from files where names don't match all the regexes separated by a semi-colon
5201 -fprofile-filter-files=<value>
5202 Instrument only functions from files where names match any regex separated by a semi-colon
5203 -fprofile-generate=<dirname>
5204 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
5205 (overridden by ``LLVM_PROFILE_FILE`` env var)
5206 -fprofile-generate
5207 Generate instrumented code to collect execution counts into default_%m.profraw file
5208 (overridden by '=' form of option or ``LLVM_PROFILE_FILE`` env var)
5209 -fprofile-instr-generate=<file_name_pattern>
5210 Generate instrumented code to collect execution counts into the file whose name pattern is specified as the argument
5211 (overridden by ``LLVM_PROFILE_FILE`` env var)
5212 -fprofile-instr-generate
5213 Generate instrumented code to collect execution counts into default.profraw file
5214 (overridden by '=' form of option or ``LLVM_PROFILE_FILE`` env var)
5215 -fprofile-instr-use=<value>
5216 Use instrumentation data for coverage testing or profile-guided optimization
5217 -fprofile-use=<value>
5218 Use instrumentation data for profile-guided optimization
5219 -fprofile-remapping-file=<file>
5220 Use the remappings described in <file> to match the profile data against names in the program
5221 -fprofile-list=<file>
5222 Filename defining the list of functions/files to instrument
5223 -fsanitize-address-field-padding=<value>
5224 Level of field padding for AddressSanitizer
5225 -fsanitize-address-globals-dead-stripping
5226 Enable linker dead stripping of globals in AddressSanitizer
5227 -fsanitize-address-poison-custom-array-cookie
5228 Enable poisoning array cookies when using custom operator new[] in AddressSanitizer
5229 -fsanitize-address-use-after-return=<mode>
5230 Select the mode of detecting stack use-after-return in AddressSanitizer: never | runtime (default) | always
5231 -fsanitize-address-use-after-scope
5232 Enable use-after-scope detection in AddressSanitizer
5233 -fsanitize-address-use-odr-indicator
5234 Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size
5235 -fsanitize-ignorelist=<value>
5236 Path to ignorelist file for sanitizers
5237 -fsanitize-cfi-cross-dso
5238 Enable control flow integrity (CFI) checks for cross-DSO calls.
5239 -fsanitize-cfi-icall-generalize-pointers
5240 Generalize pointers in CFI indirect call type signature checks
5241 -fsanitize-coverage=<value>
5242 Specify the type of coverage instrumentation for Sanitizers
5243 -fsanitize-hwaddress-abi=<value>
5244 Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor)
5245 -fsanitize-memory-track-origins=<value>
5246 Enable origins tracking in MemorySanitizer
5247 -fsanitize-memory-track-origins
5248 Enable origins tracking in MemorySanitizer
5249 -fsanitize-memory-use-after-dtor
5250 Enable use-after-destroy detection in MemorySanitizer
5251 -fsanitize-recover=<value>
5252 Enable recovery for specified sanitizers
5253 -fsanitize-stats Enable sanitizer statistics gathering.
5254 -fsanitize-thread-atomics
5255 Enable atomic operations instrumentation in ThreadSanitizer (default)
5256 -fsanitize-thread-func-entry-exit
5257 Enable function entry/exit instrumentation in ThreadSanitizer (default)
5258 -fsanitize-thread-memory-access
5259 Enable memory access instrumentation in ThreadSanitizer (default)
5260 -fsanitize-trap=<value> Enable trapping for specified sanitizers
5261 -fsanitize-undefined-strip-path-components=<number>
5262 Strip (or keep only, if negative) a given number of path components when emitting check metadata.
5263 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
5264 behavior. See user manual for available checks
5265 -fsplit-lto-unit Enables splitting of the LTO unit.
5266 -fstandalone-debug Emit full debug info for all types used by the program
5267 -fstrict-aliasing Enable optimizations based on strict aliasing rules
5268 -fsyntax-only Run the preprocessor, parser and semantic analysis stages
5269 -fdevirtualize-speculatively
5270 Enables speculative devirtualization optimization.
5271 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
5272 -gcodeview-ghash Emit type record hashes in a .debug$H section
5273 -gcodeview Generate CodeView debug information
5274 -gline-directives-only Emit debug line info directives only
5275 -gline-tables-only Emit debug line number tables only
5276 -miamcu Use Intel MCU ABI
5277 -mllvm <value> Additional arguments to forward to LLVM's option processing
5278 -nobuiltininc Disable builtin #include directories
5279 -Qunused-arguments Don't emit warning for unused driver arguments
5280 -R<remark> Enable the specified remark
5281 --target=<value> Generate code for the given target
5282 --version Print version information
5283 -v Show commands to run and use verbose output
5284 -W<warning> Enable the specified warning
5285 -Xclang <arg> Pass <arg> to the clang compiler
5286 -Xclangas <arg> Pass <arg> to the clang assembler
5287
5288 The /clang: Option
5289 ^^^^^^^^^^^^^^^^^^
5290
5291 When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all
5292 of the ``<arg>`` arguments and process them as if they were passed to the clang
5293 driver. This mechanism allows you to pass flags that are not exposed in the
5294 clang-cl options or flags that have a different meaning when passed to the clang
5295 driver. Regardless of where they appear in the command line, the ``/clang:``
5296 arguments are treated as if they were passed at the end of the clang-cl command
5297 line.
5298
5299 The /Zc:dllexportInlines- Option
5300 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5301
5302 This causes the class-level `dllexport` and `dllimport` attributes to not apply
5303 to inline member functions, as they otherwise would. For example, in the code
5304 below `S::foo()` would normally be defined and exported by the DLL, but when
5305 using the ``/Zc:dllexportInlines-`` flag it is not:
5306
5307 .. code-block:: c
5308
5309 struct __declspec(dllexport) S {
5310 void foo() {}
5311 }
5312
5313 This has the benefit that the compiler doesn't need to emit a definition of
5314 `S::foo()` in every translation unit where the declaration is included, as it
5315 would otherwise do to ensure there's a definition in the DLL even if it's not
5316 used there. If the declaration occurs in a header file that's widely used, this
5317 can save significant compilation time and output size. It also reduces the
5318 number of functions exported by the DLL similarly to what
5319 ``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.
5320 Since the function declaration comes with an inline definition, users of the
5321 library can use that definition directly instead of importing it from the DLL.
5322
5323 Note that the Microsoft Visual C++ compiler does not support this option, and
5324 if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the
5325 DLL must be compiled in the same way so that it doesn't attempt to dllimport
5326 the inline member functions. The reverse scenario should generally work though:
5327 a DLL compiled without this flag (such as a system library compiled with Visual
5328 C++) can be referenced from code compiled using the flag, meaning that the
5329 referencing code will use the inline definitions instead of importing them from
5330 the DLL.
5331
5332 Also note that like when using ``-fvisibility-inlines-hidden``, the address of
5333 `S::foo()` will be different inside and outside the DLL, breaking the C/C++
5334 standard requirement that functions have a unique address.
5335
5336 The flag does not apply to explicit class template instantiation definitions or
5337 declarations, as those are typically used to explicitly provide a single
5338 definition in a DLL, (dllexported instantiation definition) or to signal that
5339 the definition is available elsewhere (dllimport instantiation declaration). It
5340 also doesn't apply to inline members with static local variables, to ensure
5341 that the same instance of the variable is used inside and outside the DLL.
5342
5343 Using this flag can cause problems when inline functions that would otherwise
5344 be dllexported refer to internal symbols of a DLL. For example:
5345
5346 .. code-block:: c
5347
5348 void internal();
5349
5350 struct __declspec(dllimport) S {
5351 void foo() { internal(); }
5352 }
5353
5354 Normally, references to `S::foo()` would use the definition in the DLL from
5355 which it was exported, and which presumably also has the definition of
5356 `internal()`. However, when using ``/Zc:dllexportInlines-``, the inline
5357 definition of `S::foo()` is used directly, resulting in a link error since
5358 `internal()` is not available. Even worse, if there is an inline definition of
5359 `internal()` containing a static local variable, we will now refer to a
5360 different instance of that variable than in the DLL:
5361
5362 .. code-block:: c
5363
5364 inline int internal() { static int x; return x++; }
5365
5366 struct __declspec(dllimport) S {
5367 int foo() { return internal(); }
5368 }
5369
5370 This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can
5371 lead to the same issue. To avoid it in this case, make `S::foo()` or
5372 `internal()` non-inline, or mark them `dllimport/dllexport` explicitly.
5373
5374 Finding Clang runtime libraries
5375 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5376
5377 clang-cl supports several features that require runtime library support:
5378
5379 - Address Sanitizer (ASan): ``-fsanitize=address``
5380 - Undefined Behavior Sanitizer (UBSan): ``-fsanitize=undefined``
5381 - Code coverage: ``-fprofile-instr-generate -fcoverage-mapping``
5382 - Profile Guided Optimization (PGO): ``-fprofile-generate``
5383 - Certain math operations (int128 division) require the builtins library
5384
5385 In order to use these features, the user must link the right runtime libraries
5386 into their program. These libraries are distributed alongside Clang in the
5387 library resource directory. Clang searches for the resource directory by
5388 searching relative to the Clang executable. For example, if LLVM is installed
5389 in ``C:\Program Files\LLVM``, then the profile runtime library will be located
5390 at the path
5391 ``C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows\clang_rt.profile-x86_64.lib``.
5392
5393 For UBSan, PGO, and coverage, Clang will emit object files that auto-link the
5394 appropriate runtime library, but the user generally needs to help the linker
5395 (whether it is ``lld-link.exe`` or MSVC ``link.exe``) find the library resource
5396 directory. Using the example installation above, this would mean passing
5397 ``/LIBPATH:C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows`` to the linker.
5398 If the user links the program with the ``clang`` or ``clang-cl`` drivers, the
5399 driver will pass this flag for them.
5400
5401 The auto-linking can be disabled with -fno-rtlib-defaultlib. If that flag is
5402 used, pass the complete flag to required libraries as described for ASan below.
5403
5404 If the linker cannot find the appropriate library, it will emit an error like
5405 this::
5406
5407 $ clang-cl -c -fsanitize=undefined t.cpp
5408
5409 $ lld-link t.obj -dll
5410 lld-link: error: could not open 'clang_rt.ubsan_standalone-x86_64.lib': no such file or directory
5411 lld-link: error: could not open 'clang_rt.ubsan_standalone_cxx-x86_64.lib': no such file or directory
5412
5413 $ link t.obj -dll -nologo
5414 LINK : fatal error LNK1104: cannot open file 'clang_rt.ubsan_standalone-x86_64.lib'
5415
5416 To fix the error, add the appropriate ``/libpath:`` flag to the link line.
5417
5418 For ASan, as of this writing, the user is also responsible for linking against
5419 the correct ASan libraries.
5420
5421 If the user is using the dynamic CRT (``/MD``), then they should add
5422 ``clang_rt.asan_dynamic-x86_64.lib`` to the link line as a regular input. For
5423 other architectures, replace x86_64 with the appropriate name here and below.
5424
5425 If the user is using the static CRT (``/MT``), then different runtimes are used
5426 to produce DLLs and EXEs. To link a DLL, pass
5427 ``clang_rt.asan_dll_thunk-x86_64.lib``. To link an EXE, pass
5428 ``-wholearchive:clang_rt.asan-x86_64.lib``.
5429
5430 Windows System Headers and Library Lookup
5431 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5432
5433 clang-cl uses a set of different approaches to locate the right system libraries
5434 to link against when building code. The Windows environment uses libraries from
5435 three distinct sources:
5436
5437 1. Windows SDK
5438 2. UCRT (Universal C Runtime)
5439 3. Visual C++ Tools (VCRuntime)
5440
5441 The Windows SDK provides the import libraries and headers required to build
5442 programs against the Windows system packages. Underlying the Windows SDK is the
5443 UCRT, the universal C runtime.
5444
5445 This difference is best illustrated by the various headers that one would find
5446 in the different categories. The WinSDK would contain headers such as
5447 `WinSock2.h` which is part of the Windows API surface, providing the Windows
5448 socketing interfaces for networking. UCRT provides the C library headers,
5449 including e.g. `stdio.h`. Finally, the Visual C++ tools provides the underlying
5450 Visual C++ Runtime headers such as `stdint.h` or `crtdefs.h`.
5451
5452 There are various controls that allow the user control over where clang-cl will
5453 locate these headers. The default behaviour for the Windows SDK and UCRT is as
5454 follows:
5455
5456 1. Consult the command line.
5457
5458 Anything the user specifies is always given precedence. The following
5459 extensions are part of the clang-cl toolset:
5460
5461 - `/winsysroot:`
5462
5463 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix
5464 environments. It allows the control of an alternate location to be treated
5465 as a system root. When specified, it will be used as the root where the
5466 `Windows Kits` is located.
5467
5468 - `/winsdkversion:`
5469 - `/winsdkdir:`
5470
5471 If `/winsysroot:` is not specified, the `/winsdkdir:` argument is consulted
5472 as a location to identify where the Windows SDK is located. Contrary to
5473 `/winsysroot:`, `/winsdkdir:` is expected to be the complete path rather
5474 than a root to locate `Windows Kits`.
5475
5476 The `/winsdkversion:` flag allows the user to specify a version identifier
5477 for the SDK to prefer. When this is specified, no additional validation is
5478 performed and this version is preferred. If the version is not specified,
5479 the highest detected version number will be used.
5480
5481 2. Consult the environment.
5482
5483 TODO: This is not yet implemented.
5484
5485 This will consult the environment variables:
5486
5487 - `WindowsSdkDir`
5488 - `UCRTVersion`
5489
5490 3. Fallback to the registry.
5491
5492 If no arguments are used to indicate where the SDK is present, and the
5493 compiler is running on Windows, the registry is consulted to locate the
5494 installation.
5495
5496 The Visual C++ Toolset has a slightly more elaborate mechanism for detection.
5497
5498 1. Consult the command line.
5499
5500 - `/winsysroot:`
5501
5502 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix
5503 environments. It allows the control of an alternate location to be treated
5504 as a system root. When specified, it will be used as the root where the
5505 `VC` directory is located.
5506
5507 - `/vctoolsdir:`
5508 - `/vctoolsversion:`
5509
5510 If `/winsysroot:` is not specified, the `/vctoolsdir:` argument is consulted
5511 as a location to identify where the Visual C++ Tools are located. If
5512 `/vctoolsversion:` is specified, that version is preferred, otherwise, the
5513 highest version detected is used.
5514
5515 2. Consult the environment.
5516
5517 - `/external:[VARIABLE]`
5518
5519 This specifies a user identified environment variable which is treated as
5520 a path delimiter (`;`) separated list of paths to map into `-imsvc`
5521 arguments which are treated as `-isystem`.
5522
5523 - `INCLUDE` and `EXTERNAL_INCLUDE`
5524
5525 The path delimiter (`;`) separated list of paths will be mapped to
5526 `-imsvc` arguments which are treated as `-isystem`.
5527
5528 - `LIB` (indirectly)
5529
5530 The linker `link.exe` or `lld-link.exe` will honour the environment
5531 variable `LIB` which is a path delimiter (`;`) set of paths to consult for
5532 the import libraries to use when linking the final target.
5533
5534 The following environment variables will be consulted and used to form paths
5535 to validate and load content from as appropriate:
5536
5537 - `VCToolsInstallDir`
5538 - `VCINSTALLDIR`
5539 - `Path`
5540
5541 3. Consult `ISetupConfiguration` [Windows Only]
5542
5543 Assuming that the toolchain is built with `USE_MSVC_SETUP_API` defined and
5544 is running on Windows, the Visual Studio COM interface `ISetupConfiguration`
5545 will be used to locate the installation of the MSVC toolset.
5546
5547 4. Fallback to the registry [DEPRECATED]
5548
5549 The registry information is used to help locate the installation as a final
5550 fallback. This is only possible for pre-VS2017 installations and is
5551 considered deprecated.
5552
5553 Restrictions and Limitations compared to Clang
5554 ----------------------------------------------
5555
5556 Strict aliasing (TBAA) is always off by default in clang-cl whereas in clang,
5557 strict aliasing is turned on by default for all optimization levels. For more
5558 details, see :ref:`Strict aliasing <strict_aliasing>`.