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