]> granicus.if.org Git - clang/blob - docs/UsersManual.rst
UsersManual.rst: Update clang-cl options list again
[clang] / docs / UsersManual.rst
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 <http://clang.llvm.org>`_ or the `LLVM Web
19 Site <http://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 <http://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, ISO C94 (C89+AMD1), ISO
39    C99 (+TC1, TC2, TC3).
40 -  :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
41    variants depending on base language.
42 -  :ref:`C++ Language <cxx>`
43 -  :ref:`Objective C++ Language <objcxx>`
44 -  :ref:`OpenCL C Language <opencl>`: v1.0, v1.1, v1.2, v2.0.
45
46 In addition to these base languages and their dialects, Clang supports a
47 broad variety of language extensions, which are documented in the
48 corresponding language section. These extensions are provided to be
49 compatible with the GCC, Microsoft, and other popular compilers as well
50 as to improve functionality through Clang-specific features. The Clang
51 driver and language features are intentionally designed to be as
52 compatible with the GNU GCC compiler as reasonably possible, easing
53 migration from GCC to Clang. In most cases, code "just works".
54 Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
55 to be compatible with the Visual C++ compiler, cl.exe.
56
57 In addition to language specific features, Clang has a variety of
58 features that depend on what CPU architecture or operating system is
59 being compiled for. Please see the :ref:`Target-Specific Features and
60 Limitations <target_features>` section for more details.
61
62 The rest of the introduction introduces some basic :ref:`compiler
63 terminology <terminology>` that is used throughout this manual and
64 contains a basic :ref:`introduction to using Clang <basicusage>` as a
65 command line compiler.
66
67 .. _terminology:
68
69 Terminology
70 -----------
71
72 Front end, parser, backend, preprocessor, undefined behavior,
73 diagnostic, optimizer
74
75 .. _basicusage:
76
77 Basic Usage
78 -----------
79
80 Intro to how to use a C compiler for newbies.
81
82 compile + link compile then link debug info enabling optimizations
83 picking a language to use, defaults to C11 by default. Autosenses based
84 on extension. using a makefile
85
86 Command Line Options
87 ====================
88
89 This section is generally an index into other sections. It does not go
90 into depth on the ones that are covered by other sections. However, the
91 first part introduces the language selection and other high level
92 options like :option:`-c`, :option:`-g`, etc.
93
94 Options to Control Error and Warning Messages
95 ---------------------------------------------
96
97 .. option:: -Werror
98
99   Turn warnings into errors.
100
101 .. This is in plain monospaced font because it generates the same label as
102 .. -Werror, and Sphinx complains.
103
104 ``-Werror=foo``
105
106   Turn warning "foo" into an error.
107
108 .. option:: -Wno-error=foo
109
110   Turn warning "foo" into an warning even if :option:`-Werror` is specified.
111
112 .. option:: -Wfoo
113
114   Enable warning "foo".
115   See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
116   list of the warning flags that can be specified in this way.
117
118 .. option:: -Wno-foo
119
120   Disable warning "foo".
121
122 .. option:: -w
123
124   Disable all diagnostics.
125
126 .. option:: -Weverything
127
128   :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
129
130 .. option:: -pedantic
131
132   Warn on language extensions.
133
134 .. option:: -pedantic-errors
135
136   Error on language extensions.
137
138 .. option:: -Wsystem-headers
139
140   Enable warnings from system headers.
141
142 .. option:: -ferror-limit=123
143
144   Stop emitting diagnostics after 123 errors have been produced. The default is
145   20, and the error limit can be disabled with `-ferror-limit=0`.
146
147 .. option:: -ftemplate-backtrace-limit=123
148
149   Only emit up to 123 template instantiation notes within the template
150   instantiation backtrace for a single warning or error. The default is 10, and
151   the limit can be disabled with `-ftemplate-backtrace-limit=0`.
152
153 .. _cl_diag_formatting:
154
155 Formatting of Diagnostics
156 ^^^^^^^^^^^^^^^^^^^^^^^^^
157
158 Clang aims to produce beautiful diagnostics by default, particularly for
159 new users that first come to Clang. However, different people have
160 different preferences, and sometimes Clang is driven not by a human,
161 but by a program that wants consistent and easily parsable output. For
162 these cases, Clang provides a wide range of options to control the exact
163 output format of the diagnostics that it generates.
164
165 .. _opt_fshow-column:
166
167 **-f[no-]show-column**
168    Print column number in diagnostic.
169
170    This option, which defaults to on, controls whether or not Clang
171    prints the column number of a diagnostic. For example, when this is
172    enabled, Clang will print something like:
173
174    ::
175
176          test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
177          #endif bad
178                 ^
179                 //
180
181    When this is disabled, Clang will print "test.c:28: warning..." with
182    no column number.
183
184    The printed column numbers count bytes from the beginning of the
185    line; take care if your source contains multibyte characters.
186
187 .. _opt_fshow-source-location:
188
189 **-f[no-]show-source-location**
190    Print source file/line/column information in diagnostic.
191
192    This option, which defaults to on, controls whether or not Clang
193    prints the filename, line number and column number of a diagnostic.
194    For example, when this is enabled, Clang will print something like:
195
196    ::
197
198          test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
199          #endif bad
200                 ^
201                 //
202
203    When this is disabled, Clang will not print the "test.c:28:8: "
204    part.
205
206 .. _opt_fcaret-diagnostics:
207
208 **-f[no-]caret-diagnostics**
209    Print source line and ranges from source code in diagnostic.
210    This option, which defaults to on, controls whether or not Clang
211    prints the source line, source ranges, and caret when emitting a
212    diagnostic. For example, when this is enabled, Clang will print
213    something like:
214
215    ::
216
217          test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
218          #endif bad
219                 ^
220                 //
221
222 **-f[no-]color-diagnostics**
223    This option, which defaults to on when a color-capable terminal is
224    detected, controls whether or not Clang prints diagnostics in color.
225
226    When this option is enabled, Clang will use colors to highlight
227    specific parts of the diagnostic, e.g.,
228
229    .. nasty hack to not lose our dignity
230
231    .. raw:: html
232
233        <pre>
234          <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>
235          #endif bad
236                 <span style="color:green">^</span>
237                 <span style="color:green">//</span>
238        </pre>
239
240    When this is disabled, Clang will just print:
241
242    ::
243
244          test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
245          #endif bad
246                 ^
247                 //
248
249 **-fansi-escape-codes**
250    Controls whether ANSI escape codes are used instead of the Windows Console
251    API to output colored diagnostics. This option is only used on Windows and
252    defaults to off.
253
254 .. option:: -fdiagnostics-format=clang/msvc/vi
255
256    Changes diagnostic output format to better match IDEs and command line tools.
257
258    This option controls the output format of the filename, line number,
259    and column printed in diagnostic messages. The options, and their
260    affect on formatting a simple conversion diagnostic, follow:
261
262    **clang** (default)
263        ::
264
265            t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
266
267    **msvc**
268        ::
269
270            t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
271
272    **vi**
273        ::
274
275            t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
276
277 .. _opt_fdiagnostics-show-option:
278
279 **-f[no-]diagnostics-show-option**
280    Enable ``[-Woption]`` information in diagnostic line.
281
282    This option, which defaults to on, controls whether or not Clang
283    prints the associated :ref:`warning group <cl_diag_warning_groups>`
284    option name when outputting a warning diagnostic. For example, in
285    this output:
286
287    ::
288
289          test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
290          #endif bad
291                 ^
292                 //
293
294    Passing **-fno-diagnostics-show-option** will prevent Clang from
295    printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
296    the diagnostic. This information tells you the flag needed to enable
297    or disable the diagnostic, either from the command line or through
298    :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
299
300 .. _opt_fdiagnostics-show-category:
301
302 .. option:: -fdiagnostics-show-category=none/id/name
303
304    Enable printing category information in diagnostic line.
305
306    This option, which defaults to "none", controls whether or not Clang
307    prints the category associated with a diagnostic when emitting it.
308    Each diagnostic may or many not have an associated category, if it
309    has one, it is listed in the diagnostic categorization field of the
310    diagnostic line (in the []'s).
311
312    For example, a format string warning will produce these three
313    renditions based on the setting of this option:
314
315    ::
316
317          t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
318          t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
319          t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
320
321    This category can be used by clients that want to group diagnostics
322    by category, so it should be a high level category. We want dozens
323    of these, not hundreds or thousands of them.
324
325 .. _opt_fdiagnostics-show-hotness:
326
327 **-f[no-]diagnostics-show-hotness**
328    Enable profile hotness information in diagnostic line.
329
330    This option, which defaults to off, controls whether Clang prints the
331    profile hotness associated with a diagnostics in the presence of
332    profile-guided optimization information.  This is currently supported with
333    optimization remarks (see :ref:`Options to Emit Optimization Reports
334    <rpass>`).  The hotness information allows users to focus on the hot
335    optimization remarks that are likely to be more relevant for run-time
336    performance.
337
338    For example, in this output, the block containing the callsite of `foo` was
339    executed 3000 times according to the profile data:
340
341    ::
342
343          s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
344            sum += foo(x, x - 2);
345                   ^
346
347 .. _opt_fdiagnostics-fixit-info:
348
349 **-f[no-]diagnostics-fixit-info**
350    Enable "FixIt" information in the diagnostics output.
351
352    This option, which defaults to on, controls whether or not Clang
353    prints the information on how to fix a specific diagnostic
354    underneath it when it knows. For example, in this output:
355
356    ::
357
358          test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
359          #endif bad
360                 ^
361                 //
362
363    Passing **-fno-diagnostics-fixit-info** will prevent Clang from
364    printing the "//" line at the end of the message. This information
365    is useful for users who may not understand what is wrong, but can be
366    confusing for machine parsing.
367
368 .. _opt_fdiagnostics-print-source-range-info:
369
370 **-fdiagnostics-print-source-range-info**
371    Print machine parsable information about source ranges.
372    This option makes Clang print information about source ranges in a machine
373    parsable format after the file/line/column number information. The
374    information is a simple sequence of brace enclosed ranges, where each range
375    lists the start and end line/column locations. For example, in this output:
376
377    ::
378
379        exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
380           P = (P-42) + Gamma*4;
381               ~~~~~~ ^ ~~~~~~~
382
383    The {}'s are generated by -fdiagnostics-print-source-range-info.
384
385    The printed column numbers count bytes from the beginning of the
386    line; take care if your source contains multibyte characters.
387
388 .. option:: -fdiagnostics-parseable-fixits
389
390    Print Fix-Its in a machine parseable form.
391
392    This option makes Clang print available Fix-Its in a machine
393    parseable format at the end of diagnostics. The following example
394    illustrates the format:
395
396    ::
397
398         fix-it:"t.cpp":{7:25-7:29}:"Gamma"
399
400    The range printed is a half-open range, so in this example the
401    characters at column 25 up to but not including column 29 on line 7
402    in t.cpp should be replaced with the string "Gamma". Either the
403    range or the replacement string may be empty (representing strict
404    insertions and strict erasures, respectively). Both the file name
405    and the insertion string escape backslash (as "\\\\"), tabs (as
406    "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
407    non-printable characters (as octal "\\xxx").
408
409    The printed column numbers count bytes from the beginning of the
410    line; take care if your source contains multibyte characters.
411
412 .. option:: -fno-elide-type
413
414    Turns off elision in template type printing.
415
416    The default for template type printing is to elide as many template
417    arguments as possible, removing those which are the same in both
418    template types, leaving only the differences. Adding this flag will
419    print all the template arguments. If supported by the terminal,
420    highlighting will still appear on differing arguments.
421
422    Default:
423
424    ::
425
426        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;
427
428    -fno-elide-type:
429
430    ::
431
432        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;
433
434 .. option:: -fdiagnostics-show-template-tree
435
436    Template type diffing prints a text tree.
437
438    For diffing large templated types, this option will cause Clang to
439    display the templates as an indented text tree, one argument per
440    line, with differences marked inline. This is compatible with
441    -fno-elide-type.
442
443    Default:
444
445    ::
446
447        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;
448
449    With :option:`-fdiagnostics-show-template-tree`:
450
451    ::
452
453        t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
454          vector<
455            map<
456              [...],
457              map<
458                [float != double],
459                [...]>>>
460
461 .. _cl_diag_warning_groups:
462
463 Individual Warning Groups
464 ^^^^^^^^^^^^^^^^^^^^^^^^^
465
466 TODO: Generate this from tblgen. Define one anchor per warning group.
467
468 .. _opt_wextra-tokens:
469
470 .. option:: -Wextra-tokens
471
472    Warn about excess tokens at the end of a preprocessor directive.
473
474    This option, which defaults to on, enables warnings about extra
475    tokens at the end of preprocessor directives. For example:
476
477    ::
478
479          test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
480          #endif bad
481                 ^
482
483    These extra tokens are not strictly conforming, and are usually best
484    handled by commenting them out.
485
486 .. option:: -Wambiguous-member-template
487
488    Warn about unqualified uses of a member template whose name resolves to
489    another template at the location of the use.
490
491    This option, which defaults to on, enables a warning in the
492    following code:
493
494    ::
495
496        template<typename T> struct set{};
497        template<typename T> struct trait { typedef const T& type; };
498        struct Value {
499          template<typename T> void set(typename trait<T>::type value) {}
500        };
501        void foo() {
502          Value v;
503          v.set<double>(3.2);
504        }
505
506    C++ [basic.lookup.classref] requires this to be an error, but,
507    because it's hard to work around, Clang downgrades it to a warning
508    as an extension.
509
510 .. option:: -Wbind-to-temporary-copy
511
512    Warn about an unusable copy constructor when binding a reference to a
513    temporary.
514
515    This option enables warnings about binding a
516    reference to a temporary when the temporary doesn't have a usable
517    copy constructor. For example:
518
519    ::
520
521          struct NonCopyable {
522            NonCopyable();
523          private:
524            NonCopyable(const NonCopyable&);
525          };
526          void foo(const NonCopyable&);
527          void bar() {
528            foo(NonCopyable());  // Disallowed in C++98; allowed in C++11.
529          }
530
531    ::
532
533          struct NonCopyable2 {
534            NonCopyable2();
535            NonCopyable2(NonCopyable2&);
536          };
537          void foo(const NonCopyable2&);
538          void bar() {
539            foo(NonCopyable2());  // Disallowed in C++98; allowed in C++11.
540          }
541
542    Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
543    whose instantiation produces a compile error, that error will still
544    be a hard error in C++98 mode even if this warning is turned off.
545
546 Options to Control Clang Crash Diagnostics
547 ------------------------------------------
548
549 As unbelievable as it may sound, Clang does crash from time to time.
550 Generally, this only occurs to those living on the `bleeding
551 edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
552 lengths to assist you in filing a bug report. Specifically, Clang
553 generates preprocessed source file(s) and associated run script(s) upon
554 a crash. These files should be attached to a bug report to ease
555 reproducibility of the failure. Below are the command line options to
556 control the crash diagnostics.
557
558 .. option:: -fno-crash-diagnostics
559
560   Disable auto-generation of preprocessed source files during a clang crash.
561
562 The -fno-crash-diagnostics flag can be helpful for speeding the process
563 of generating a delta reduced test case.
564
565 .. _rpass:
566
567 Options to Emit Optimization Reports
568 ------------------------------------
569
570 Optimization reports trace, at a high-level, all the major decisions
571 done by compiler transformations. For instance, when the inliner
572 decides to inline function ``foo()`` into ``bar()``, or the loop unroller
573 decides to unroll a loop N times, or the vectorizer decides to
574 vectorize a loop body.
575
576 Clang offers a family of flags which the optimizers can use to emit
577 a diagnostic in three cases:
578
579 1. When the pass makes a transformation (`-Rpass`).
580
581 2. When the pass fails to make a transformation (`-Rpass-missed`).
582
583 3. When the pass determines whether or not to make a transformation
584    (`-Rpass-analysis`).
585
586 NOTE: Although the discussion below focuses on `-Rpass`, the exact
587 same options apply to `-Rpass-missed` and `-Rpass-analysis`.
588
589 Since there are dozens of passes inside the compiler, each of these flags
590 take a regular expression that identifies the name of the pass which should
591 emit the associated diagnostic. For example, to get a report from the inliner,
592 compile the code with:
593
594 .. code-block:: console
595
596    $ clang -O2 -Rpass=inline code.cc -o code
597    code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
598    int bar(int j) { return foo(j, j - 2); }
599                            ^
600
601 Note that remarks from the inliner are identified with `[-Rpass=inline]`.
602 To request a report from every optimization pass, you should use
603 `-Rpass=.*` (in fact, you can use any valid POSIX regular
604 expression). However, do not expect a report from every transformation
605 made by the compiler. Optimization remarks do not really make sense
606 outside of the major transformations (e.g., inlining, vectorization,
607 loop optimizations) and not every optimization pass supports this
608 feature.
609
610 Note that when using profile-guided optimization information, profile hotness
611 information can be included in the remarks (see
612 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
613
614 Current limitations
615 ^^^^^^^^^^^^^^^^^^^
616
617 1. Optimization remarks that refer to function names will display the
618    mangled name of the function. Since these remarks are emitted by the
619    back end of the compiler, it does not know anything about the input
620    language, nor its mangling rules.
621
622 2. Some source locations are not displayed correctly. The front end has
623    a more detailed source location tracking than the locations included
624    in the debug info (e.g., the front end can locate code inside macro
625    expansions). However, the locations used by `-Rpass` are
626    translated from debug annotations. That translation can be lossy,
627    which results in some remarks having no location information.
628
629 Other Options
630 -------------
631 Clang options that that don't fit neatly into other categories.
632
633 .. option:: -MV
634
635   When emitting a dependency file, use formatting conventions appropriate
636   for NMake or Jom. Ignored unless another option causes Clang to emit a
637   dependency file.
638
639 When Clang emits a dependency file (e.g., you supplied the -M option)
640 most filenames can be written to the file without any special formatting.
641 Different Make tools will treat different sets of characters as "special"
642 and use different conventions for telling the Make tool that the character
643 is actually part of the filename. Normally Clang uses backslash to "escape"
644 a special character, which is the convention used by GNU Make. The -MV
645 option tells Clang to put double-quotes around the entire filename, which
646 is the convention used by NMake and Jom.
647
648
649 Language and Target-Independent Features
650 ========================================
651
652 Controlling Errors and Warnings
653 -------------------------------
654
655 Clang provides a number of ways to control which code constructs cause
656 it to emit errors and warning messages, and how they are displayed to
657 the console.
658
659 Controlling How Clang Displays Diagnostics
660 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
661
662 When Clang emits a diagnostic, it includes rich information in the
663 output, and gives you fine-grain control over which information is
664 printed. Clang has the ability to print this information, and these are
665 the options that control it:
666
667 #. A file/line/column indicator that shows exactly where the diagnostic
668    occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
669    :ref:`-fshow-source-location <opt_fshow-source-location>`].
670 #. A categorization of the diagnostic as a note, warning, error, or
671    fatal error.
672 #. A text string that describes what the problem is.
673 #. An option that indicates how to control the diagnostic (for
674    diagnostics that support it)
675    [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
676 #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
677    for clients that want to group diagnostics by class (for diagnostics
678    that support it)
679    [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
680 #. The line of source code that the issue occurs on, along with a caret
681    and ranges that indicate the important locations
682    [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
683 #. "FixIt" information, which is a concise explanation of how to fix the
684    problem (when Clang is certain it knows)
685    [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
686 #. A machine-parsable representation of the ranges involved (off by
687    default)
688    [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
689
690 For more information please see :ref:`Formatting of
691 Diagnostics <cl_diag_formatting>`.
692
693 Diagnostic Mappings
694 ^^^^^^^^^^^^^^^^^^^
695
696 All diagnostics are mapped into one of these 6 classes:
697
698 -  Ignored
699 -  Note
700 -  Remark
701 -  Warning
702 -  Error
703 -  Fatal
704
705 .. _diagnostics_categories:
706
707 Diagnostic Categories
708 ^^^^^^^^^^^^^^^^^^^^^
709
710 Though not shown by default, diagnostics may each be associated with a
711 high-level category. This category is intended to make it possible to
712 triage builds that produce a large number of errors or warnings in a
713 grouped way.
714
715 Categories are not shown by default, but they can be turned on with the
716 :ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
717 When set to "``name``", the category is printed textually in the
718 diagnostic output. When it is set to "``id``", a category number is
719 printed. The mapping of category names to category id's can be obtained
720 by running '``clang   --print-diagnostic-categories``'.
721
722 Controlling Diagnostics via Command Line Flags
723 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
724
725 TODO: -W flags, -pedantic, etc
726
727 .. _pragma_gcc_diagnostic:
728
729 Controlling Diagnostics via Pragmas
730 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
731
732 Clang can also control what diagnostics are enabled through the use of
733 pragmas in the source code. This is useful for turning off specific
734 warnings in a section of source code. Clang supports GCC's pragma for
735 compatibility with existing source code, as well as several extensions.
736
737 The pragma may control any warning that can be used from the command
738 line. Warnings may be set to ignored, warning, error, or fatal. The
739 following example code will tell Clang or GCC to ignore the -Wall
740 warnings:
741
742 .. code-block:: c
743
744   #pragma GCC diagnostic ignored "-Wall"
745
746 In addition to all of the functionality provided by GCC's pragma, Clang
747 also allows you to push and pop the current warning state. This is
748 particularly useful when writing a header file that will be compiled by
749 other people, because you don't know what warning flags they build with.
750
751 In the below example :option:`-Wextra-tokens` is ignored for only a single line
752 of code, after which the diagnostics return to whatever state had previously
753 existed.
754
755 .. code-block:: c
756
757   #if foo
758   #endif foo // warning: extra tokens at end of #endif directive
759
760   #pragma clang diagnostic ignored "-Wextra-tokens"
761
762   #if foo
763   #endif foo // no warning
764
765   #pragma clang diagnostic pop
766
767 The push and pop pragmas will save and restore the full diagnostic state
768 of the compiler, regardless of how it was set. That means that it is
769 possible to use push and pop around GCC compatible diagnostics and Clang
770 will push and pop them appropriately, while GCC will ignore the pushes
771 and pops as unknown pragmas. It should be noted that while Clang
772 supports the GCC pragma, Clang and GCC do not support the exact same set
773 of warnings, so even when using GCC compatible #pragmas there is no
774 guarantee that they will have identical behaviour on both compilers.
775
776 In addition to controlling warnings and errors generated by the compiler, it is
777 possible to generate custom warning and error messages through the following
778 pragmas:
779
780 .. code-block:: c
781
782   // The following will produce warning messages
783   #pragma message "some diagnostic message"
784   #pragma GCC warning "TODO: replace deprecated feature"
785
786   // The following will produce an error message
787   #pragma GCC error "Not supported"
788
789 These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
790 directives, except that they may also be embedded into preprocessor macros via
791 the C99 ``_Pragma`` operator, for example:
792
793 .. code-block:: c
794
795   #define STR(X) #X
796   #define DEFER(M,...) M(__VA_ARGS__)
797   #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
798
799   CUSTOM_ERROR("Feature not available");
800
801 Controlling Diagnostics in System Headers
802 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
803
804 Warnings are suppressed when they occur in system headers. By default,
805 an included file is treated as a system header if it is found in an
806 include path specified by ``-isystem``, but this can be overridden in
807 several ways.
808
809 The ``system_header`` pragma can be used to mark the current file as
810 being a system header. No warnings will be produced from the location of
811 the pragma onwards within the same file.
812
813 .. code-block:: c
814
815   #if foo
816   #endif foo // warning: extra tokens at end of #endif directive
817
818   #pragma clang system_header
819
820   #if foo
821   #endif foo // no warning
822
823 The `--system-header-prefix=` and `--no-system-header-prefix=`
824 command-line arguments can be used to override whether subsets of an include
825 path are treated as system headers. When the name in a ``#include`` directive
826 is found within a header search path and starts with a system prefix, the
827 header is treated as a system header. The last prefix on the
828 command-line which matches the specified header name takes precedence.
829 For instance:
830
831 .. code-block:: console
832
833   $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
834       --no-system-header-prefix=x/y/
835
836 Here, ``#include "x/a.h"`` is treated as including a system header, even
837 if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
838 as not including a system header, even if the header is found in
839 ``bar``.
840
841 A ``#include`` directive which finds a file relative to the current
842 directory is treated as including a system header if the including file
843 is treated as a system header.
844
845 .. _diagnostics_enable_everything:
846
847 Enabling All Diagnostics
848 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
849
850 In addition to the traditional ``-W`` flags, one can enable **all**
851 diagnostics by passing :option:`-Weverything`. This works as expected
852 with
853 :option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
854
855 Note that when combined with :option:`-w` (which disables all warnings), that
856 flag wins.
857
858 Controlling Static Analyzer Diagnostics
859 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
860
861 While not strictly part of the compiler, the diagnostics from Clang's
862 `static analyzer <http://clang-analyzer.llvm.org>`_ can also be
863 influenced by the user via changes to the source code. See the available
864 `annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
865 analyzer's `FAQ
866 page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
867 information.
868
869 .. _usersmanual-precompiled-headers:
870
871 Precompiled Headers
872 -------------------
873
874 `Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
875 are a general approach employed by many compilers to reduce compilation
876 time. The underlying motivation of the approach is that it is common for
877 the same (and often large) header files to be included by multiple
878 source files. Consequently, compile times can often be greatly improved
879 by caching some of the (redundant) work done by a compiler to process
880 headers. Precompiled header files, which represent one of many ways to
881 implement this optimization, are literally files that represent an
882 on-disk cache that contains the vital information necessary to reduce
883 some of the work needed to process a corresponding header file. While
884 details of precompiled headers vary between compilers, precompiled
885 headers have been shown to be highly effective at speeding up program
886 compilation on systems with very large system headers (e.g., Mac OS X).
887
888 Generating a PCH File
889 ^^^^^^^^^^^^^^^^^^^^^
890
891 To generate a PCH file using Clang, one invokes Clang with the
892 `-x <language>-header` option. This mirrors the interface in GCC
893 for generating PCH files:
894
895 .. code-block:: console
896
897   $ gcc -x c-header test.h -o test.h.gch
898   $ clang -x c-header test.h -o test.h.pch
899
900 Using a PCH File
901 ^^^^^^^^^^^^^^^^
902
903 A PCH file can then be used as a prefix header when a :option:`-include`
904 option is passed to ``clang``:
905
906 .. code-block:: console
907
908   $ clang -include test.h test.c -o test
909
910 The ``clang`` driver will first check if a PCH file for ``test.h`` is
911 available; if so, the contents of ``test.h`` (and the files it includes)
912 will be processed from the PCH file. Otherwise, Clang falls back to
913 directly processing the content of ``test.h``. This mirrors the behavior
914 of GCC.
915
916 .. note::
917
918   Clang does *not* automatically use PCH files for headers that are directly
919   included within a source file. For example:
920
921   .. code-block:: console
922
923     $ clang -x c-header test.h -o test.h.pch
924     $ cat test.c
925     #include "test.h"
926     $ clang test.c -o test
927
928   In this example, ``clang`` will not automatically use the PCH file for
929   ``test.h`` since ``test.h`` was included directly in the source file and not
930   specified on the command line using :option:`-include`.
931
932 Relocatable PCH Files
933 ^^^^^^^^^^^^^^^^^^^^^
934
935 It is sometimes necessary to build a precompiled header from headers
936 that are not yet in their final, installed locations. For example, one
937 might build a precompiled header within the build tree that is then
938 meant to be installed alongside the headers. Clang permits the creation
939 of "relocatable" precompiled headers, which are built with a given path
940 (into the build directory) and can later be used from an installed
941 location.
942
943 To build a relocatable precompiled header, place your headers into a
944 subdirectory whose structure mimics the installed location. For example,
945 if you want to build a precompiled header for the header ``mylib.h``
946 that will be installed into ``/usr/include``, create a subdirectory
947 ``build/usr/include`` and place the header ``mylib.h`` into that
948 subdirectory. If ``mylib.h`` depends on other headers, then they can be
949 stored within ``build/usr/include`` in a way that mimics the installed
950 location.
951
952 Building a relocatable precompiled header requires two additional
953 arguments. First, pass the ``--relocatable-pch`` flag to indicate that
954 the resulting PCH file should be relocatable. Second, pass
955 `-isysroot /path/to/build`, which makes all includes for your library
956 relative to the build directory. For example:
957
958 .. code-block:: console
959
960   # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
961
962 When loading the relocatable PCH file, the various headers used in the
963 PCH file are found from the system header root. For example, ``mylib.h``
964 can be found in ``/usr/include/mylib.h``. If the headers are installed
965 in some other system root, the `-isysroot` option can be used provide
966 a different system root from which the headers will be based. For
967 example, `-isysroot /Developer/SDKs/MacOSX10.4u.sdk` will look for
968 ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
969
970 Relocatable precompiled headers are intended to be used in a limited
971 number of cases where the compilation environment is tightly controlled
972 and the precompiled header cannot be generated after headers have been
973 installed.
974
975 .. _controlling-code-generation:
976
977 Controlling Code Generation
978 ---------------------------
979
980 Clang provides a number of ways to control code generation. The options
981 are listed below.
982
983 **-f[no-]sanitize=check1,check2,...**
984    Turn on runtime checks for various forms of undefined or suspicious
985    behavior.
986
987    This option controls whether Clang adds runtime checks for various
988    forms of undefined or suspicious behavior, and is disabled by
989    default. If a check fails, a diagnostic message is produced at
990    runtime explaining the problem. The main checks are:
991
992    -  .. _opt_fsanitize_address:
993
994       ``-fsanitize=address``:
995       :doc:`AddressSanitizer`, a memory error
996       detector.
997    -  .. _opt_fsanitize_thread:
998
999       ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
1000    -  .. _opt_fsanitize_memory:
1001
1002       ``-fsanitize=memory``: :doc:`MemorySanitizer`,
1003       a detector of uninitialized reads. Requires instrumentation of all
1004       program code.
1005    -  .. _opt_fsanitize_undefined:
1006
1007       ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
1008       a fast and compatible undefined behavior checker.
1009
1010    -  ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
1011       flow analysis.
1012    -  ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
1013       checks. Requires ``-flto``.
1014    -  ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
1015       protection against stack-based memory corruption errors.
1016
1017    There are more fine-grained checks available: see
1018    the :ref:`list <ubsan-checks>` of specific kinds of
1019    undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
1020    of control flow integrity schemes.
1021
1022    The ``-fsanitize=`` argument must also be provided when linking, in
1023    order to link to the appropriate runtime library.
1024
1025    It is not possible to combine more than one of the ``-fsanitize=address``,
1026    ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
1027    program.
1028
1029 **-f[no-]sanitize-recover=check1,check2,...**
1030
1031 **-f[no-]sanitize-recover=all**
1032
1033    Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
1034    If the check is fatal, program will halt after the first error
1035    of this kind is detected and error report is printed.
1036
1037    By default, non-fatal checks are those enabled by
1038    :doc:`UndefinedBehaviorSanitizer`,
1039    except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
1040    sanitizers may not support recovery (or not support it by default
1041    e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
1042    is detected.
1043
1044    Note that the ``-fsanitize-trap`` flag has precedence over this flag.
1045    This means that if a check has been configured to trap elsewhere on the
1046    command line, or if the check traps by default, this flag will not have
1047    any effect unless that sanitizer's trapping behavior is disabled with
1048    ``-fno-sanitize-trap``.
1049
1050    For example, if a command line contains the flags ``-fsanitize=undefined
1051    -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
1052    will have no effect on its own; it will need to be accompanied by
1053    ``-fno-sanitize-trap=alignment``.
1054
1055 **-f[no-]sanitize-trap=check1,check2,...**
1056
1057    Controls which checks enabled by the ``-fsanitize=`` flag trap. This
1058    option is intended for use in cases where the sanitizer runtime cannot
1059    be used (for instance, when building libc or a kernel module), or where
1060    the binary size increase caused by the sanitizer runtime is a concern.
1061
1062    This flag is only compatible with :doc:`control flow integrity
1063    <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
1064    checks other than ``vptr``. If this flag
1065    is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
1066    will be implicitly disabled.
1067
1068    This flag is enabled by default for sanitizers in the ``cfi`` group.
1069
1070 .. option:: -fsanitize-blacklist=/path/to/blacklist/file
1071
1072    Disable or modify sanitizer checks for objects (source files, functions,
1073    variables, types) listed in the file. See
1074    :doc:`SanitizerSpecialCaseList` for file format description.
1075
1076 .. option:: -fno-sanitize-blacklist
1077
1078    Don't use blacklist file, if it was specified earlier in the command line.
1079
1080 **-f[no-]sanitize-coverage=[type,features,...]**
1081
1082    Enable simple code coverage in addition to certain sanitizers.
1083    See :doc:`SanitizerCoverage` for more details.
1084
1085 **-f[no-]sanitize-stats**
1086
1087    Enable simple statistics gathering for the enabled sanitizers.
1088    See :doc:`SanitizerStats` for more details.
1089
1090 .. option:: -fsanitize-undefined-trap-on-error
1091
1092    Deprecated alias for ``-fsanitize-trap=undefined``.
1093
1094 .. option:: -fsanitize-cfi-cross-dso
1095
1096    Enable cross-DSO control flow integrity checks. This flag modifies
1097    the behavior of sanitizers in the ``cfi`` group to allow checking
1098    of cross-DSO virtual and indirect calls.
1099
1100 .. option:: -ffast-math
1101
1102    Enable fast-math mode. This defines the ``__FAST_MATH__`` preprocessor
1103    macro, and lets the compiler make aggressive, potentially-lossy assumptions
1104    about floating-point math.  These include:
1105
1106    * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1107      ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1108      ``(a + b) * c == a * c + b * c``),
1109    * operands to floating-point operations are not equal to ``NaN`` and
1110      ``Inf``, and
1111    * ``+0`` and ``-0`` are interchangeable.
1112
1113 .. option:: -fdenormal-fp-math=[values]
1114
1115    Select which denormal numbers the code is permitted to require.
1116
1117    Valid values are: ``ieee``, ``preserve-sign``, and ``positive-zero``,
1118    which correspond to IEEE 754 denormal numbers, the sign of a
1119    flushed-to-zero number is preserved in the sign of 0, denormals are
1120    flushed to positive zero, respectively.
1121
1122 .. option:: -fwhole-program-vtables
1123
1124    Enable whole-program vtable optimizations, such as single-implementation
1125    devirtualization and virtual constant propagation, for classes with
1126    :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
1127
1128 .. option:: -fno-assume-sane-operator-new
1129
1130    Don't assume that the C++'s new operator is sane.
1131
1132    This option tells the compiler to do not assume that C++'s global
1133    new operator will always return a pointer that does not alias any
1134    other pointer when the function returns.
1135
1136 .. option:: -ftrap-function=[name]
1137
1138    Instruct code generator to emit a function call to the specified
1139    function name for ``__builtin_trap()``.
1140
1141    LLVM code generator translates ``__builtin_trap()`` to a trap
1142    instruction if it is supported by the target ISA. Otherwise, the
1143    builtin is translated into a call to ``abort``. If this option is
1144    set, then the code generator will always lower the builtin to a call
1145    to the specified function regardless of whether the target ISA has a
1146    trap instruction. This option is useful for environments (e.g.
1147    deeply embedded) where a trap cannot be properly handled, or when
1148    some custom behavior is desired.
1149
1150 .. option:: -ftls-model=[model]
1151
1152    Select which TLS model to use.
1153
1154    Valid values are: ``global-dynamic``, ``local-dynamic``,
1155    ``initial-exec`` and ``local-exec``. The default value is
1156    ``global-dynamic``. The compiler may use a different model if the
1157    selected model is not supported by the target, or if a more
1158    efficient model can be used. The TLS model can be overridden per
1159    variable using the ``tls_model`` attribute.
1160
1161 .. option:: -femulated-tls
1162
1163    Select emulated TLS model, which overrides all -ftls-model choices.
1164
1165    In emulated TLS mode, all access to TLS variables are converted to
1166    calls to __emutls_get_address in the runtime library.
1167
1168 .. option:: -mhwdiv=[values]
1169
1170    Select the ARM modes (arm or thumb) that support hardware division
1171    instructions.
1172
1173    Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
1174    This option is used to indicate which mode (arm or thumb) supports
1175    hardware division instructions. This only applies to the ARM
1176    architecture.
1177
1178 .. option:: -m[no-]crc
1179
1180    Enable or disable CRC instructions.
1181
1182    This option is used to indicate whether CRC instructions are to
1183    be generated. This only applies to the ARM architecture.
1184
1185    CRC instructions are enabled by default on ARMv8.
1186
1187 .. option:: -mgeneral-regs-only
1188
1189    Generate code which only uses the general purpose registers.
1190
1191    This option restricts the generated code to use general registers
1192    only. This only applies to the AArch64 architecture.
1193
1194 .. option:: -mcompact-branches=[values]
1195
1196    Control the usage of compact branches for MIPSR6.
1197
1198    Valid values are: ``never``, ``optimal`` and ``always``.
1199    The default value is ``optimal`` which generates compact branches
1200    when a delay slot cannot be filled. ``never`` disables the usage of
1201    compact branches and ``always`` generates compact branches whenever
1202    possible.
1203
1204 **-f[no-]max-type-align=[number]**
1205    Instruct the code generator to not enforce a higher alignment than the given
1206    number (of bytes) when accessing memory via an opaque pointer or reference.
1207    This cap is ignored when directly accessing a variable or when the pointee
1208    type has an explicit “aligned” attribute.
1209
1210    The value should usually be determined by the properties of the system allocator.
1211    Some builtin types, especially vector types, have very high natural alignments;
1212    when working with values of those types, Clang usually wants to use instructions
1213    that take advantage of that alignment.  However, many system allocators do
1214    not promise to return memory that is more than 8-byte or 16-byte-aligned.  Use
1215    this option to limit the alignment that the compiler can assume for an arbitrary
1216    pointer, which may point onto the heap.
1217
1218    This option does not affect the ABI alignment of types; the layout of structs and
1219    unions and the value returned by the alignof operator remain the same.
1220
1221    This option can be overridden on a case-by-case basis by putting an explicit
1222    “aligned” alignment on a struct, union, or typedef.  For example:
1223
1224    .. code-block:: console
1225
1226       #include <immintrin.h>
1227       // Make an aligned typedef of the AVX-512 16-int vector type.
1228       typedef __v16si __aligned_v16si __attribute__((aligned(64)));
1229
1230       void initialize_vector(__aligned_v16si *v) {
1231         // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
1232         // value of -fmax-type-align.
1233       }
1234
1235
1236 Profile Guided Optimization
1237 ---------------------------
1238
1239 Profile information enables better optimization. For example, knowing that a
1240 branch is taken very frequently helps the compiler make better decisions when
1241 ordering basic blocks. Knowing that a function ``foo`` is called more
1242 frequently than another function ``bar`` helps the inliner.
1243
1244 Clang supports profile guided optimization with two different kinds of
1245 profiling. A sampling profiler can generate a profile with very low runtime
1246 overhead, or you can build an instrumented version of the code that collects
1247 more detailed profile information. Both kinds of profiles can provide execution
1248 counts for instructions in the code and information on branches taken and
1249 function invocation.
1250
1251 Regardless of which kind of profiling you use, be careful to collect profiles
1252 by running your code with inputs that are representative of the typical
1253 behavior. Code that is not exercised in the profile will be optimized as if it
1254 is unimportant, and the compiler may make poor optimization choices for code
1255 that is disproportionately used while profiling.
1256
1257 Differences Between Sampling and Instrumentation
1258 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1259
1260 Although both techniques are used for similar purposes, there are important
1261 differences between the two:
1262
1263 1. Profile data generated with one cannot be used by the other, and there is no
1264    conversion tool that can convert one to the other. So, a profile generated
1265    via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
1266    Similarly, sampling profiles generated by external profilers must be
1267    converted and used with ``-fprofile-sample-use``.
1268
1269 2. Instrumentation profile data can be used for code coverage analysis and
1270    optimization.
1271
1272 3. Sampling profiles can only be used for optimization. They cannot be used for
1273    code coverage analysis. Although it would be technically possible to use
1274    sampling profiles for code coverage, sample-based profiles are too
1275    coarse-grained for code coverage purposes; it would yield poor results.
1276
1277 4. Sampling profiles must be generated by an external tool. The profile
1278    generated by that tool must then be converted into a format that can be read
1279    by LLVM. The section on sampling profilers describes one of the supported
1280    sampling profile formats.
1281
1282
1283 Using Sampling Profilers
1284 ^^^^^^^^^^^^^^^^^^^^^^^^
1285
1286 Sampling profilers are used to collect runtime information, such as
1287 hardware counters, while your application executes. They are typically
1288 very efficient and do not incur a large runtime overhead. The
1289 sample data collected by the profiler can be used during compilation
1290 to determine what the most executed areas of the code are.
1291
1292 Using the data from a sample profiler requires some changes in the way
1293 a program is built. Before the compiler can use profiling information,
1294 the code needs to execute under the profiler. The following is the
1295 usual build cycle when using sample profilers for optimization:
1296
1297 1. Build the code with source line table information. You can use all the
1298    usual build flags that you always build your application with. The only
1299    requirement is that you add ``-gline-tables-only`` or ``-g`` to the
1300    command line. This is important for the profiler to be able to map
1301    instructions back to source line locations.
1302
1303    .. code-block:: console
1304
1305      $ clang++ -O2 -gline-tables-only code.cc -o code
1306
1307 2. Run the executable under a sampling profiler. The specific profiler
1308    you use does not really matter, as long as its output can be converted
1309    into the format that the LLVM optimizer understands. Currently, there
1310    exists a conversion tool for the Linux Perf profiler
1311    (https://perf.wiki.kernel.org/), so these examples assume that you
1312    are using Linux Perf to profile your code.
1313
1314    .. code-block:: console
1315
1316      $ perf record -b ./code
1317
1318    Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
1319    Record (LBR) to record call chains. While this is not strictly required,
1320    it provides better call information, which improves the accuracy of
1321    the profile data.
1322
1323 3. Convert the collected profile data to LLVM's sample profile format.
1324    This is currently supported via the AutoFDO converter ``create_llvm_prof``.
1325    It is available at http://github.com/google/autofdo. Once built and
1326    installed, you can convert the ``perf.data`` file to LLVM using
1327    the command:
1328
1329    .. code-block:: console
1330
1331      $ create_llvm_prof --binary=./code --out=code.prof
1332
1333    This will read ``perf.data`` and the binary file ``./code`` and emit
1334    the profile data in ``code.prof``. Note that if you ran ``perf``
1335    without the ``-b`` flag, you need to use ``--use_lbr=false`` when
1336    calling ``create_llvm_prof``.
1337
1338 4. Build the code again using the collected profile. This step feeds
1339    the profile back to the optimizers. This should result in a binary
1340    that executes faster than the original one. Note that you are not
1341    required to build the code with the exact same arguments that you
1342    used in the first step. The only requirement is that you build the code
1343    with ``-gline-tables-only`` and ``-fprofile-sample-use``.
1344
1345    .. code-block:: console
1346
1347      $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
1348
1349
1350 Sample Profile Formats
1351 """"""""""""""""""""""
1352
1353 Since external profilers generate profile data in a variety of custom formats,
1354 the data generated by the profiler must be converted into a format that can be
1355 read by the backend. LLVM supports three different sample profile formats:
1356
1357 1. ASCII text. This is the easiest one to generate. The file is divided into
1358    sections, which correspond to each of the functions with profile
1359    information. The format is described below. It can also be generated from
1360    the binary or gcov formats using the ``llvm-profdata`` tool.
1361
1362 2. Binary encoding. This uses a more efficient encoding that yields smaller
1363    profile files. This is the format generated by the ``create_llvm_prof`` tool
1364    in http://github.com/google/autofdo.
1365
1366 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
1367    is only interesting in environments where GCC and Clang co-exist. This
1368    encoding is only generated by the ``create_gcov`` tool in
1369    http://github.com/google/autofdo. It can be read by LLVM and
1370    ``llvm-profdata``, but it cannot be generated by either.
1371
1372 If you are using Linux Perf to generate sampling profiles, you can use the
1373 conversion tool ``create_llvm_prof`` described in the previous section.
1374 Otherwise, you will need to write a conversion tool that converts your
1375 profiler's native format into one of these three.
1376
1377
1378 Sample Profile Text Format
1379 """"""""""""""""""""""""""
1380
1381 This section describes the ASCII text format for sampling profiles. It is,
1382 arguably, the easiest one to generate. If you are interested in generating any
1383 of the other two, consult the ``ProfileData`` library in in LLVM's source tree
1384 (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
1385
1386 .. code-block:: console
1387
1388     function1:total_samples:total_head_samples
1389      offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
1390      offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
1391      ...
1392      offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
1393      offsetA[.discriminator]: fnA:num_of_total_samples
1394       offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
1395       offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
1396       offsetB[.discriminator]: fnB:num_of_total_samples
1397        offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
1398
1399 This is a nested tree in which the identation represents the nesting level
1400 of the inline stack. There are no blank lines in the file. And the spacing
1401 within a single line is fixed. Additional spaces will result in an error
1402 while reading the file.
1403
1404 Any line starting with the '#' character is completely ignored.
1405
1406 Inlined calls are represented with indentation. The Inline stack is a
1407 stack of source locations in which the top of the stack represents the
1408 leaf function, and the bottom of the stack represents the actual
1409 symbol to which the instruction belongs.
1410
1411 Function names must be mangled in order for the profile loader to
1412 match them in the current translation unit. The two numbers in the
1413 function header specify how many total samples were accumulated in the
1414 function (first number), and the total number of samples accumulated
1415 in the prologue of the function (second number). This head sample
1416 count provides an indicator of how frequently the function is invoked.
1417
1418 There are two types of lines in the function body.
1419
1420 -  Sampled line represents the profile information of a source location.
1421    ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
1422
1423 -  Callsite line represents the profile information of an inlined callsite.
1424    ``offsetA[.discriminator]: fnA:num_of_total_samples``
1425
1426 Each sampled line may contain several items. Some are optional (marked
1427 below):
1428
1429 a. Source line offset. This number represents the line number
1430    in the function where the sample was collected. The line number is
1431    always relative to the line where symbol of the function is
1432    defined. So, if the function has its header at line 280, the offset
1433    13 is at line 293 in the file.
1434
1435    Note that this offset should never be a negative number. This could
1436    happen in cases like macros. The debug machinery will register the
1437    line number at the point of macro expansion. So, if the macro was
1438    expanded in a line before the start of the function, the profile
1439    converter should emit a 0 as the offset (this means that the optimizers
1440    will not be able to associate a meaningful weight to the instructions
1441    in the macro).
1442
1443 b. [OPTIONAL] Discriminator. This is used if the sampled program
1444    was compiled with DWARF discriminator support
1445    (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
1446    DWARF discriminators are unsigned integer values that allow the
1447    compiler to distinguish between multiple execution paths on the
1448    same source line location.
1449
1450    For example, consider the line of code ``if (cond) foo(); else bar();``.
1451    If the predicate ``cond`` is true 80% of the time, then the edge
1452    into function ``foo`` should be considered to be taken most of the
1453    time. But both calls to ``foo`` and ``bar`` are at the same source
1454    line, so a sample count at that line is not sufficient. The
1455    compiler needs to know which part of that line is taken more
1456    frequently.
1457
1458    This is what discriminators provide. In this case, the calls to
1459    ``foo`` and ``bar`` will be at the same line, but will have
1460    different discriminator values. This allows the compiler to correctly
1461    set edge weights into ``foo`` and ``bar``.
1462
1463 c. Number of samples. This is an integer quantity representing the
1464    number of samples collected by the profiler at this source
1465    location.
1466
1467 d. [OPTIONAL] Potential call targets and samples. If present, this
1468    line contains a call instruction. This models both direct and
1469    number of samples. For example,
1470
1471    .. code-block:: console
1472
1473      130: 7  foo:3  bar:2  baz:7
1474
1475    The above means that at relative line offset 130 there is a call
1476    instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
1477    with ``baz()`` being the relatively more frequently called target.
1478
1479 As an example, consider a program with the call chain ``main -> foo -> bar``.
1480 When built with optimizations enabled, the compiler may inline the
1481 calls to ``bar`` and ``foo`` inside ``main``. The generated profile
1482 could then be something like this:
1483
1484 .. code-block:: console
1485
1486     main:35504:0
1487     1: _Z3foov:35504
1488       2: _Z32bari:31977
1489       1.1: 31977
1490     2: 0
1491
1492 This profile indicates that there were a total of 35,504 samples
1493 collected in main. All of those were at line 1 (the call to ``foo``).
1494 Of those, 31,977 were spent inside the body of ``bar``. The last line
1495 of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
1496 samples were collected there.
1497
1498 Profiling with Instrumentation
1499 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1500
1501 Clang also supports profiling via instrumentation. This requires building a
1502 special instrumented version of the code and has some runtime
1503 overhead during the profiling, but it provides more detailed results than a
1504 sampling profiler. It also provides reproducible results, at least to the
1505 extent that the code behaves consistently across runs.
1506
1507 Here are the steps for using profile guided optimization with
1508 instrumentation:
1509
1510 1. Build an instrumented version of the code by compiling and linking with the
1511    ``-fprofile-instr-generate`` option.
1512
1513    .. code-block:: console
1514
1515      $ clang++ -O2 -fprofile-instr-generate code.cc -o code
1516
1517 2. Run the instrumented executable with inputs that reflect the typical usage.
1518    By default, the profile data will be written to a ``default.profraw`` file
1519    in the current directory. You can override that default by using option
1520    ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE`` 
1521    environment variable to specify an alternate file. If non-default file name
1522    is specified by both the environment variable and the command line option,
1523    the environment variable takes precedence. The file name pattern specified
1524    can include different modifiers: ``%p``, ``%h``, and ``%m``.
1525
1526    Any instance of ``%p`` in that file name will be replaced by the process
1527    ID, so that you can easily distinguish the profile output from multiple
1528    runs.
1529
1530    .. code-block:: console
1531
1532      $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
1533
1534    The modifier ``%h`` can be used in scenarios where the same instrumented
1535    binary is run in multiple different host machines dumping profile data
1536    to a shared network based storage. The ``%h`` specifier will be substituted
1537    with the hostname so that profiles collected from different hosts do not
1538    clobber each other.
1539
1540    While the use of ``%p`` specifier can reduce the likelihood for the profiles
1541    dumped from different processes to clobber each other, such clobbering can still
1542    happen because of the ``pid`` re-use by the OS. Another side-effect of using
1543    ``%p`` is that the storage requirement for raw profile data files is greatly
1544    increased.  To avoid issues like this, the ``%m`` specifier can used in the profile
1545    name.  When this specifier is used, the profiler runtime will substitute ``%m``
1546    with a unique integer identifier associated with the instrumented binary. Additionally,
1547    multiple raw profiles dumped from different processes that share a file system (can be
1548    on different hosts) will be automatically merged by the profiler runtime during the
1549    dumping. If the program links in multiple instrumented shared libraries, each library
1550    will dump the profile data into its own profile data file (with its unique integer
1551    id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
1552    profile data generated by profiler runtime. The resulting merged "raw" profile data
1553    file still needs to be converted to a different format expected by the compiler (
1554    see step 3 below).
1555
1556    .. code-block:: console
1557
1558      $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
1559
1560
1561 3. Combine profiles from multiple runs and convert the "raw" profile format to
1562    the input expected by clang. Use the ``merge`` command of the
1563    ``llvm-profdata`` tool to do this.
1564
1565    .. code-block:: console
1566
1567      $ llvm-profdata merge -output=code.profdata code-*.profraw
1568
1569    Note that this step is necessary even when there is only one "raw" profile,
1570    since the merge operation also changes the file format.
1571
1572 4. Build the code again using the ``-fprofile-instr-use`` option to specify the
1573    collected profile data.
1574
1575    .. code-block:: console
1576
1577      $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
1578
1579    You can repeat step 4 as often as you like without regenerating the
1580    profile. As you make changes to your code, clang may no longer be able to
1581    use the profile data. It will warn you when this happens.
1582
1583 Profile generation using an alternative instrumentation method can be
1584 controlled by the GCC-compatible flags ``-fprofile-generate`` and
1585 ``-fprofile-use``. Although these flags are semantically equivalent to
1586 their GCC counterparts, they *do not* handle GCC-compatible profiles.
1587 They are only meant to implement GCC's semantics with respect to
1588 profile creation and use.
1589
1590 .. option:: -fprofile-generate[=<dirname>]
1591
1592   The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
1593   an alterantive instrumentation method for profile generation. When
1594   given a directory name, it generates the profile file
1595   ``default_%m.profraw`` in the directory named ``dirname`` if specified.
1596   If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
1597   will be substibuted with a unique id documented in step 2 above. In other words,
1598   with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
1599   merging is turned on by default, so there will no longer any risk of profile
1600   clobbering from different running processes.  For example,
1601
1602   .. code-block:: console
1603
1604     $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
1605
1606   When ``code`` is executed, the profile will be written to the file
1607   ``yyy/zzz/default_xxxx.profraw``.
1608
1609   To generate the profile data file with the compiler readable format, the 
1610   ``llvm-profdata`` tool can be used with the profile directory as the input:
1611
1612    .. code-block:: console
1613
1614      $ llvm-profdata merge -output=code.profdata yyy/zzz/
1615
1616  If the user wants to turn off the auto-merging feature, or simply override the
1617  the profile dumping path specified at command line, the environment variable
1618  ``LLVM_PROFILE_FILE`` can still be used to override
1619  the directory and filename for the profile file at runtime.
1620
1621 .. option:: -fprofile-use[=<pathname>]
1622
1623   Without any other arguments, ``-fprofile-use`` behaves identically to
1624   ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
1625   profile file, it reads from that file. If ``pathname`` is a directory name,
1626   it reads from ``pathname/default.profdata``.
1627
1628 Disabling Instrumentation
1629 ^^^^^^^^^^^^^^^^^^^^^^^^^
1630
1631 In certain situations, it may be useful to disable profile generation or use
1632 for specific files in a build, without affecting the main compilation flags
1633 used for the other files in the project.
1634
1635 In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
1636 ``-fno-profile-generate``) to disable profile generation, and
1637 ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
1638
1639 Note that these flags should appear after the corresponding profile
1640 flags to have an effect.
1641
1642 Controlling Debug Information
1643 -----------------------------
1644
1645 Controlling Size of Debug Information
1646 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1647
1648 Debug info kind generated by Clang can be set by one of the flags listed
1649 below. If multiple flags are present, the last one is used.
1650
1651 .. option:: -g0
1652
1653   Don't generate any debug info (default).
1654
1655 .. option:: -gline-tables-only
1656
1657   Generate line number tables only.
1658
1659   This kind of debug info allows to obtain stack traces with function names,
1660   file names and line numbers (by such tools as ``gdb`` or ``addr2line``).  It
1661   doesn't contain any other data (e.g. description of local variables or
1662   function parameters).
1663
1664 .. option:: -fstandalone-debug
1665
1666   Clang supports a number of optimizations to reduce the size of debug
1667   information in the binary. They work based on the assumption that
1668   the debug type information can be spread out over multiple
1669   compilation units.  For instance, Clang will not emit type
1670   definitions for types that are not needed by a module and could be
1671   replaced with a forward declaration.  Further, Clang will only emit
1672   type info for a dynamic C++ class in the module that contains the
1673   vtable for the class.
1674
1675   The **-fstandalone-debug** option turns off these optimizations.
1676   This is useful when working with 3rd-party libraries that don't come
1677   with debug information.  Note that Clang will never emit type
1678   information for types that are not referenced at all by the program.
1679
1680 .. option:: -fno-standalone-debug
1681
1682    On Darwin **-fstandalone-debug** is enabled by default. The
1683    **-fno-standalone-debug** option can be used to get to turn on the
1684    vtable-based optimization described above.
1685
1686 .. option:: -g
1687
1688   Generate complete debug info.
1689
1690 Controlling Debugger "Tuning"
1691 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1692
1693 While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
1694 different debuggers may know how to take advantage of different specific DWARF
1695 features. You can "tune" the debug info for one of several different debuggers.
1696
1697 .. option:: -ggdb, -glldb, -gsce
1698
1699   Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg|
1700   debugger, respectively. Each of these options implies **-g**. (Therefore, if
1701   you want both **-gline-tables-only** and debugger tuning, the tuning option
1702   must come first.)
1703
1704
1705 Comment Parsing Options
1706 -----------------------
1707
1708 Clang parses Doxygen and non-Doxygen style documentation comments and attaches
1709 them to the appropriate declaration nodes.  By default, it only parses
1710 Doxygen-style comments and ignores ordinary comments starting with ``//`` and
1711 ``/*``.
1712
1713 .. option:: -Wdocumentation
1714
1715   Emit warnings about use of documentation comments.  This warning group is off
1716   by default.
1717
1718   This includes checking that ``\param`` commands name parameters that actually
1719   present in the function signature, checking that ``\returns`` is used only on
1720   functions that actually return a value etc.
1721
1722 .. option:: -Wno-documentation-unknown-command
1723
1724   Don't warn when encountering an unknown Doxygen command.
1725
1726 .. option:: -fparse-all-comments
1727
1728   Parse all comments as documentation comments (including ordinary comments
1729   starting with ``//`` and ``/*``).
1730
1731 .. option:: -fcomment-block-commands=[commands]
1732
1733   Define custom documentation commands as block commands.  This allows Clang to
1734   construct the correct AST for these custom commands, and silences warnings
1735   about unknown commands.  Several commands must be separated by a comma
1736   *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
1737   custom commands ``\foo`` and ``\bar``.
1738
1739   It is also possible to use ``-fcomment-block-commands`` several times; e.g.
1740   ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
1741   as above.
1742
1743 .. _c:
1744
1745 C Language Features
1746 ===================
1747
1748 The support for standard C in clang is feature-complete except for the
1749 C99 floating-point pragmas.
1750
1751 Extensions supported by clang
1752 -----------------------------
1753
1754 See :doc:`LanguageExtensions`.
1755
1756 Differences between various standard modes
1757 ------------------------------------------
1758
1759 clang supports the -std option, which changes what language mode clang
1760 uses. The supported modes for C are c89, gnu89, c94, c99, gnu99, c11,
1761 gnu11, and various aliases for those modes. If no -std option is
1762 specified, clang defaults to gnu11 mode. Many C99 and C11 features are
1763 supported in earlier modes as a conforming extension, with a warning. Use
1764 ``-pedantic-errors`` to request an error if a feature from a later standard
1765 revision is used in an earlier mode.
1766
1767 Differences between all ``c*`` and ``gnu*`` modes:
1768
1769 -  ``c*`` modes define "``__STRICT_ANSI__``".
1770 -  Target-specific defines not prefixed by underscores, like "linux",
1771    are defined in ``gnu*`` modes.
1772 -  Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
1773    the -trigraphs option.
1774 -  The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
1775    the variants "``__asm__``" and "``__typeof__``" are recognized in all
1776    modes.
1777 -  The Apple "blocks" extension is recognized by default in ``gnu*`` modes
1778    on some platforms; it can be enabled in any mode with the "-fblocks"
1779    option.
1780 -  Arrays that are VLA's according to the standard, but which can be
1781    constant folded by the frontend are treated as fixed size arrays.
1782    This occurs for things like "int X[(1, 2)];", which is technically a
1783    VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
1784
1785 Differences between ``*89`` and ``*99`` modes:
1786
1787 -  The ``*99`` modes default to implementing "inline" as specified in C99,
1788    while the ``*89`` modes implement the GNU version. This can be
1789    overridden for individual functions with the ``__gnu_inline__``
1790    attribute.
1791 -  Digraphs are not recognized in c89 mode.
1792 -  The scope of names defined inside a "for", "if", "switch", "while",
1793    or "do" statement is different. (example: "``if ((struct x {int
1794    x;}*)0) {}``".)
1795 -  ``__STDC_VERSION__`` is not defined in ``*89`` modes.
1796 -  "inline" is not recognized as a keyword in c89 mode.
1797 -  "restrict" is not recognized as a keyword in ``*89`` modes.
1798 -  Commas are allowed in integer constant expressions in ``*99`` modes.
1799 -  Arrays which are not lvalues are not implicitly promoted to pointers
1800    in ``*89`` modes.
1801 -  Some warnings are different.
1802
1803 Differences between ``*99`` and ``*11`` modes:
1804
1805 -  Warnings for use of C11 features are disabled.
1806 -  ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
1807
1808 c94 mode is identical to c89 mode except that digraphs are enabled in
1809 c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
1810
1811 GCC extensions not implemented yet
1812 ----------------------------------
1813
1814 clang tries to be compatible with gcc as much as possible, but some gcc
1815 extensions are not implemented yet:
1816
1817 -  clang does not support decimal floating point types (``_Decimal32`` and
1818    friends) or fixed-point types (``_Fract`` and friends); nobody has
1819    expressed interest in these features yet, so it's hard to say when
1820    they will be implemented.
1821 -  clang does not support nested functions; this is a complex feature
1822    which is infrequently used, so it is unlikely to be implemented
1823    anytime soon. In C++11 it can be emulated by assigning lambda
1824    functions to local variables, e.g:
1825
1826    .. code-block:: cpp
1827
1828      auto const local_function = [&](int parameter) {
1829        // Do something
1830      };
1831      ...
1832      local_function(1);
1833
1834 -  clang only supports global register variables when the register specified
1835    is non-allocatable (e.g. the stack pointer). Support for general global
1836    register variables is unlikely to be implemented soon because it requires
1837    additional LLVM backend support.
1838 -  clang does not support static initialization of flexible array
1839    members. This appears to be a rarely used extension, but could be
1840    implemented pending user demand.
1841 -  clang does not support
1842    ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
1843    used rarely, but in some potentially interesting places, like the
1844    glibc headers, so it may be implemented pending user demand. Note
1845    that because clang pretends to be like GCC 4.2, and this extension
1846    was introduced in 4.3, the glibc headers will not try to use this
1847    extension with clang at the moment.
1848 -  clang does not support the gcc extension for forward-declaring
1849    function parameters; this has not shown up in any real-world code
1850    yet, though, so it might never be implemented.
1851
1852 This is not a complete list; if you find an unsupported extension
1853 missing from this list, please send an e-mail to cfe-dev. This list
1854 currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
1855 list does not include bugs in mostly-implemented features; please see
1856 the `bug
1857 tracker <http://llvm.org/bugs/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
1858 for known existing bugs (FIXME: Is there a section for bug-reporting
1859 guidelines somewhere?).
1860
1861 Intentionally unsupported GCC extensions
1862 ----------------------------------------
1863
1864 -  clang does not support the gcc extension that allows variable-length
1865    arrays in structures. This is for a few reasons: one, it is tricky to
1866    implement, two, the extension is completely undocumented, and three,
1867    the extension appears to be rarely used. Note that clang *does*
1868    support flexible array members (arrays with a zero or unspecified
1869    size at the end of a structure).
1870 -  clang does not have an equivalent to gcc's "fold"; this means that
1871    clang doesn't accept some constructs gcc might accept in contexts
1872    where a constant expression is required, like "x-x" where x is a
1873    variable.
1874 -  clang does not support ``__builtin_apply`` and friends; this extension
1875    is extremely obscure and difficult to implement reliably.
1876
1877 .. _c_ms:
1878
1879 Microsoft extensions
1880 --------------------
1881
1882 clang has support for many extensions from Microsoft Visual C++. To enable these
1883 extensions, use the ``-fms-extensions`` command-line option. This is the default
1884 for Windows targets. Clang does not implement every pragma or declspec provided
1885 by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
1886 comment(lib)`` are well supported.
1887
1888 clang has a ``-fms-compatibility`` flag that makes clang accept enough
1889 invalid C++ to be able to parse most Microsoft headers. For example, it
1890 allows `unqualified lookup of dependent base class members
1891 <http://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
1892 a common compatibility issue with clang. This flag is enabled by default
1893 for Windows targets.
1894
1895 ``-fdelayed-template-parsing`` lets clang delay parsing of function template
1896 definitions until the end of a translation unit. This flag is enabled by
1897 default for Windows targets.
1898
1899 For compatibility with existing code that compiles with MSVC, clang defines the
1900 ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
1901 and 180000000 respectively, making clang look like an early release of Visual
1902 C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values.  It
1903 accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
1904 compatibility version makes clang behave more like that version of MSVC. For
1905 example, ``-fms-compatibility-version=19`` will enable C++14 features and define
1906 ``char16_t`` and ``char32_t`` as builtin types.
1907
1908 .. _cxx:
1909
1910 C++ Language Features
1911 =====================
1912
1913 clang fully implements all of standard C++98 except for exported
1914 templates (which were removed in C++11), and all of standard C++11
1915 and the current draft standard for C++1y.
1916
1917 Controlling implementation limits
1918 ---------------------------------
1919
1920 .. option:: -fbracket-depth=N
1921
1922   Sets the limit for nested parentheses, brackets, and braces to N.  The
1923   default is 256.
1924
1925 .. option:: -fconstexpr-depth=N
1926
1927   Sets the limit for recursive constexpr function invocations to N.  The
1928   default is 512.
1929
1930 .. option:: -ftemplate-depth=N
1931
1932   Sets the limit for recursively nested template instantiations to N.  The
1933   default is 256.
1934
1935 .. option:: -foperator-arrow-depth=N
1936
1937   Sets the limit for iterative calls to 'operator->' functions to N.  The
1938   default is 256.
1939
1940 .. _objc:
1941
1942 Objective-C Language Features
1943 =============================
1944
1945 .. _objcxx:
1946
1947 Objective-C++ Language Features
1948 ===============================
1949
1950 .. _openmp:
1951
1952 OpenMP Features
1953 ===============
1954
1955 Clang supports all OpenMP 3.1 directives and clauses.  In addition, some
1956 features of OpenMP 4.0 are supported.  For example, ``#pragma omp simd``,
1957 ``#pragma omp for simd``, ``#pragma omp parallel for simd`` directives, extended
1958 set of atomic constructs, ``proc_bind`` clause for all parallel-based
1959 directives, ``depend`` clause for ``#pragma omp task`` directive (except for
1960 array sections), ``#pragma omp cancel`` and ``#pragma omp cancellation point``
1961 directives, and ``#pragma omp taskgroup`` directive.
1962
1963 Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
1964 `-fno-openmp`.
1965
1966 Controlling implementation limits
1967 ---------------------------------
1968
1969 .. option:: -fopenmp-use-tls
1970
1971  Controls code generation for OpenMP threadprivate variables. In presence of
1972  this option all threadprivate variables are generated the same way as thread
1973  local variables, using TLS support. If `-fno-openmp-use-tls`
1974  is provided or target does not support TLS, code generation for threadprivate
1975  variables relies on OpenMP runtime library.
1976
1977 .. _opencl:
1978
1979 OpenCL Features
1980 ===============
1981
1982 Clang can be used to compile OpenCL kernels for execution on a device
1983 (e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMD or
1984 Nvidia targets) that can be uploaded to run directly on a device (e.g. using
1985 `clCreateProgramWithBinary
1986 <https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
1987 into generic bitcode files loadable into other toolchains.
1988
1989 Compiling to a binary using the default target from the installation can be done
1990 as follows:
1991
1992    .. code-block:: console
1993
1994      $ echo "kernel void k(){}" > test.cl
1995      $ clang test.cl
1996
1997 Compiling for a specific target can be done by specifying the triple corresponding
1998 to the target, for example:
1999
2000    .. code-block:: console
2001
2002      $ clang -target nvptx64-unknown-unknown test.cl
2003      $ clang -target amdgcn-amd-amdhsa-opencl test.cl
2004
2005 Compiling to bitcode can be done as follows:
2006
2007    .. code-block:: console
2008
2009      $ clang -c -emit-llvm test.cl
2010
2011 This will produce a generic test.bc file that can be used in vendor toolchains
2012 to perform machine code generation.
2013
2014 Clang currently supports OpenCL C language standards up to v2.0.
2015
2016 OpenCL Specific Options
2017 -----------------------
2018
2019 Most of the OpenCL build options from `the specification v2.0 section 5.8.4
2020 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
2021
2022 Examples:
2023
2024    .. code-block:: console
2025
2026      $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
2027
2028 Some extra options are available to support special OpenCL features.
2029
2030 .. option:: -finclude-default-header
2031
2032 Loads standard includes during compilations. By default OpenCL headers are not
2033 loaded and therefore standard library includes are not available. To load them
2034 automatically a flag has been added to the frontend (see also :ref:`the section
2035 on the OpenCL Header <opencl_header>`):
2036
2037    .. code-block:: console
2038
2039      $ clang -Xclang -finclude-default-header test.cl
2040
2041 Alternatively ``-include`` or ``-I`` followed by the path to the header location
2042 can be given manually.
2043
2044    .. code-block:: console
2045
2046      $ clang -I<path to clang>/lib/Headers/opencl-c.h test.cl
2047
2048 In this case the kernel code should contain ``#include <opencl-c.h>`` just as a
2049 regular C include.
2050
2051 .. option:: -cl-ext
2052
2053 Disables support of OpenCL extensions. All OpenCL targets provide a list
2054 of extensions that they support. Clang allows to amend this using the ``-cl-ext``
2055 flag with a comma-separated list of extensions prefixed with ``'+'`` or ``'-'``.
2056 The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``,  where extensions
2057 can be either one of `the OpenCL specification extensions
2058 <https://www.khronos.org/registry/cl/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
2059 or any known vendor extension. Alternatively, ``'all'`` can be used to enable
2060 or disable all known extensions.
2061 Example disabling double support for the 64-bit SPIR target:
2062
2063    .. code-block:: console
2064
2065      $ clang -cc1 -triple spir64-unknown-unknown -cl-ext=-cl_khr_fp64 test.cl
2066
2067 Enabling all extensions except double support in R600 AMD GPU can be done using:
2068
2069    .. code-block:: console
2070
2071      $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl
2072
2073 .. _opencl_fake_address_space_map:
2074
2075 .. option:: -ffake-address-space-map
2076
2077 Overrides the target address space map with a fake map.
2078 This allows adding explicit address space IDs to the bitcode for non-segmented
2079 memory architectures that don't have separate IDs for each of the OpenCL
2080 logical address spaces by default. Passing ``-ffake-address-space-map`` will
2081 add/override address spaces of the target compiled for with the following values:
2082 ``1-global``, ``2-constant``, ``3-local``, ``4-generic``. The private address
2083 space is represented by the absence of an address space attribute in the IR (see
2084 also :ref:`the section on the address space attribute <opencl_addrsp>`).
2085
2086    .. code-block:: console
2087
2088      $ clang -ffake-address-space-map test.cl
2089
2090 Some other flags used for the compilation for C can also be passed while
2091 compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
2092
2093 OpenCL Targets
2094 --------------
2095
2096 OpenCL targets are derived from the regular Clang target classes. The OpenCL
2097 specific parts of the target representation provide address space mapping as
2098 well as a set of supported extensions.
2099
2100 Specific Targets
2101 ^^^^^^^^^^^^^^^^
2102
2103 There is a set of concrete HW architectures that OpenCL can be compiled for.
2104
2105 - For AMD target:
2106
2107    .. code-block:: console
2108
2109      $ clang -target amdgcn-amd-amdhsa-opencl test.cl
2110
2111 - For Nvidia architectures:
2112
2113    .. code-block:: console
2114
2115      $ clang -target nvptx64-unknown-unknown test.cl
2116
2117
2118 Generic Targets
2119 ^^^^^^^^^^^^^^^
2120
2121 - SPIR is available as a generic target to allow portable bitcode to be produced
2122   that can be used across GPU toolchains. The implementation follows `the SPIR
2123   specification <https://www.khronos.org/spir>`_. There are two flavors
2124   available for 32 and 64 bits.
2125
2126    .. code-block:: console
2127
2128     $ clang -target spir-unknown-unknown test.cl
2129     $ clang -target spir64-unknown-unknown test.cl
2130
2131   All known OpenCL extensions are supported in the SPIR targets. Clang will
2132   generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and SPIR v2.0
2133   for OpenCL v2.0.
2134
2135 - x86 is used by some implementations that are x86 compatible and currently
2136   remains for backwards compatibility (with older implementations prior to
2137   SPIR target support). For "non-SPMD" targets which cannot spawn multiple
2138   work-items on the fly using hardware, which covers practically all non-GPU
2139   devices such as CPUs and DSPs, additional processing is needed for the kernels
2140   to support multiple work-item execution. For this, a 3rd party toolchain,
2141   such as for example `POCL <http://portablecl.org/>`_, can be used.
2142
2143   This target does not support multiple memory segments and, therefore, the fake
2144   address space map can be added using the :ref:`-ffake-address-space-map
2145   <opencl_fake_address_space_map>` flag.
2146
2147 .. _opencl_header:
2148
2149 OpenCL Header
2150 -------------
2151
2152 By default Clang will not include standard headers and therefore OpenCL builtin
2153 functions and some types (i.e. vectors) are unknown. The default CL header is,
2154 however, provided in the Clang installation and can be enabled by passing the
2155 ``-finclude-default-header`` flag to the Clang frontend.
2156
2157    .. code-block:: console
2158
2159      $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
2160      $ clang -Xclang -finclude-default-header -cl-std=CL2.0 test.cl
2161
2162 Because the header is very large and long to parse, PCH (:doc:`PCHInternals`)
2163 and modules (:doc:`Modules`) are used internally to improve the compilation
2164 speed.
2165
2166 To enable modules for OpenCL:
2167
2168    .. code-block:: console
2169
2170      $ clang -target spir-unknown-unknown -c -emit-llvm -Xclang -finclude-default-header -fmodules -fimplicit-module-maps -fmodules-cache-path=<path to the generated module> test.cl
2171
2172 OpenCL Metadata
2173 ---------------
2174
2175 Clang uses metadata to provide additional OpenCL semantics in IR needed for
2176 backends and OpenCL runtime.
2177
2178 Each kernel will have function metadata attached to it, specifying the arguments.
2179 Kernel argument metadata is used to provide source level information for querying
2180 at runtime, for example using the `clGetKernelArgInfo 
2181 <https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf#167>`_
2182 call.
2183
2184 Note that ``-cl-kernel-arg-info`` enables more information about the original CL
2185 code to be added e.g. kernel parameter names will appear in the OpenCL metadata
2186 along with other information. 
2187
2188 The IDs used to encode the OpenCL's logical address spaces in the argument info
2189 metadata follows the SPIR address space mapping as defined in the SPIR
2190 specification `section 2.2
2191 <https://www.khronos.org/registry/spir/specs/spir_spec-2.0.pdf#18>`_
2192
2193 OpenCL-Specific Attributes
2194 --------------------------
2195
2196 OpenCL support in Clang contains a set of attribute taken directly from the
2197 specification as well as additional attributes.
2198
2199 See also :doc:`AttributeReference`.
2200
2201 nosvm
2202 ^^^^^
2203
2204 Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
2205 does not have any effect on the IR. For more details reffer to the specification
2206 `section 6.7.2
2207 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
2208
2209
2210 opencl_hint_unroll
2211 ^^^^^^^^^^^^^^^^^^
2212
2213 The implementation of this feature mirrors the unroll hint for C.
2214 More details on the syntax can be found in the specification
2215 `section 6.11.5
2216 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
2217
2218 convergent
2219 ^^^^^^^^^^
2220
2221 To make sure no invalid optimizations occur for single program multiple data
2222 (SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
2223 can be used for special functions that have cross work item semantics.
2224 An example is the subgroup operations such as `intel_sub_group_shuffle 
2225 <https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
2226
2227    .. code-block:: c
2228
2229      // Define custom my_sub_group_shuffle(data, c)
2230      // that makes use of intel_sub_group_shuffle
2231      r1 = … 
2232      if (r0) r1 = computeA();
2233      // Shuffle data from r1 into r3
2234      // of threads id r2.
2235      r3 = my_sub_group_shuffle(r1, r2);
2236      if (r0) r3 = computeB();
2237
2238 with non-SPMD semantics this is optimized to the following equivalent code:
2239
2240    .. code-block:: c
2241
2242      r1 = …
2243      if (!r0)
2244        // Incorrect functionality! The data in r1
2245        // have not been computed by all threads yet.
2246        r3 = my_sub_group_shuffle(r1, r2);
2247      else {
2248        r1 = computeA();
2249        r3 = my_sub_group_shuffle(r1, r2);
2250        r3 = computeB();
2251      }
2252
2253 Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
2254 would prevent this:
2255
2256    .. code-block:: c
2257
2258      my_sub_group_shuffle() __attribute__((convergent));
2259
2260 Using ``convergent`` guarantees correct execution by keeping CFG equivalence
2261 wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
2262 node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
2263 respect to ``Ni`` remain the same in both ``G`` and ``G´``. 
2264
2265 noduplicate
2266 ^^^^^^^^^^^
2267
2268 ``noduplicate`` is more restrictive with respect to optimizations than
2269 ``convergent`` because a convergent function only preserves CFG equivalence.
2270 This allows some optimizations to happen as long as the control flow remains
2271 unmodified.
2272
2273    .. code-block:: c
2274
2275      for (int i=0; i<4; i++)
2276        my_sub_group_shuffle()
2277
2278 can be modified to:
2279
2280    .. code-block:: c
2281
2282      my_sub_group_shuffle();
2283      my_sub_group_shuffle();
2284      my_sub_group_shuffle();
2285      my_sub_group_shuffle();
2286
2287 while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
2288 have the same safe semantics of CFG as ``convergent`` and can cause changes in
2289 CFG that modify semantics of the original program.
2290
2291 ``noduplicate`` is kept for backwards compatibility only and it considered to be
2292 deprecated for future uses.
2293
2294 .. _opencl_addrsp:
2295
2296 address_space
2297 ^^^^^^^^^^^^^
2298
2299 Clang has arbitrary address space support using the ``address_space(N)``
2300 attribute, where ``N`` is an integer number in the range ``0`` to ``16777215``
2301 (``0xffffffu``).
2302
2303 An OpenCL implementation provides a list of standard address spaces using
2304 keywords: ``private``, ``local``, ``global``, and ``generic``. In the AST and
2305 in the IR local, global, or generic will be represented by the address space
2306 attribute with the corresponding unique number. Note that private does not have
2307 any corresponding attribute added and, therefore, is represented by the absence
2308 of an address space number. The specific IDs for an address space do not have to
2309 match between the AST and the IR. Typically in the AST address space numbers
2310 represent logical segments while in the IR they represent physical segments.
2311 Therefore, machines with flat memory segments can map all AST address space
2312 numbers to the same physical segment ID or skip address space attribute
2313 completely while generating the IR. However, if the address space information
2314 is needed by the IR passes e.g. to improve alias analysis, it is recommended
2315 to keep it and only lower to reflect physical memory segments in the late
2316 machine passes.
2317
2318 OpenCL builtins
2319 ---------------
2320
2321 There are some standard OpenCL functions that are implemented as Clang builtins:
2322
2323 - All pipe functions from `section 6.13.16.2/6.13.16.3
2324   <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#160>`_ of
2325   the OpenCL v2.0 kernel language specification. `
2326
2327 - Address space qualifier conversion functions ``to_global``/``to_local``/``to_private``
2328   from `section 6.13.9
2329   <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#101>`_.
2330
2331 - All the ``enqueue_kernel`` functions from `section 6.13.17.1
2332   <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#164>`_ and
2333   enqueue query functions from `section 6.13.17.5
2334   <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#171>`_.
2335
2336 .. _target_features:
2337
2338 Target-Specific Features and Limitations
2339 ========================================
2340
2341 CPU Architectures Features and Limitations
2342 ------------------------------------------
2343
2344 X86
2345 ^^^
2346
2347 The support for X86 (both 32-bit and 64-bit) is considered stable on
2348 Darwin (Mac OS X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
2349 to correctly compile many large C, C++, Objective-C, and Objective-C++
2350 codebases.
2351
2352 On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
2353 Microsoft x64 calling convention. You might need to tweak
2354 ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
2355
2356 For the X86 target, clang supports the `-m16` command line
2357 argument which enables 16-bit code output. This is broadly similar to
2358 using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
2359 and the ABI remains 32-bit but the assembler emits instructions
2360 appropriate for a CPU running in 16-bit mode, with address-size and
2361 operand-size prefixes to enable 32-bit addressing and operations.
2362
2363 ARM
2364 ^^^
2365
2366 The support for ARM (specifically ARMv6 and ARMv7) is considered stable
2367 on Darwin (iOS): it has been tested to correctly compile many large C,
2368 C++, Objective-C, and Objective-C++ codebases. Clang only supports a
2369 limited number of ARM architectures. It does not yet fully support
2370 ARMv5, for example.
2371
2372 PowerPC
2373 ^^^^^^^
2374
2375 The support for PowerPC (especially PowerPC64) is considered stable
2376 on Linux and FreeBSD: it has been tested to correctly compile many
2377 large C and C++ codebases. PowerPC (32bit) is still missing certain
2378 features (e.g. PIC code on ELF platforms).
2379
2380 Other platforms
2381 ^^^^^^^^^^^^^^^
2382
2383 clang currently contains some support for other architectures (e.g. Sparc);
2384 however, significant pieces of code generation are still missing, and they
2385 haven't undergone significant testing.
2386
2387 clang contains limited support for the MSP430 embedded processor, but
2388 both the clang support and the LLVM backend support are highly
2389 experimental.
2390
2391 Other platforms are completely unsupported at the moment. Adding the
2392 minimal support needed for parsing and semantic analysis on a new
2393 platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
2394 tree. This level of support is also sufficient for conversion to LLVM IR
2395 for simple programs. Proper support for conversion to LLVM IR requires
2396 adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
2397 change soon, though. Generating assembly requires a suitable LLVM
2398 backend.
2399
2400 Operating System Features and Limitations
2401 -----------------------------------------
2402
2403 Darwin (Mac OS X)
2404 ^^^^^^^^^^^^^^^^^
2405
2406 Thread Sanitizer is not supported.
2407
2408 Windows
2409 ^^^^^^^
2410
2411 Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
2412 platforms.
2413
2414 See also :ref:`Microsoft Extensions <c_ms>`.
2415
2416 Cygwin
2417 """"""
2418
2419 Clang works on Cygwin-1.7.
2420
2421 MinGW32
2422 """""""
2423
2424 Clang works on some mingw32 distributions. Clang assumes directories as
2425 below;
2426
2427 -  ``C:/mingw/include``
2428 -  ``C:/mingw/lib``
2429 -  ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
2430
2431 On MSYS, a few tests might fail.
2432
2433 MinGW-w64
2434 """""""""
2435
2436 For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
2437 assumes as below;
2438
2439 -  ``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)``
2440 -  ``some_directory/bin/gcc.exe``
2441 -  ``some_directory/bin/clang.exe``
2442 -  ``some_directory/bin/clang++.exe``
2443 -  ``some_directory/bin/../include/c++/GCC_version``
2444 -  ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
2445 -  ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
2446 -  ``some_directory/bin/../include/c++/GCC_version/backward``
2447 -  ``some_directory/bin/../x86_64-w64-mingw32/include``
2448 -  ``some_directory/bin/../i686-w64-mingw32/include``
2449 -  ``some_directory/bin/../include``
2450
2451 This directory layout is standard for any toolchain you will find on the
2452 official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
2453
2454 Clang expects the GCC executable "gcc.exe" compiled for
2455 ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
2456
2457 `Some tests might fail <http://llvm.org/bugs/show_bug.cgi?id=9072>`_ on
2458 ``x86_64-w64-mingw32``.
2459
2460 .. _clang-cl:
2461
2462 clang-cl
2463 ========
2464
2465 clang-cl is an alternative command-line interface to Clang, designed for
2466 compatibility with the Visual C++ compiler, cl.exe.
2467
2468 To enable clang-cl to find system headers, libraries, and the linker when run
2469 from the command-line, it should be executed inside a Visual Studio Native Tools
2470 Command Prompt or a regular Command Prompt where the environment has been set
2471 up using e.g. `vcvars32.bat <http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
2472
2473 clang-cl can also be used from inside Visual Studio by using an LLVM Platform
2474 Toolset.
2475
2476 Command-Line Options
2477 --------------------
2478
2479 To be compatible with cl.exe, clang-cl supports most of the same command-line
2480 options. Those options can start with either ``/`` or ``-``. It also supports
2481 some of Clang's core options, such as the ``-W`` options.
2482
2483 Options that are known to clang-cl, but not currently supported, are ignored
2484 with a warning. For example:
2485
2486   ::
2487
2488     clang-cl.exe: warning: argument unused during compilation: '/AI'
2489
2490 To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
2491
2492 Options that are not known to clang-cl will be ignored by default. Use the
2493 ``-Werror=unknown-argument`` option in order to treat them as errors. If these
2494 options are spelled with a leading ``/``, they will be mistaken for a filename:
2495
2496   ::
2497
2498     clang-cl.exe: error: no such file or directory: '/foobar'
2499
2500 Please `file a bug <http://llvm.org/bugs/enter_bug.cgi?product=clang&component=Driver>`_
2501 for any valid cl.exe flags that clang-cl does not understand.
2502
2503 Execute ``clang-cl /?`` to see a list of supported options:
2504
2505   ::
2506
2507     CL.EXE COMPATIBILITY OPTIONS:
2508       /?                      Display available options
2509       /arch:<value>           Set architecture for code generation
2510       /Brepro-                Emit an object file which cannot be reproduced over time
2511       /Brepro                 Emit an object file which can be reproduced over time
2512       /C                      Don't discard comments when preprocessing
2513       /c                      Compile only
2514       /D <macro[=value]>      Define macro
2515       /EH<value>              Exception handling model
2516       /EP                     Disable linemarker output and preprocess to stdout
2517       /execution-charset:<value>
2518                               Runtime encoding, supports only UTF-8
2519       /E                      Preprocess to stdout
2520       /fallback               Fall back to cl.exe if clang-cl fails to compile
2521       /FA                     Output assembly code file during compilation
2522       /Fa<file or directory>  Output assembly code to this file during compilation (with /FA)
2523       /Fe<file or directory>  Set output executable file or directory (ends in / or \)
2524       /FI <value>             Include file before parsing
2525       /Fi<file>               Set preprocess output file name (with /P)
2526       /Fo<file or directory>  Set output object file, or directory (ends in / or \) (with /c)
2527       /fp:except-
2528       /fp:except
2529       /fp:fast
2530       /fp:precise
2531       /fp:strict
2532       /Fp<filename>           Set pch filename (with /Yc and /Yu)
2533       /GA                     Assume thread-local variables are defined in the executable
2534       /Gd                     Set __cdecl as a default calling convention
2535       /GF-                    Disable string pooling
2536       /GR-                    Disable emission of RTTI data
2537       /GR                     Enable emission of RTTI data
2538       /Gr                     Set __fastcall as a default calling convention
2539       /GS-                    Disable buffer security check
2540       /GS                     Enable buffer security check
2541       /Gs<value>              Set stack probe size
2542       /Gv                     Set __vectorcall as a default calling convention
2543       /Gw-                    Don't put each data item in its own section
2544       /Gw                     Put each data item in its own section
2545       /GX-                    Enable exception handling
2546       /GX                     Enable exception handling
2547       /Gy-                    Don't put each function in its own section
2548       /Gy                     Put each function in its own section
2549       /Gz                     Set __stdcall as a default calling convention
2550       /help                   Display available options
2551       /imsvc <dir>            Add directory to system include search path, as if part of %INCLUDE%
2552       /I <dir>                Add directory to include search path
2553       /J                      Make char type unsigned
2554       /LDd                    Create debug DLL
2555       /LD                     Create DLL
2556       /link <options>         Forward options to the linker
2557       /MDd                    Use DLL debug run-time
2558       /MD                     Use DLL run-time
2559       /MTd                    Use static debug run-time
2560       /MT                     Use static run-time
2561       /Od                     Disable optimization
2562       /Oi-                    Disable use of builtin functions
2563       /Oi                     Enable use of builtin functions
2564       /Os                     Optimize for size
2565       /Ot                     Optimize for speed
2566       /O<value>               Optimization level
2567       /o <file or directory>  Set output file or directory (ends in / or \)
2568       /P                      Preprocess to file
2569       /Qvec-                  Disable the loop vectorization passes
2570       /Qvec                   Enable the loop vectorization passes
2571       /showIncludes           Print info about included files to stderr
2572       /source-charset:<value> Source encoding, supports only UTF-8
2573       /std:<value>            Language standard to compile for
2574       /TC                     Treat all source files as C
2575       /Tc <filename>          Specify a C source file
2576       /TP                     Treat all source files as C++
2577       /Tp <filename>          Specify a C++ source file
2578       /utf-8                  Set source and runtime encoding to UTF-8 (default)
2579       /U <macro>              Undefine macro
2580       /vd<value>              Control vtordisp placement
2581       /vmb                    Use a best-case representation method for member pointers
2582       /vmg                    Use a most-general representation for member pointers
2583       /vmm                    Set the default most-general representation to multiple inheritance
2584       /vms                    Set the default most-general representation to single inheritance
2585       /vmv                    Set the default most-general representation to virtual inheritance
2586       /volatile:iso           Volatile loads and stores have standard semantics
2587       /volatile:ms            Volatile loads and stores have acquire and release semantics
2588       /W0                     Disable all warnings
2589       /W1                     Enable -Wall
2590       /W2                     Enable -Wall
2591       /W3                     Enable -Wall
2592       /W4                     Enable -Wall and -Wextra
2593       /Wall                   Enable -Wall and -Wextra
2594       /WX-                    Do not treat warnings as errors
2595       /WX                     Treat warnings as errors
2596       /w                      Disable all warnings
2597       /Y-                     Disable precompiled headers, overrides /Yc and /Yu
2598       /Yc<filename>           Generate a pch file for all code up to and including <filename>
2599       /Yu<filename>           Load a pch file and use it instead of all code up to and including <filename>
2600       /Z7                     Enable CodeView debug information in object files
2601       /Zc:sizedDealloc-       Disable C++14 sized global deallocation functions
2602       /Zc:sizedDealloc        Enable C++14 sized global deallocation functions
2603       /Zc:strictStrings       Treat string literals as const
2604       /Zc:threadSafeInit-     Disable thread-safe initialization of static variables
2605       /Zc:threadSafeInit      Enable thread-safe initialization of static variables
2606       /Zc:trigraphs-          Disable trigraphs (default)
2607       /Zc:trigraphs           Enable trigraphs
2608       /Zd                     Emit debug line number tables only
2609       /Zi                     Alias for /Z7. Does not produce PDBs.
2610       /Zl                     Don't mention any default libraries in the object file
2611       /Zp                     Set the default maximum struct packing alignment to 1
2612       /Zp<value>              Specify the default maximum struct packing alignment
2613       /Zs                     Syntax-check only
2614
2615     OPTIONS:
2616       -###                    Print (but do not run) the commands to run for this compilation
2617       --analyze               Run the static analyzer
2618       -fansi-escape-codes     Use ANSI escape codes for diagnostics
2619       -fcolor-diagnostics     Use colors in diagnostics
2620       -fdelayed-template-parsing
2621                               Parse templated function definitions at the end of the translation unit
2622       -fdiagnostics-absolute-paths
2623                               Print absolute paths in diagnostics
2624       -fdiagnostics-parseable-fixits
2625                               Print fix-its in machine parseable form
2626       -flto                   Enable LTO in 'full' mode
2627       -fms-compatibility-version=<value>
2628                               Dot-separated value representing the Microsoft compiler version
2629                               number to report in _MSC_VER (0 = don't define it (default))
2630       -fms-compatibility      Enable full Microsoft Visual C++ compatibility
2631       -fms-extensions         Accept some non-standard constructs supported by the Microsoft compiler
2632       -fmsc-version=<value>   Microsoft compiler version number to report in _MSC_VER
2633                               (0 = don't define it (default))
2634       -fno-delayed-template-parsing
2635                               Disable delayed template parsing
2636       -fno-sanitize-coverage=<value>
2637                               Disable specified features of coverage instrumentation for Sanitizers
2638       -fno-sanitize-recover=<value>
2639                               Disable recovery for specified sanitizers
2640       -fno-sanitize-trap=<value>
2641                               Disable trapping for specified sanitizers
2642       -fno-standalone-debug   Limit debug information produced to reduce size of debug binary
2643       -fprofile-instr-generate=<file>
2644                               Generate instrumented code to collect execution counts into <file>
2645                               (overridden by LLVM_PROFILE_FILE env var)
2646       -fprofile-instr-generate
2647                               Generate instrumented code to collect execution counts into default.profraw file
2648                               (overriden by '=' form of option or LLVM_PROFILE_FILE env var)
2649       -fprofile-instr-use=<value>
2650                               Use instrumentation data for profile-guided optimization
2651       -fsanitize-blacklist=<value>
2652                               Path to blacklist file for sanitizers
2653       -fsanitize-coverage=<value>
2654                               Specify the type of coverage instrumentation for Sanitizers
2655       -fsanitize-recover=<value>
2656                               Enable recovery for specified sanitizers
2657       -fsanitize-trap=<value> Enable trapping for specified sanitizers
2658       -fsanitize=<check>      Turn on runtime checks for various forms of undefined or suspicious
2659                               behavior. See user manual for available checks
2660       -fstandalone-debug      Emit full debug info for all types used by the program
2661       -gcodeview              Generate CodeView debug information
2662       -gline-tables-only      Emit debug line number tables only
2663       -miamcu                 Use Intel MCU ABI
2664       -mllvm <value>          Additional arguments to forward to LLVM's option processing
2665       -Qunused-arguments      Don't emit warning for unused driver arguments
2666       -R<remark>              Enable the specified remark
2667       --target=<value>        Generate code for the given target
2668       -v                      Show commands to run and use verbose output
2669       -W<warning>             Enable the specified warning
2670       -Xclang <arg>           Pass <arg> to the clang compiler
2671
2672 The /fallback Option
2673 ^^^^^^^^^^^^^^^^^^^^
2674
2675 When clang-cl is run with the ``/fallback`` option, it will first try to
2676 compile files itself. For any file that it fails to compile, it will fall back
2677 and try to compile the file by invoking cl.exe.
2678
2679 This option is intended to be used as a temporary means to build projects where
2680 clang-cl cannot successfully compile all the files. clang-cl may fail to compile
2681 a file either because it cannot generate code for some C++ feature, or because
2682 it cannot parse some Microsoft language extension.