• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1============================
2Clang Compiler User's Manual
3============================
4
5.. contents::
6   :local:
7
8Introduction
9============
10
11The Clang Compiler is an open-source compiler for the C family of
12programming languages, aiming to be the best in class implementation of
13these languages. Clang builds on the LLVM optimizer and code generator,
14allowing it to provide high-quality optimization and code generation
15support for many targets. For more general information, please see the
16`Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
17Site <http://llvm.org>`_.
18
19This document describes important notes about using Clang as a compiler
20for an end-user, documenting the supported features, command line
21options, etc. If you are interested in using Clang to build a tool that
22processes code, please see :doc:`InternalsManual`. If you are interested in the
23`Clang Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
24page.
25
26Clang is designed to support the C family of programming languages,
27which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
28:ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
29language-specific information, please see the corresponding language
30specific section:
31
32-  :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
33   C99 (+TC1, TC2, TC3).
34-  :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
35   variants depending on base language.
36-  :ref:`C++ Language <cxx>`
37-  :ref:`Objective C++ Language <objcxx>`
38
39In addition to these base languages and their dialects, Clang supports a
40broad variety of language extensions, which are documented in the
41corresponding language section. These extensions are provided to be
42compatible with the GCC, Microsoft, and other popular compilers as well
43as to improve functionality through Clang-specific features. The Clang
44driver and language features are intentionally designed to be as
45compatible with the GNU GCC compiler as reasonably possible, easing
46migration from GCC to Clang. In most cases, code "just works".
47Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
48to be compatible with the Visual C++ compiler, cl.exe.
49
50In addition to language specific features, Clang has a variety of
51features that depend on what CPU architecture or operating system is
52being compiled for. Please see the :ref:`Target-Specific Features and
53Limitations <target_features>` section for more details.
54
55The rest of the introduction introduces some basic :ref:`compiler
56terminology <terminology>` that is used throughout this manual and
57contains a basic :ref:`introduction to using Clang <basicusage>` as a
58command line compiler.
59
60.. _terminology:
61
62Terminology
63-----------
64
65Front end, parser, backend, preprocessor, undefined behavior,
66diagnostic, optimizer
67
68.. _basicusage:
69
70Basic Usage
71-----------
72
73Intro to how to use a C compiler for newbies.
74
75compile + link compile then link debug info enabling optimizations
76picking a language to use, defaults to C99 by default. Autosenses based
77on extension. using a makefile
78
79Command Line Options
80====================
81
82This section is generally an index into other sections. It does not go
83into depth on the ones that are covered by other sections. However, the
84first part introduces the language selection and other high level
85options like :option:`-c`, :option:`-g`, etc.
86
87Options to Control Error and Warning Messages
88---------------------------------------------
89
90.. option:: -Werror
91
92  Turn warnings into errors.
93
94.. This is in plain monospaced font because it generates the same label as
95.. -Werror, and Sphinx complains.
96
97``-Werror=foo``
98
99  Turn warning "foo" into an error.
100
101.. option:: -Wno-error=foo
102
103  Turn warning "foo" into an warning even if :option:`-Werror` is specified.
104
105.. option:: -Wfoo
106
107  Enable warning "foo".
108
109.. option:: -Wno-foo
110
111  Disable warning "foo".
112
113.. option:: -w
114
115  Disable all diagnostics.
116
117.. option:: -Weverything
118
119  :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
120
121.. option:: -pedantic
122
123  Warn on language extensions.
124
125.. option:: -pedantic-errors
126
127  Error on language extensions.
128
129.. option:: -Wsystem-headers
130
131  Enable warnings from system headers.
132
133.. option:: -ferror-limit=123
134
135  Stop emitting diagnostics after 123 errors have been produced. The default is
136  20, and the error limit can be disabled with :option:`-ferror-limit=0`.
137
138.. option:: -ftemplate-backtrace-limit=123
139
140  Only emit up to 123 template instantiation notes within the template
141  instantiation backtrace for a single warning or error. The default is 10, and
142  the limit can be disabled with :option:`-ftemplate-backtrace-limit=0`.
143
144.. _cl_diag_formatting:
145
146Formatting of Diagnostics
147^^^^^^^^^^^^^^^^^^^^^^^^^
148
149Clang aims to produce beautiful diagnostics by default, particularly for
150new users that first come to Clang. However, different people have
151different preferences, and sometimes Clang is driven by another program
152that wants to parse simple and consistent output, not a person. For
153these cases, Clang provides a wide range of options to control the exact
154output format of the diagnostics that it generates.
155
156.. _opt_fshow-column:
157
158**-f[no-]show-column**
159   Print column number in diagnostic.
160
161   This option, which defaults to on, controls whether or not Clang
162   prints the column number of a diagnostic. For example, when this is
163   enabled, Clang will print something like:
164
165   ::
166
167         test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
168         #endif bad
169                ^
170                //
171
172   When this is disabled, Clang will print "test.c:28: warning..." with
173   no column number.
174
175   The printed column numbers count bytes from the beginning of the
176   line; take care if your source contains multibyte characters.
177
178.. _opt_fshow-source-location:
179
180**-f[no-]show-source-location**
181   Print source file/line/column information in diagnostic.
182
183   This option, which defaults to on, controls whether or not Clang
184   prints the filename, line number and column number of a diagnostic.
185   For example, when this is enabled, Clang will print something like:
186
187   ::
188
189         test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
190         #endif bad
191                ^
192                //
193
194   When this is disabled, Clang will not print the "test.c:28:8: "
195   part.
196
197.. _opt_fcaret-diagnostics:
198
199**-f[no-]caret-diagnostics**
200   Print source line and ranges from source code in diagnostic.
201   This option, which defaults to on, controls whether or not Clang
202   prints the source line, source ranges, and caret when emitting a
203   diagnostic. For example, when this is enabled, Clang will print
204   something like:
205
206   ::
207
208         test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
209         #endif bad
210                ^
211                //
212
213**-f[no-]color-diagnostics**
214   This option, which defaults to on when a color-capable terminal is
215   detected, controls whether or not Clang prints diagnostics in color.
216
217   When this option is enabled, Clang will use colors to highlight
218   specific parts of the diagnostic, e.g.,
219
220   .. nasty hack to not lose our dignity
221
222   .. raw:: html
223
224       <pre>
225         <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>
226         #endif bad
227                <span style="color:green">^</span>
228                <span style="color:green">//</span>
229       </pre>
230
231   When this is disabled, Clang will just print:
232
233   ::
234
235         test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
236         #endif bad
237                ^
238                //
239
240**-fansi-escape-codes**
241   Controls whether ANSI escape codes are used instead of the Windows Console
242   API to output colored diagnostics. This option is only used on Windows and
243   defaults to off.
244
245.. option:: -fdiagnostics-format=clang/msvc/vi
246
247   Changes diagnostic output format to better match IDEs and command line tools.
248
249   This option controls the output format of the filename, line number,
250   and column printed in diagnostic messages. The options, and their
251   affect on formatting a simple conversion diagnostic, follow:
252
253   **clang** (default)
254       ::
255
256           t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
257
258   **msvc**
259       ::
260
261           t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
262
263   **vi**
264       ::
265
266           t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
267
268.. _opt_fdiagnostics-show-option:
269
270**-f[no-]diagnostics-show-option**
271   Enable ``[-Woption]`` information in diagnostic line.
272
273   This option, which defaults to on, controls whether or not Clang
274   prints the associated :ref:`warning group <cl_diag_warning_groups>`
275   option name when outputting a warning diagnostic. For example, in
276   this output:
277
278   ::
279
280         test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
281         #endif bad
282                ^
283                //
284
285   Passing **-fno-diagnostics-show-option** will prevent Clang from
286   printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
287   the diagnostic. This information tells you the flag needed to enable
288   or disable the diagnostic, either from the command line or through
289   :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
290
291.. _opt_fdiagnostics-show-category:
292
293.. option:: -fdiagnostics-show-category=none/id/name
294
295   Enable printing category information in diagnostic line.
296
297   This option, which defaults to "none", controls whether or not Clang
298   prints the category associated with a diagnostic when emitting it.
299   Each diagnostic may or many not have an associated category, if it
300   has one, it is listed in the diagnostic categorization field of the
301   diagnostic line (in the []'s).
302
303   For example, a format string warning will produce these three
304   renditions based on the setting of this option:
305
306   ::
307
308         t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
309         t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
310         t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
311
312   This category can be used by clients that want to group diagnostics
313   by category, so it should be a high level category. We want dozens
314   of these, not hundreds or thousands of them.
315
316.. _opt_fdiagnostics-fixit-info:
317
318**-f[no-]diagnostics-fixit-info**
319   Enable "FixIt" information in the diagnostics output.
320
321   This option, which defaults to on, controls whether or not Clang
322   prints the information on how to fix a specific diagnostic
323   underneath it when it knows. For example, in this output:
324
325   ::
326
327         test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
328         #endif bad
329                ^
330                //
331
332   Passing **-fno-diagnostics-fixit-info** will prevent Clang from
333   printing the "//" line at the end of the message. This information
334   is useful for users who may not understand what is wrong, but can be
335   confusing for machine parsing.
336
337.. _opt_fdiagnostics-print-source-range-info:
338
339**-fdiagnostics-print-source-range-info**
340   Print machine parsable information about source ranges.
341   This option makes Clang print information about source ranges in a machine
342   parsable format after the file/line/column number information. The
343   information is a simple sequence of brace enclosed ranges, where each range
344   lists the start and end line/column locations. For example, in this output:
345
346   ::
347
348       exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
349          P = (P-42) + Gamma*4;
350              ~~~~~~ ^ ~~~~~~~
351
352   The {}'s are generated by -fdiagnostics-print-source-range-info.
353
354   The printed column numbers count bytes from the beginning of the
355   line; take care if your source contains multibyte characters.
356
357.. option:: -fdiagnostics-parseable-fixits
358
359   Print Fix-Its in a machine parseable form.
360
361   This option makes Clang print available Fix-Its in a machine
362   parseable format at the end of diagnostics. The following example
363   illustrates the format:
364
365   ::
366
367        fix-it:"t.cpp":{7:25-7:29}:"Gamma"
368
369   The range printed is a half-open range, so in this example the
370   characters at column 25 up to but not including column 29 on line 7
371   in t.cpp should be replaced with the string "Gamma". Either the
372   range or the replacement string may be empty (representing strict
373   insertions and strict erasures, respectively). Both the file name
374   and the insertion string escape backslash (as "\\\\"), tabs (as
375   "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
376   non-printable characters (as octal "\\xxx").
377
378   The printed column numbers count bytes from the beginning of the
379   line; take care if your source contains multibyte characters.
380
381.. option:: -fno-elide-type
382
383   Turns off elision in template type printing.
384
385   The default for template type printing is to elide as many template
386   arguments as possible, removing those which are the same in both
387   template types, leaving only the differences. Adding this flag will
388   print all the template arguments. If supported by the terminal,
389   highlighting will still appear on differing arguments.
390
391   Default:
392
393   ::
394
395       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;
396
397   -fno-elide-type:
398
399   ::
400
401       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;
402
403.. option:: -fdiagnostics-show-template-tree
404
405   Template type diffing prints a text tree.
406
407   For diffing large templated types, this option will cause Clang to
408   display the templates as an indented text tree, one argument per
409   line, with differences marked inline. This is compatible with
410   -fno-elide-type.
411
412   Default:
413
414   ::
415
416       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;
417
418   With :option:`-fdiagnostics-show-template-tree`:
419
420   ::
421
422       t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
423         vector<
424           map<
425             [...],
426             map<
427               [float != double],
428               [...]>>>
429
430.. _cl_diag_warning_groups:
431
432Individual Warning Groups
433^^^^^^^^^^^^^^^^^^^^^^^^^
434
435TODO: Generate this from tblgen. Define one anchor per warning group.
436
437.. _opt_wextra-tokens:
438
439.. option:: -Wextra-tokens
440
441   Warn about excess tokens at the end of a preprocessor directive.
442
443   This option, which defaults to on, enables warnings about extra
444   tokens at the end of preprocessor directives. For example:
445
446   ::
447
448         test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
449         #endif bad
450                ^
451
452   These extra tokens are not strictly conforming, and are usually best
453   handled by commenting them out.
454
455.. option:: -Wambiguous-member-template
456
457   Warn about unqualified uses of a member template whose name resolves to
458   another template at the location of the use.
459
460   This option, which defaults to on, enables a warning in the
461   following code:
462
463   ::
464
465       template<typename T> struct set{};
466       template<typename T> struct trait { typedef const T& type; };
467       struct Value {
468         template<typename T> void set(typename trait<T>::type value) {}
469       };
470       void foo() {
471         Value v;
472         v.set<double>(3.2);
473       }
474
475   C++ [basic.lookup.classref] requires this to be an error, but,
476   because it's hard to work around, Clang downgrades it to a warning
477   as an extension.
478
479.. option:: -Wbind-to-temporary-copy
480
481   Warn about an unusable copy constructor when binding a reference to a
482   temporary.
483
484   This option, which defaults to on, enables warnings about binding a
485   reference to a temporary when the temporary doesn't have a usable
486   copy constructor. For example:
487
488   ::
489
490         struct NonCopyable {
491           NonCopyable();
492         private:
493           NonCopyable(const NonCopyable&);
494         };
495         void foo(const NonCopyable&);
496         void bar() {
497           foo(NonCopyable());  // Disallowed in C++98; allowed in C++11.
498         }
499
500   ::
501
502         struct NonCopyable2 {
503           NonCopyable2();
504           NonCopyable2(NonCopyable2&);
505         };
506         void foo(const NonCopyable2&);
507         void bar() {
508           foo(NonCopyable2());  // Disallowed in C++98; allowed in C++11.
509         }
510
511   Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
512   whose instantiation produces a compile error, that error will still
513   be a hard error in C++98 mode even if this warning is turned off.
514
515Options to Control Clang Crash Diagnostics
516------------------------------------------
517
518As unbelievable as it may sound, Clang does crash from time to time.
519Generally, this only occurs to those living on the `bleeding
520edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
521lengths to assist you in filing a bug report. Specifically, Clang
522generates preprocessed source file(s) and associated run script(s) upon
523a crash. These files should be attached to a bug report to ease
524reproducibility of the failure. Below are the command line options to
525control the crash diagnostics.
526
527.. option:: -fno-crash-diagnostics
528
529  Disable auto-generation of preprocessed source files during a clang crash.
530
531The -fno-crash-diagnostics flag can be helpful for speeding the process
532of generating a delta reduced test case.
533
534Options to Emit Optimization Reports
535------------------------------------
536
537Optimization reports trace, at a high-level, all the major decisions
538done by compiler transformations. For instance, when the inliner
539decides to inline function ``foo()`` into ``bar()``, or the loop unroller
540decides to unroll a loop N times, or the vectorizer decides to
541vectorize a loop body.
542
543Clang offers a family of flags which the optimizers can use to emit
544a diagnostic in three cases:
545
5461. When the pass makes a transformation (:option:`-Rpass`).
547
5482. When the pass fails to make a transformation (:option:`-Rpass-missed`).
549
5503. When the pass determines whether or not to make a transformation
551   (:option:`-Rpass-analysis`).
552
553NOTE: Although the discussion below focuses on :option:`-Rpass`, the exact
554same options apply to :option:`-Rpass-missed` and :option:`-Rpass-analysis`.
555
556Since there are dozens of passes inside the compiler, each of these flags
557take a regular expression that identifies the name of the pass which should
558emit the associated diagnostic. For example, to get a report from the inliner,
559compile the code with:
560
561.. code-block:: console
562
563   $ clang -O2 -Rpass=inline code.cc -o code
564   code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
565   int bar(int j) { return foo(j, j - 2); }
566                           ^
567
568Note that remarks from the inliner are identified with `[-Rpass=inline]`.
569To request a report from every optimization pass, you should use
570:option:`-Rpass=.*` (in fact, you can use any valid POSIX regular
571expression). However, do not expect a report from every transformation
572made by the compiler. Optimization remarks do not really make sense
573outside of the major transformations (e.g., inlining, vectorization,
574loop optimizations) and not every optimization pass supports this
575feature.
576
577Current limitations
578^^^^^^^^^^^^^^^^^^^
579
5801. For :option:`-Rpass` to provide column information, you
581   need to enable it explicitly. That is, you need to add
582   :option:`-gcolumn-info`. If you omit this, remarks will only show
583   line information.
584
5852. Optimization remarks that refer to function names will display the
586   mangled name of the function. Since these remarks are emitted by the
587   back end of the compiler, it does not know anything about the input
588   language, nor its mangling rules.
589
5903. Some source locations are not displayed correctly. The front end has
591   a more detailed source location tracking than the locations included
592   in the debug info (e.g., the front end can locate code inside macro
593   expansions). However, the locations used by :option:`-Rpass` are
594   translated from debug annotations. That translation can be lossy,
595   which results in some remarks having no location information.
596
597
598Language and Target-Independent Features
599========================================
600
601Controlling Errors and Warnings
602-------------------------------
603
604Clang provides a number of ways to control which code constructs cause
605it to emit errors and warning messages, and how they are displayed to
606the console.
607
608Controlling How Clang Displays Diagnostics
609^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
610
611When Clang emits a diagnostic, it includes rich information in the
612output, and gives you fine-grain control over which information is
613printed. Clang has the ability to print this information, and these are
614the options that control it:
615
616#. A file/line/column indicator that shows exactly where the diagnostic
617   occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
618   :ref:`-fshow-source-location <opt_fshow-source-location>`].
619#. A categorization of the diagnostic as a note, warning, error, or
620   fatal error.
621#. A text string that describes what the problem is.
622#. An option that indicates how to control the diagnostic (for
623   diagnostics that support it)
624   [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
625#. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
626   for clients that want to group diagnostics by class (for diagnostics
627   that support it)
628   [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
629#. The line of source code that the issue occurs on, along with a caret
630   and ranges that indicate the important locations
631   [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
632#. "FixIt" information, which is a concise explanation of how to fix the
633   problem (when Clang is certain it knows)
634   [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
635#. A machine-parsable representation of the ranges involved (off by
636   default)
637   [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
638
639For more information please see :ref:`Formatting of
640Diagnostics <cl_diag_formatting>`.
641
642Diagnostic Mappings
643^^^^^^^^^^^^^^^^^^^
644
645All diagnostics are mapped into one of these 5 classes:
646
647-  Ignored
648-  Note
649-  Remark
650-  Warning
651-  Error
652-  Fatal
653
654.. _diagnostics_categories:
655
656Diagnostic Categories
657^^^^^^^^^^^^^^^^^^^^^
658
659Though not shown by default, diagnostics may each be associated with a
660high-level category. This category is intended to make it possible to
661triage builds that produce a large number of errors or warnings in a
662grouped way.
663
664Categories are not shown by default, but they can be turned on with the
665:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
666When set to "``name``", the category is printed textually in the
667diagnostic output. When it is set to "``id``", a category number is
668printed. The mapping of category names to category id's can be obtained
669by running '``clang   --print-diagnostic-categories``'.
670
671Controlling Diagnostics via Command Line Flags
672^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
673
674TODO: -W flags, -pedantic, etc
675
676.. _pragma_gcc_diagnostic:
677
678Controlling Diagnostics via Pragmas
679^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
680
681Clang can also control what diagnostics are enabled through the use of
682pragmas in the source code. This is useful for turning off specific
683warnings in a section of source code. Clang supports GCC's pragma for
684compatibility with existing source code, as well as several extensions.
685
686The pragma may control any warning that can be used from the command
687line. Warnings may be set to ignored, warning, error, or fatal. The
688following example code will tell Clang or GCC to ignore the -Wall
689warnings:
690
691.. code-block:: c
692
693  #pragma GCC diagnostic ignored "-Wall"
694
695In addition to all of the functionality provided by GCC's pragma, Clang
696also allows you to push and pop the current warning state. This is
697particularly useful when writing a header file that will be compiled by
698other people, because you don't know what warning flags they build with.
699
700In the below example :option:`-Wmultichar` is ignored for only a single line of
701code, after which the diagnostics return to whatever state had previously
702existed.
703
704.. code-block:: c
705
706  #pragma clang diagnostic push
707  #pragma clang diagnostic ignored "-Wmultichar"
708
709  char b = 'df'; // no warning.
710
711  #pragma clang diagnostic pop
712
713The push and pop pragmas will save and restore the full diagnostic state
714of the compiler, regardless of how it was set. That means that it is
715possible to use push and pop around GCC compatible diagnostics and Clang
716will push and pop them appropriately, while GCC will ignore the pushes
717and pops as unknown pragmas. It should be noted that while Clang
718supports the GCC pragma, Clang and GCC do not support the exact same set
719of warnings, so even when using GCC compatible #pragmas there is no
720guarantee that they will have identical behaviour on both compilers.
721
722In addition to controlling warnings and errors generated by the compiler, it is
723possible to generate custom warning and error messages through the following
724pragmas:
725
726.. code-block:: c
727
728  // The following will produce warning messages
729  #pragma message "some diagnostic message"
730  #pragma GCC warning "TODO: replace deprecated feature"
731
732  // The following will produce an error message
733  #pragma GCC error "Not supported"
734
735These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
736directives, except that they may also be embedded into preprocessor macros via
737the C99 ``_Pragma`` operator, for example:
738
739.. code-block:: c
740
741  #define STR(X) #X
742  #define DEFER(M,...) M(__VA_ARGS__)
743  #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
744
745  CUSTOM_ERROR("Feature not available");
746
747Controlling Diagnostics in System Headers
748^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
749
750Warnings are suppressed when they occur in system headers. By default,
751an included file is treated as a system header if it is found in an
752include path specified by ``-isystem``, but this can be overridden in
753several ways.
754
755The ``system_header`` pragma can be used to mark the current file as
756being a system header. No warnings will be produced from the location of
757the pragma onwards within the same file.
758
759.. code-block:: c
760
761  char a = 'xy'; // warning
762
763  #pragma clang system_header
764
765  char b = 'ab'; // no warning
766
767The :option:`--system-header-prefix=` and :option:`--no-system-header-prefix=`
768command-line arguments can be used to override whether subsets of an include
769path are treated as system headers. When the name in a ``#include`` directive
770is found within a header search path and starts with a system prefix, the
771header is treated as a system header. The last prefix on the
772command-line which matches the specified header name takes precedence.
773For instance:
774
775.. code-block:: console
776
777  $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
778      --no-system-header-prefix=x/y/
779
780Here, ``#include "x/a.h"`` is treated as including a system header, even
781if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
782as not including a system header, even if the header is found in
783``bar``.
784
785A ``#include`` directive which finds a file relative to the current
786directory is treated as including a system header if the including file
787is treated as a system header.
788
789.. _diagnostics_enable_everything:
790
791Enabling All Diagnostics
792^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
793
794In addition to the traditional ``-W`` flags, one can enable **all**
795diagnostics by passing :option:`-Weverything`. This works as expected
796with
797:option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
798
799Note that when combined with :option:`-w` (which disables all warnings), that
800flag wins.
801
802Controlling Static Analyzer Diagnostics
803^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
804
805While not strictly part of the compiler, the diagnostics from Clang's
806`static analyzer <http://clang-analyzer.llvm.org>`_ can also be
807influenced by the user via changes to the source code. See the available
808`annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
809analyzer's `FAQ
810page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
811information.
812
813.. _usersmanual-precompiled-headers:
814
815Precompiled Headers
816-------------------
817
818`Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
819are a general approach employed by many compilers to reduce compilation
820time. The underlying motivation of the approach is that it is common for
821the same (and often large) header files to be included by multiple
822source files. Consequently, compile times can often be greatly improved
823by caching some of the (redundant) work done by a compiler to process
824headers. Precompiled header files, which represent one of many ways to
825implement this optimization, are literally files that represent an
826on-disk cache that contains the vital information necessary to reduce
827some of the work needed to process a corresponding header file. While
828details of precompiled headers vary between compilers, precompiled
829headers have been shown to be highly effective at speeding up program
830compilation on systems with very large system headers (e.g., Mac OS X).
831
832Generating a PCH File
833^^^^^^^^^^^^^^^^^^^^^
834
835To generate a PCH file using Clang, one invokes Clang with the
836:option:`-x <language>-header` option. This mirrors the interface in GCC
837for generating PCH files:
838
839.. code-block:: console
840
841  $ gcc -x c-header test.h -o test.h.gch
842  $ clang -x c-header test.h -o test.h.pch
843
844Using a PCH File
845^^^^^^^^^^^^^^^^
846
847A PCH file can then be used as a prefix header when a :option:`-include`
848option is passed to ``clang``:
849
850.. code-block:: console
851
852  $ clang -include test.h test.c -o test
853
854The ``clang`` driver will first check if a PCH file for ``test.h`` is
855available; if so, the contents of ``test.h`` (and the files it includes)
856will be processed from the PCH file. Otherwise, Clang falls back to
857directly processing the content of ``test.h``. This mirrors the behavior
858of GCC.
859
860.. note::
861
862  Clang does *not* automatically use PCH files for headers that are directly
863  included within a source file. For example:
864
865  .. code-block:: console
866
867    $ clang -x c-header test.h -o test.h.pch
868    $ cat test.c
869    #include "test.h"
870    $ clang test.c -o test
871
872  In this example, ``clang`` will not automatically use the PCH file for
873  ``test.h`` since ``test.h`` was included directly in the source file and not
874  specified on the command line using :option:`-include`.
875
876Relocatable PCH Files
877^^^^^^^^^^^^^^^^^^^^^
878
879It is sometimes necessary to build a precompiled header from headers
880that are not yet in their final, installed locations. For example, one
881might build a precompiled header within the build tree that is then
882meant to be installed alongside the headers. Clang permits the creation
883of "relocatable" precompiled headers, which are built with a given path
884(into the build directory) and can later be used from an installed
885location.
886
887To build a relocatable precompiled header, place your headers into a
888subdirectory whose structure mimics the installed location. For example,
889if you want to build a precompiled header for the header ``mylib.h``
890that will be installed into ``/usr/include``, create a subdirectory
891``build/usr/include`` and place the header ``mylib.h`` into that
892subdirectory. If ``mylib.h`` depends on other headers, then they can be
893stored within ``build/usr/include`` in a way that mimics the installed
894location.
895
896Building a relocatable precompiled header requires two additional
897arguments. First, pass the ``--relocatable-pch`` flag to indicate that
898the resulting PCH file should be relocatable. Second, pass
899:option:`-isysroot /path/to/build`, which makes all includes for your library
900relative to the build directory. For example:
901
902.. code-block:: console
903
904  # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
905
906When loading the relocatable PCH file, the various headers used in the
907PCH file are found from the system header root. For example, ``mylib.h``
908can be found in ``/usr/include/mylib.h``. If the headers are installed
909in some other system root, the :option:`-isysroot` option can be used provide
910a different system root from which the headers will be based. For
911example, :option:`-isysroot /Developer/SDKs/MacOSX10.4u.sdk` will look for
912``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
913
914Relocatable precompiled headers are intended to be used in a limited
915number of cases where the compilation environment is tightly controlled
916and the precompiled header cannot be generated after headers have been
917installed.
918
919Controlling Code Generation
920---------------------------
921
922Clang provides a number of ways to control code generation. The options
923are listed below.
924
925**-f[no-]sanitize=check1,check2,...**
926   Turn on runtime checks for various forms of undefined or suspicious
927   behavior.
928
929   This option controls whether Clang adds runtime checks for various
930   forms of undefined or suspicious behavior, and is disabled by
931   default. If a check fails, a diagnostic message is produced at
932   runtime explaining the problem. The main checks are:
933
934   -  .. _opt_fsanitize_address:
935
936      ``-fsanitize=address``:
937      :doc:`AddressSanitizer`, a memory error
938      detector.
939   -  ``-fsanitize=integer``: Enables checks for undefined or
940      suspicious integer behavior.
941   -  .. _opt_fsanitize_thread:
942
943      ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
944   -  .. _opt_fsanitize_memory:
945
946      ``-fsanitize=memory``: :doc:`MemorySanitizer`,
947      an *experimental* detector of uninitialized reads. Not ready for
948      widespread use.
949   -  .. _opt_fsanitize_undefined:
950
951      ``-fsanitize=undefined``: Fast and compatible undefined behavior
952      checker. Enables the undefined behavior checks that have small
953      runtime cost and no impact on address space layout or ABI. This
954      includes all of the checks listed below other than
955      ``unsigned-integer-overflow``.
956
957   -  ``-fsanitize=undefined-trap``: This includes all sanitizers
958      included by ``-fsanitize=undefined``, except those that require
959      runtime support. This group of sanitizers is intended to be
960      used in conjunction with the ``-fsanitize-undefined-trap-on-error``
961      flag. This includes all of the checks listed below other than
962      ``unsigned-integer-overflow`` and ``vptr``.
963   -  ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
964      flow analysis.
965
966   The following more fine-grained checks are also available:
967
968   -  ``-fsanitize=alignment``: Use of a misaligned pointer or creation
969      of a misaligned reference.
970   -  ``-fsanitize=bool``: Load of a ``bool`` value which is neither
971      ``true`` nor ``false``.
972   -  ``-fsanitize=bounds``: Out of bounds array indexing, in cases
973      where the array bound can be statically determined.
974   -  ``-fsanitize=enum``: Load of a value of an enumerated type which
975      is not in the range of representable values for that enumerated
976      type.
977   -  ``-fsanitize=float-cast-overflow``: Conversion to, from, or
978      between floating-point types which would overflow the
979      destination.
980   -  ``-fsanitize=float-divide-by-zero``: Floating point division by
981      zero.
982   -  ``-fsanitize=function``: Indirect call of a function through a
983      function pointer of the wrong type (Linux, C++ and x86/x86_64 only).
984   -  ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
985   -  ``-fsanitize=null``: Use of a null pointer or creation of a null
986      reference.
987   -  ``-fsanitize=object-size``: An attempt to use bytes which the
988      optimizer can determine are not part of the object being
989      accessed. The sizes of objects are determined using
990      ``__builtin_object_size``, and consequently may be able to detect
991      more problems at higher optimization levels.
992   -  ``-fsanitize=return``: In C++, reaching the end of a
993      value-returning function without returning a value.
994   -  ``-fsanitize=shift``: Shift operators where the amount shifted is
995      greater or equal to the promoted bit-width of the left hand side
996      or less than zero, or where the left hand side is negative. For a
997      signed left shift, also checks for signed overflow in C, and for
998      unsigned overflow in C++.
999   -  ``-fsanitize=signed-integer-overflow``: Signed integer overflow,
1000      including all the checks added by ``-ftrapv``, and checking for
1001      overflow in signed division (``INT_MIN / -1``).
1002   -  ``-fsanitize=unreachable``: If control flow reaches
1003      ``__builtin_unreachable``.
1004   -  ``-fsanitize=unsigned-integer-overflow``: Unsigned integer
1005      overflows.
1006   -  ``-fsanitize=vla-bound``: A variable-length array whose bound
1007      does not evaluate to a positive value.
1008   -  ``-fsanitize=vptr``: Use of an object whose vptr indicates that
1009      it is of the wrong dynamic type, or that its lifetime has not
1010      begun or has ended. Incompatible with ``-fno-rtti``.
1011
1012   You can turn off or modify checks for certain source files, functions
1013   or even variables by providing a special file:
1014
1015   -  ``-fsanitize-blacklist=/path/to/blacklist/file``: disable or modify
1016      sanitizer checks for objects listed in the file. See
1017      :doc:`SanitizerSpecialCaseList` for file format description.
1018   -  ``-fno-sanitize-blacklist``: don't use blacklist file, if it was
1019      specified earlier in the command line.
1020
1021   Extra features of MemorySanitizer (require explicit
1022   ``-fsanitize=memory``):
1023
1024   -  ``-fsanitize-memory-track-origins[=level]``: Enables origin tracking in
1025      MemorySanitizer. Adds a second section to MemorySanitizer
1026      reports pointing to the heap or stack allocation the
1027      uninitialized bits came from. Slows down execution by additional
1028      1.5x-2x.
1029
1030      Possible values for level are 0 (off), 1 (default), 2. Level 2 adds more
1031      sections to MemorySanitizer reports describing the order of memory stores
1032      the uninitialized value went through. Beware, this mode may use a lot of
1033      extra memory.
1034
1035   Extra features of UndefinedBehaviorSanitizer:
1036
1037   -  ``-fno-sanitize-recover``: By default, after a sanitizer diagnoses
1038      an issue, it will attempt to continue executing the program if there
1039      is a reasonable behavior it can give to the faulting operation. This
1040      option causes the program to abort instead.
1041   -  ``-fsanitize-undefined-trap-on-error``: Causes traps to be emitted
1042      rather than calls to runtime libraries when a problem is detected.
1043      This option is intended for use in cases where the sanitizer runtime
1044      cannot be used (for instance, when building libc or a kernel module).
1045      This is only compatible with the sanitizers in the ``undefined-trap``
1046      group.
1047
1048   The ``-fsanitize=`` argument must also be provided when linking, in
1049   order to link to the appropriate runtime library. When using
1050   ``-fsanitize=vptr`` (or a group that includes it, such as
1051   ``-fsanitize=undefined``) with a C++ program, the link must be
1052   performed by ``clang++``, not ``clang``, in order to link against the
1053   C++-specific parts of the runtime library.
1054
1055   It is not possible to combine more than one of the ``-fsanitize=address``,
1056   ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
1057   program. The ``-fsanitize=undefined`` checks can be combined with other
1058   sanitizers.
1059
1060.. option:: -fno-assume-sane-operator-new
1061
1062   Don't assume that the C++'s new operator is sane.
1063
1064   This option tells the compiler to do not assume that C++'s global
1065   new operator will always return a pointer that does not alias any
1066   other pointer when the function returns.
1067
1068.. option:: -ftrap-function=[name]
1069
1070   Instruct code generator to emit a function call to the specified
1071   function name for ``__builtin_trap()``.
1072
1073   LLVM code generator translates ``__builtin_trap()`` to a trap
1074   instruction if it is supported by the target ISA. Otherwise, the
1075   builtin is translated into a call to ``abort``. If this option is
1076   set, then the code generator will always lower the builtin to a call
1077   to the specified function regardless of whether the target ISA has a
1078   trap instruction. This option is useful for environments (e.g.
1079   deeply embedded) where a trap cannot be properly handled, or when
1080   some custom behavior is desired.
1081
1082.. option:: -ftls-model=[model]
1083
1084   Select which TLS model to use.
1085
1086   Valid values are: ``global-dynamic``, ``local-dynamic``,
1087   ``initial-exec`` and ``local-exec``. The default value is
1088   ``global-dynamic``. The compiler may use a different model if the
1089   selected model is not supported by the target, or if a more
1090   efficient model can be used. The TLS model can be overridden per
1091   variable using the ``tls_model`` attribute.
1092
1093.. option:: -mhwdiv=[values]
1094
1095   Select the ARM modes (arm or thumb) that support hardware division
1096   instructions.
1097
1098   Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
1099   This option is used to indicate which mode (arm or thumb) supports
1100   hardware division instructions. This only applies to the ARM
1101   architecture.
1102
1103.. option:: -m[no-]crc
1104
1105   Enable or disable CRC instructions.
1106
1107   This option is used to indicate whether CRC instructions are to
1108   be generated. This only applies to the ARM architecture.
1109
1110   CRC instructions are enabled by default on ARMv8.
1111
1112.. option:: -mgeneral-regs-only
1113
1114   Generate code which only uses the general purpose registers.
1115
1116   This option restricts the generated code to use general registers
1117   only. This only applies to the AArch64 architecture.
1118
1119
1120Profile Guided Optimization
1121---------------------------
1122
1123Profile information enables better optimization. For example, knowing that a
1124branch is taken very frequently helps the compiler make better decisions when
1125ordering basic blocks. Knowing that a function ``foo`` is called more
1126frequently than another function ``bar`` helps the inliner.
1127
1128Clang supports profile guided optimization with two different kinds of
1129profiling. A sampling profiler can generate a profile with very low runtime
1130overhead, or you can build an instrumented version of the code that collects
1131more detailed profile information. Both kinds of profiles can provide execution
1132counts for instructions in the code and information on branches taken and
1133function invocation.
1134
1135Regardless of which kind of profiling you use, be careful to collect profiles
1136by running your code with inputs that are representative of the typical
1137behavior. Code that is not exercised in the profile will be optimized as if it
1138is unimportant, and the compiler may make poor optimization choices for code
1139that is disproportionately used while profiling.
1140
1141Using Sampling Profilers
1142^^^^^^^^^^^^^^^^^^^^^^^^
1143
1144Sampling profilers are used to collect runtime information, such as
1145hardware counters, while your application executes. They are typically
1146very efficient and do not incur a large runtime overhead. The
1147sample data collected by the profiler can be used during compilation
1148to determine what the most executed areas of the code are.
1149
1150Using the data from a sample profiler requires some changes in the way
1151a program is built. Before the compiler can use profiling information,
1152the code needs to execute under the profiler. The following is the
1153usual build cycle when using sample profilers for optimization:
1154
11551. Build the code with source line table information. You can use all the
1156   usual build flags that you always build your application with. The only
1157   requirement is that you add ``-gline-tables-only`` or ``-g`` to the
1158   command line. This is important for the profiler to be able to map
1159   instructions back to source line locations.
1160
1161   .. code-block:: console
1162
1163     $ clang++ -O2 -gline-tables-only code.cc -o code
1164
11652. Run the executable under a sampling profiler. The specific profiler
1166   you use does not really matter, as long as its output can be converted
1167   into the format that the LLVM optimizer understands. Currently, there
1168   exists a conversion tool for the Linux Perf profiler
1169   (https://perf.wiki.kernel.org/), so these examples assume that you
1170   are using Linux Perf to profile your code.
1171
1172   .. code-block:: console
1173
1174     $ perf record -b ./code
1175
1176   Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
1177   Record (LBR) to record call chains. While this is not strictly required,
1178   it provides better call information, which improves the accuracy of
1179   the profile data.
1180
11813. Convert the collected profile data to LLVM's sample profile format.
1182   This is currently supported via the AutoFDO converter ``create_llvm_prof``.
1183   It is available at http://github.com/google/autofdo. Once built and
1184   installed, you can convert the ``perf.data`` file to LLVM using
1185   the command:
1186
1187   .. code-block:: console
1188
1189     $ create_llvm_prof --binary=./code --out=code.prof
1190
1191   This will read ``perf.data`` and the binary file ``./code`` and emit
1192   the profile data in ``code.prof``. Note that if you ran ``perf``
1193   without the ``-b`` flag, you need to use ``--use_lbr=false`` when
1194   calling ``create_llvm_prof``.
1195
11964. Build the code again using the collected profile. This step feeds
1197   the profile back to the optimizers. This should result in a binary
1198   that executes faster than the original one. Note that you are not
1199   required to build the code with the exact same arguments that you
1200   used in the first step. The only requirement is that you build the code
1201   with ``-gline-tables-only`` and ``-fprofile-sample-use``.
1202
1203   .. code-block:: console
1204
1205     $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
1206
1207
1208Sample Profile Format
1209"""""""""""""""""""""
1210
1211If you are not using Linux Perf to collect profiles, you will need to
1212write a conversion tool from your profiler to LLVM's format. This section
1213explains the file format expected by the backend.
1214
1215Sample profiles are written as ASCII text. The file is divided into sections,
1216which correspond to each of the functions executed at runtime. Each
1217section has the following format (taken from
1218https://github.com/google/autofdo/blob/master/profile_writer.h):
1219
1220.. code-block:: console
1221
1222    function1:total_samples:total_head_samples
1223    offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
1224    offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
1225    ...
1226    offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
1227
1228The file may contain blank lines between sections and within a
1229section. However, the spacing within a single line is fixed. Additional
1230spaces will result in an error while reading the file.
1231
1232Function names must be mangled in order for the profile loader to
1233match them in the current translation unit. The two numbers in the
1234function header specify how many total samples were accumulated in the
1235function (first number), and the total number of samples accumulated
1236in the prologue of the function (second number). This head sample
1237count provides an indicator of how frequently the function is invoked.
1238
1239Each sampled line may contain several items. Some are optional (marked
1240below):
1241
1242a. Source line offset. This number represents the line number
1243   in the function where the sample was collected. The line number is
1244   always relative to the line where symbol of the function is
1245   defined. So, if the function has its header at line 280, the offset
1246   13 is at line 293 in the file.
1247
1248   Note that this offset should never be a negative number. This could
1249   happen in cases like macros. The debug machinery will register the
1250   line number at the point of macro expansion. So, if the macro was
1251   expanded in a line before the start of the function, the profile
1252   converter should emit a 0 as the offset (this means that the optimizers
1253   will not be able to associate a meaningful weight to the instructions
1254   in the macro).
1255
1256b. [OPTIONAL] Discriminator. This is used if the sampled program
1257   was compiled with DWARF discriminator support
1258   (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
1259   DWARF discriminators are unsigned integer values that allow the
1260   compiler to distinguish between multiple execution paths on the
1261   same source line location.
1262
1263   For example, consider the line of code ``if (cond) foo(); else bar();``.
1264   If the predicate ``cond`` is true 80% of the time, then the edge
1265   into function ``foo`` should be considered to be taken most of the
1266   time. But both calls to ``foo`` and ``bar`` are at the same source
1267   line, so a sample count at that line is not sufficient. The
1268   compiler needs to know which part of that line is taken more
1269   frequently.
1270
1271   This is what discriminators provide. In this case, the calls to
1272   ``foo`` and ``bar`` will be at the same line, but will have
1273   different discriminator values. This allows the compiler to correctly
1274   set edge weights into ``foo`` and ``bar``.
1275
1276c. Number of samples. This is an integer quantity representing the
1277   number of samples collected by the profiler at this source
1278   location.
1279
1280d. [OPTIONAL] Potential call targets and samples. If present, this
1281   line contains a call instruction. This models both direct and
1282   number of samples. For example,
1283
1284   .. code-block:: console
1285
1286     130: 7  foo:3  bar:2  baz:7
1287
1288   The above means that at relative line offset 130 there is a call
1289   instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
1290   with ``baz()`` being the relatively more frequently called target.
1291
1292
1293Profiling with Instrumentation
1294^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1295
1296Clang also supports profiling via instrumentation. This requires building a
1297special instrumented version of the code and has some runtime
1298overhead during the profiling, but it provides more detailed results than a
1299sampling profiler. It also provides reproducible results, at least to the
1300extent that the code behaves consistently across runs.
1301
1302Here are the steps for using profile guided optimization with
1303instrumentation:
1304
13051. Build an instrumented version of the code by compiling and linking with the
1306   ``-fprofile-instr-generate`` option.
1307
1308   .. code-block:: console
1309
1310     $ clang++ -O2 -fprofile-instr-generate code.cc -o code
1311
13122. Run the instrumented executable with inputs that reflect the typical usage.
1313   By default, the profile data will be written to a ``default.profraw`` file
1314   in the current directory. You can override that default by setting the
1315   ``LLVM_PROFILE_FILE`` environment variable to specify an alternate file.
1316   Any instance of ``%p`` in that file name will be replaced by the process
1317   ID, so that you can easily distinguish the profile output from multiple
1318   runs.
1319
1320   .. code-block:: console
1321
1322     $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
1323
13243. Combine profiles from multiple runs and convert the "raw" profile format to
1325   the input expected by clang. Use the ``merge`` command of the llvm-profdata
1326   tool to do this.
1327
1328   .. code-block:: console
1329
1330     $ llvm-profdata merge -output=code.profdata code-*.profraw
1331
1332   Note that this step is necessary even when there is only one "raw" profile,
1333   since the merge operation also changes the file format.
1334
13354. Build the code again using the ``-fprofile-instr-use`` option to specify the
1336   collected profile data.
1337
1338   .. code-block:: console
1339
1340     $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
1341
1342   You can repeat step 4 as often as you like without regenerating the
1343   profile. As you make changes to your code, clang may no longer be able to
1344   use the profile data. It will warn you when this happens.
1345
1346
1347Controlling Size of Debug Information
1348-------------------------------------
1349
1350Debug info kind generated by Clang can be set by one of the flags listed
1351below. If multiple flags are present, the last one is used.
1352
1353.. option:: -g0
1354
1355  Don't generate any debug info (default).
1356
1357.. option:: -gline-tables-only
1358
1359  Generate line number tables only.
1360
1361  This kind of debug info allows to obtain stack traces with function names,
1362  file names and line numbers (by such tools as ``gdb`` or ``addr2line``).  It
1363  doesn't contain any other data (e.g. description of local variables or
1364  function parameters).
1365
1366.. option:: -fstandalone-debug
1367
1368  Clang supports a number of optimizations to reduce the size of debug
1369  information in the binary. They work based on the assumption that
1370  the debug type information can be spread out over multiple
1371  compilation units.  For instance, Clang will not emit type
1372  definitions for types that are not needed by a module and could be
1373  replaced with a forward declaration.  Further, Clang will only emit
1374  type info for a dynamic C++ class in the module that contains the
1375  vtable for the class.
1376
1377  The **-fstandalone-debug** option turns off these optimizations.
1378  This is useful when working with 3rd-party libraries that don't come
1379  with debug information.  Note that Clang will never emit type
1380  information for types that are not referenced at all by the program.
1381
1382.. option:: -fno-standalone-debug
1383
1384   On Darwin **-fstandalone-debug** is enabled by default. The
1385   **-fno-standalone-debug** option can be used to get to turn on the
1386   vtable-based optimization described above.
1387
1388.. option:: -g
1389
1390  Generate complete debug info.
1391
1392Comment Parsing Options
1393-----------------------
1394
1395Clang parses Doxygen and non-Doxygen style documentation comments and attaches
1396them to the appropriate declaration nodes.  By default, it only parses
1397Doxygen-style comments and ignores ordinary comments starting with ``//`` and
1398``/*``.
1399
1400.. option:: -Wdocumentation
1401
1402  Emit warnings about use of documentation comments.  This warning group is off
1403  by default.
1404
1405  This includes checking that ``\param`` commands name parameters that actually
1406  present in the function signature, checking that ``\returns`` is used only on
1407  functions that actually return a value etc.
1408
1409.. option:: -Wno-documentation-unknown-command
1410
1411  Don't warn when encountering an unknown Doxygen command.
1412
1413.. option:: -fparse-all-comments
1414
1415  Parse all comments as documentation comments (including ordinary comments
1416  starting with ``//`` and ``/*``).
1417
1418.. option:: -fcomment-block-commands=[commands]
1419
1420  Define custom documentation commands as block commands.  This allows Clang to
1421  construct the correct AST for these custom commands, and silences warnings
1422  about unknown commands.  Several commands must be separated by a comma
1423  *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
1424  custom commands ``\foo`` and ``\bar``.
1425
1426  It is also possible to use ``-fcomment-block-commands`` several times; e.g.
1427  ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
1428  as above.
1429
1430.. _c:
1431
1432C Language Features
1433===================
1434
1435The support for standard C in clang is feature-complete except for the
1436C99 floating-point pragmas.
1437
1438Extensions supported by clang
1439-----------------------------
1440
1441See :doc:`LanguageExtensions`.
1442
1443Differences between various standard modes
1444------------------------------------------
1445
1446clang supports the -std option, which changes what language mode clang
1447uses. The supported modes for C are c89, gnu89, c94, c99, gnu99 and
1448various aliases for those modes. If no -std option is specified, clang
1449defaults to gnu99 mode.
1450
1451Differences between all ``c*`` and ``gnu*`` modes:
1452
1453-  ``c*`` modes define "``__STRICT_ANSI__``".
1454-  Target-specific defines not prefixed by underscores, like "linux",
1455   are defined in ``gnu*`` modes.
1456-  Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
1457   the -trigraphs option.
1458-  The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
1459   the variants "``__asm__``" and "``__typeof__``" are recognized in all
1460   modes.
1461-  The Apple "blocks" extension is recognized by default in ``gnu*`` modes
1462   on some platforms; it can be enabled in any mode with the "-fblocks"
1463   option.
1464-  Arrays that are VLA's according to the standard, but which can be
1465   constant folded by the frontend are treated as fixed size arrays.
1466   This occurs for things like "int X[(1, 2)];", which is technically a
1467   VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
1468
1469Differences between ``*89`` and ``*99`` modes:
1470
1471-  The ``*99`` modes default to implementing "inline" as specified in C99,
1472   while the ``*89`` modes implement the GNU version. This can be
1473   overridden for individual functions with the ``__gnu_inline__``
1474   attribute.
1475-  Digraphs are not recognized in c89 mode.
1476-  The scope of names defined inside a "for", "if", "switch", "while",
1477   or "do" statement is different. (example: "``if ((struct x {int
1478   x;}*)0) {}``".)
1479-  ``__STDC_VERSION__`` is not defined in ``*89`` modes.
1480-  "inline" is not recognized as a keyword in c89 mode.
1481-  "restrict" is not recognized as a keyword in ``*89`` modes.
1482-  Commas are allowed in integer constant expressions in ``*99`` modes.
1483-  Arrays which are not lvalues are not implicitly promoted to pointers
1484   in ``*89`` modes.
1485-  Some warnings are different.
1486
1487c94 mode is identical to c89 mode except that digraphs are enabled in
1488c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
1489
1490GCC extensions not implemented yet
1491----------------------------------
1492
1493clang tries to be compatible with gcc as much as possible, but some gcc
1494extensions are not implemented yet:
1495
1496-  clang does not support #pragma weak (`bug
1497   3679 <http://llvm.org/bugs/show_bug.cgi?id=3679>`_). Due to the uses
1498   described in the bug, this is likely to be implemented at some point,
1499   at least partially.
1500-  clang does not support decimal floating point types (``_Decimal32`` and
1501   friends) or fixed-point types (``_Fract`` and friends); nobody has
1502   expressed interest in these features yet, so it's hard to say when
1503   they will be implemented.
1504-  clang does not support nested functions; this is a complex feature
1505   which is infrequently used, so it is unlikely to be implemented
1506   anytime soon. In C++11 it can be emulated by assigning lambda
1507   functions to local variables, e.g:
1508
1509   .. code-block:: cpp
1510
1511     auto const local_function = [&](int parameter) {
1512       // Do something
1513     };
1514     ...
1515     local_function(1);
1516
1517-  clang does not support global register variables; this is unlikely to
1518   be implemented soon because it requires additional LLVM backend
1519   support.
1520-  clang does not support static initialization of flexible array
1521   members. This appears to be a rarely used extension, but could be
1522   implemented pending user demand.
1523-  clang does not support
1524   ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
1525   used rarely, but in some potentially interesting places, like the
1526   glibc headers, so it may be implemented pending user demand. Note
1527   that because clang pretends to be like GCC 4.2, and this extension
1528   was introduced in 4.3, the glibc headers will not try to use this
1529   extension with clang at the moment.
1530-  clang does not support the gcc extension for forward-declaring
1531   function parameters; this has not shown up in any real-world code
1532   yet, though, so it might never be implemented.
1533
1534This is not a complete list; if you find an unsupported extension
1535missing from this list, please send an e-mail to cfe-dev. This list
1536currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
1537list does not include bugs in mostly-implemented features; please see
1538the `bug
1539tracker <http://llvm.org/bugs/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
1540for known existing bugs (FIXME: Is there a section for bug-reporting
1541guidelines somewhere?).
1542
1543Intentionally unsupported GCC extensions
1544----------------------------------------
1545
1546-  clang does not support the gcc extension that allows variable-length
1547   arrays in structures. This is for a few reasons: one, it is tricky to
1548   implement, two, the extension is completely undocumented, and three,
1549   the extension appears to be rarely used. Note that clang *does*
1550   support flexible array members (arrays with a zero or unspecified
1551   size at the end of a structure).
1552-  clang does not have an equivalent to gcc's "fold"; this means that
1553   clang doesn't accept some constructs gcc might accept in contexts
1554   where a constant expression is required, like "x-x" where x is a
1555   variable.
1556-  clang does not support ``__builtin_apply`` and friends; this extension
1557   is extremely obscure and difficult to implement reliably.
1558
1559.. _c_ms:
1560
1561Microsoft extensions
1562--------------------
1563
1564clang has some experimental support for extensions from Microsoft Visual
1565C++; to enable it, use the ``-fms-extensions`` command-line option. This is
1566the default for Windows targets. Note that the support is incomplete.
1567Some constructs such as ``dllexport`` on classes are ignored with a warning,
1568and others such as `Microsoft IDL annotations
1569<http://msdn.microsoft.com/en-us/library/8tesw2eh.aspx>`_ are silently
1570ignored.
1571
1572clang has a ``-fms-compatibility`` flag that makes clang accept enough
1573invalid C++ to be able to parse most Microsoft headers. For example, it
1574allows `unqualified lookup of dependent base class members
1575<http://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
1576a common compatibility issue with clang. This flag is enabled by default
1577for Windows targets.
1578
1579``-fdelayed-template-parsing`` lets clang delay parsing of function template
1580definitions until the end of a translation unit. This flag is enabled by
1581default for Windows targets.
1582
1583-  clang allows setting ``_MSC_VER`` with ``-fmsc-version=``. It defaults to
1584   1700 which is the same as Visual C/C++ 2012. Any number is supported
1585   and can greatly affect what Windows SDK and c++stdlib headers clang
1586   can compile.
1587-  clang does not support the Microsoft extension where anonymous record
1588   members can be declared using user defined typedefs.
1589-  clang supports the Microsoft ``#pragma pack`` feature for controlling
1590   record layout. GCC also contains support for this feature, however
1591   where MSVC and GCC are incompatible clang follows the MSVC
1592   definition.
1593-  clang supports the Microsoft ``#pragma comment(lib, "foo.lib")`` feature for
1594   automatically linking against the specified library.  Currently this feature
1595   only works with the Visual C++ linker.
1596-  clang supports the Microsoft ``#pragma comment(linker, "/flag:foo")`` feature
1597   for adding linker flags to COFF object files.  The user is responsible for
1598   ensuring that the linker understands the flags.
1599-  clang defaults to C++11 for Windows targets.
1600
1601.. _cxx:
1602
1603C++ Language Features
1604=====================
1605
1606clang fully implements all of standard C++98 except for exported
1607templates (which were removed in C++11), and all of standard C++11
1608and the current draft standard for C++1y.
1609
1610Controlling implementation limits
1611---------------------------------
1612
1613.. option:: -fbracket-depth=N
1614
1615  Sets the limit for nested parentheses, brackets, and braces to N.  The
1616  default is 256.
1617
1618.. option:: -fconstexpr-depth=N
1619
1620  Sets the limit for recursive constexpr function invocations to N.  The
1621  default is 512.
1622
1623.. option:: -ftemplate-depth=N
1624
1625  Sets the limit for recursively nested template instantiations to N.  The
1626  default is 256.
1627
1628.. option:: -foperator-arrow-depth=N
1629
1630  Sets the limit for iterative calls to 'operator->' functions to N.  The
1631  default is 256.
1632
1633.. _objc:
1634
1635Objective-C Language Features
1636=============================
1637
1638.. _objcxx:
1639
1640Objective-C++ Language Features
1641===============================
1642
1643
1644.. _target_features:
1645
1646Target-Specific Features and Limitations
1647========================================
1648
1649CPU Architectures Features and Limitations
1650------------------------------------------
1651
1652X86
1653^^^
1654
1655The support for X86 (both 32-bit and 64-bit) is considered stable on
1656Darwin (Mac OS X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
1657to correctly compile many large C, C++, Objective-C, and Objective-C++
1658codebases.
1659
1660On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
1661Microsoft x64 calling convention. You might need to tweak
1662``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
1663
1664For the X86 target, clang supports the :option:`-m16` command line
1665argument which enables 16-bit code output. This is broadly similar to
1666using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
1667and the ABI remains 32-bit but the assembler emits instructions
1668appropriate for a CPU running in 16-bit mode, with address-size and
1669operand-size prefixes to enable 32-bit addressing and operations.
1670
1671ARM
1672^^^
1673
1674The support for ARM (specifically ARMv6 and ARMv7) is considered stable
1675on Darwin (iOS): it has been tested to correctly compile many large C,
1676C++, Objective-C, and Objective-C++ codebases. Clang only supports a
1677limited number of ARM architectures. It does not yet fully support
1678ARMv5, for example.
1679
1680PowerPC
1681^^^^^^^
1682
1683The support for PowerPC (especially PowerPC64) is considered stable
1684on Linux and FreeBSD: it has been tested to correctly compile many
1685large C and C++ codebases. PowerPC (32bit) is still missing certain
1686features (e.g. PIC code on ELF platforms).
1687
1688Other platforms
1689^^^^^^^^^^^^^^^
1690
1691clang currently contains some support for other architectures (e.g. Sparc);
1692however, significant pieces of code generation are still missing, and they
1693haven't undergone significant testing.
1694
1695clang contains limited support for the MSP430 embedded processor, but
1696both the clang support and the LLVM backend support are highly
1697experimental.
1698
1699Other platforms are completely unsupported at the moment. Adding the
1700minimal support needed for parsing and semantic analysis on a new
1701platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
1702tree. This level of support is also sufficient for conversion to LLVM IR
1703for simple programs. Proper support for conversion to LLVM IR requires
1704adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
1705change soon, though. Generating assembly requires a suitable LLVM
1706backend.
1707
1708Operating System Features and Limitations
1709-----------------------------------------
1710
1711Darwin (Mac OS X)
1712^^^^^^^^^^^^^^^^^
1713
1714Thread Sanitizer is not supported.
1715
1716Windows
1717^^^^^^^
1718
1719Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
1720platforms.
1721
1722See also :ref:`Microsoft Extensions <c_ms>`.
1723
1724Cygwin
1725""""""
1726
1727Clang works on Cygwin-1.7.
1728
1729MinGW32
1730"""""""
1731
1732Clang works on some mingw32 distributions. Clang assumes directories as
1733below;
1734
1735-  ``C:/mingw/include``
1736-  ``C:/mingw/lib``
1737-  ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
1738
1739On MSYS, a few tests might fail.
1740
1741MinGW-w64
1742"""""""""
1743
1744For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
1745assumes as below;
1746
1747-  ``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)``
1748-  ``some_directory/bin/gcc.exe``
1749-  ``some_directory/bin/clang.exe``
1750-  ``some_directory/bin/clang++.exe``
1751-  ``some_directory/bin/../include/c++/GCC_version``
1752-  ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
1753-  ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
1754-  ``some_directory/bin/../include/c++/GCC_version/backward``
1755-  ``some_directory/bin/../x86_64-w64-mingw32/include``
1756-  ``some_directory/bin/../i686-w64-mingw32/include``
1757-  ``some_directory/bin/../include``
1758
1759This directory layout is standard for any toolchain you will find on the
1760official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
1761
1762Clang expects the GCC executable "gcc.exe" compiled for
1763``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
1764
1765`Some tests might fail <http://llvm.org/bugs/show_bug.cgi?id=9072>`_ on
1766``x86_64-w64-mingw32``.
1767
1768.. _clang-cl:
1769
1770clang-cl
1771========
1772
1773clang-cl is an alternative command-line interface to Clang driver, designed for
1774compatibility with the Visual C++ compiler, cl.exe.
1775
1776To enable clang-cl to find system headers, libraries, and the linker when run
1777from the command-line, it should be executed inside a Visual Studio Native Tools
1778Command Prompt or a regular Command Prompt where the environment has been set
1779up using e.g. `vcvars32.bat <http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
1780
1781clang-cl can also be used from inside Visual Studio  by using an LLVM Platform
1782Toolset.
1783
1784Command-Line Options
1785--------------------
1786
1787To be compatible with cl.exe, clang-cl supports most of the same command-line
1788options. Those options can start with either ``/`` or ``-``. It also supports
1789some of Clang's core options, such as the ``-W`` options.
1790
1791Options that are known to clang-cl, but not currently supported, are ignored
1792with a warning. For example:
1793
1794  ::
1795
1796    clang-cl.exe: warning: argument unused during compilation: '/Zi'
1797
1798To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
1799
1800Options that are not known to clang-cl will cause errors. If they are spelled with a
1801leading ``/``, they will be mistaken for a filename:
1802
1803  ::
1804
1805    clang-cl.exe: error: no such file or directory: '/foobar'
1806
1807Please `file a bug <http://llvm.org/bugs/enter_bug.cgi?product=clang&component=Driver>`_
1808for any valid cl.exe flags that clang-cl does not understand.
1809
1810Execute ``clang-cl /?`` to see a list of supported options:
1811
1812  ::
1813
1814    /?                     Display available options
1815    /c                     Compile only
1816    /D <macro[=value]>     Define macro
1817    /fallback              Fall back to cl.exe if clang-cl fails to compile
1818    /FA                    Output assembly code file during compilation
1819    /Fa<file or directory> Output assembly code to this file during compilation
1820    /Fe<file or directory> Set output executable file or directory (ends in / or \)
1821    /FI<value>             Include file before parsing
1822    /Fo<file or directory> Set output object file, or directory (ends in / or \)
1823    /GF-                   Disable string pooling
1824    /GR-                   Disable RTTI
1825    /GR                    Enable RTTI
1826    /help                  Display available options
1827    /I <dir>               Add directory to include search path
1828    /J                     Make char type unsigned
1829    /LDd                   Create debug DLL
1830    /LD                    Create DLL
1831    /link <options>        Forward options to the linker
1832    /MDd                   Use DLL debug run-time
1833    /MD                    Use DLL run-time
1834    /MTd                   Use static debug run-time
1835    /MT                    Use static run-time
1836    /Ob0                   Disable inlining
1837    /Od                    Disable optimization
1838    /Oi-                   Disable use of builtin functions
1839    /Oi                    Enable use of builtin functions
1840    /Os                    Optimize for size
1841    /Ot                    Optimize for speed
1842    /Ox                    Maximum optimization
1843    /Oy-                   Disable frame pointer omission
1844    /Oy                    Enable frame pointer omission
1845    /O<n>                  Optimization level
1846    /P                     Only run the preprocessor
1847    /showIncludes          Print info about included files to stderr
1848    /TC                    Treat all source files as C
1849    /Tc <filename>         Specify a C source file
1850    /TP                    Treat all source files as C++
1851    /Tp <filename>         Specify a C++ source file
1852    /U <macro>             Undefine macro
1853    /W0                    Disable all warnings
1854    /W1                    Enable -Wall
1855    /W2                    Enable -Wall
1856    /W3                    Enable -Wall
1857    /W4                    Enable -Wall
1858    /Wall                  Enable -Wall
1859    /WX-                   Do not treat warnings as errors
1860    /WX                    Treat warnings as errors
1861    /w                     Disable all warnings
1862    /Zs                    Syntax-check only
1863
1864The /fallback Option
1865^^^^^^^^^^^^^^^^^^^^
1866
1867When clang-cl is run with the ``/fallback`` option, it will first try to
1868compile files itself. For any file that it fails to compile, it will fall back
1869and try to compile the file by invoking cl.exe.
1870
1871This option is intended to be used as a temporary means to build projects where
1872clang-cl cannot successfully compile all the files. clang-cl may fail to compile
1873a file either because it cannot generate code for some C++ feature, or because
1874it cannot parse some Microsoft language extension.
1875