blob: 96b7ac95cb5d6370840a3ce1c58abfb63b9a041d [file] [log] [blame]
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001============================
2Clang Compiler User's Manual
3============================
4
Paul Robinson8ce9b442016-08-15 18:45:52 +00005.. include:: <isonum.txt>
6
Sean Silvabf9b4cd2012-12-13 01:10:46 +00007.. contents::
8 :local:
9
10Introduction
11============
12
13The Clang Compiler is an open-source compiler for the C family of
14programming languages, aiming to be the best in class implementation of
15these languages. Clang builds on the LLVM optimizer and code generator,
16allowing it to provide high-quality optimization and code generation
17support for many targets. For more general information, please see the
18`Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
19Site <http://llvm.org>`_.
20
21This document describes important notes about using Clang as a compiler
22for an end-user, documenting the supported features, command line
23options, etc. If you are interested in using Clang to build a tool that
Dmitri Gribenkod9d26072012-12-15 20:41:17 +000024processes code, please see :doc:`InternalsManual`. If you are interested in the
25`Clang Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
Sean Silvabf9b4cd2012-12-13 01:10:46 +000026page.
27
Richard Smith58e14742016-10-27 20:55:56 +000028Clang is one component in a complete toolchain for C family languages.
29A separate document describes the other pieces necessary to
30:doc:`assemble a complete toolchain <Toolchain>`.
31
Sean Silvabf9b4cd2012-12-13 01:10:46 +000032Clang is designed to support the C family of programming languages,
33which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
34:ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
35language-specific information, please see the corresponding language
36specific section:
37
38- :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
39 C99 (+TC1, TC2, TC3).
40- :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
41 variants depending on base language.
42- :ref:`C++ Language <cxx>`
43- :ref:`Objective C++ Language <objcxx>`
44
45In addition to these base languages and their dialects, Clang supports a
46broad variety of language extensions, which are documented in the
47corresponding language section. These extensions are provided to be
48compatible with the GCC, Microsoft, and other popular compilers as well
49as to improve functionality through Clang-specific features. The Clang
50driver and language features are intentionally designed to be as
51compatible with the GNU GCC compiler as reasonably possible, easing
52migration from GCC to Clang. In most cases, code "just works".
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +000053Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
54to be compatible with the Visual C++ compiler, cl.exe.
Sean Silvabf9b4cd2012-12-13 01:10:46 +000055
56In addition to language specific features, Clang has a variety of
57features that depend on what CPU architecture or operating system is
58being compiled for. Please see the :ref:`Target-Specific Features and
59Limitations <target_features>` section for more details.
60
61The rest of the introduction introduces some basic :ref:`compiler
62terminology <terminology>` that is used throughout this manual and
63contains a basic :ref:`introduction to using Clang <basicusage>` as a
64command line compiler.
65
66.. _terminology:
67
68Terminology
69-----------
70
71Front end, parser, backend, preprocessor, undefined behavior,
72diagnostic, optimizer
73
74.. _basicusage:
75
76Basic Usage
77-----------
78
79Intro to how to use a C compiler for newbies.
80
81compile + link compile then link debug info enabling optimizations
Richard Smithab506ad2014-10-20 23:26:58 +000082picking a language to use, defaults to C11 by default. Autosenses based
Sean Silvabf9b4cd2012-12-13 01:10:46 +000083on extension. using a makefile
84
85Command Line Options
86====================
87
88This section is generally an index into other sections. It does not go
89into depth on the ones that are covered by other sections. However, the
90first part introduces the language selection and other high level
Dmitri Gribenko1436ff22012-12-19 22:06:59 +000091options like :option:`-c`, :option:`-g`, etc.
Sean Silvabf9b4cd2012-12-13 01:10:46 +000092
93Options to Control Error and Warning Messages
94---------------------------------------------
95
Dmitri Gribenko1436ff22012-12-19 22:06:59 +000096.. option:: -Werror
Sean Silvabf9b4cd2012-12-13 01:10:46 +000097
Dmitri Gribenko1436ff22012-12-19 22:06:59 +000098 Turn warnings into errors.
Sean Silvabf9b4cd2012-12-13 01:10:46 +000099
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000100.. This is in plain monospaced font because it generates the same label as
101.. -Werror, and Sphinx complains.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000102
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000103``-Werror=foo``
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000104
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000105 Turn warning "foo" into an error.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000106
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000107.. option:: -Wno-error=foo
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000108
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000109 Turn warning "foo" into an warning even if :option:`-Werror` is specified.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000110
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000111.. option:: -Wfoo
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000112
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000113 Enable warning "foo".
Richard Smithb6a3b4b2016-09-12 05:58:29 +0000114 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
115 list of the warning flags that can be specified in this way.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000116
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000117.. option:: -Wno-foo
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000118
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000119 Disable warning "foo".
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000120
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000121.. option:: -w
122
Tobias Grosser74160242014-02-28 09:11:08 +0000123 Disable all diagnostics.
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000124
125.. option:: -Weverything
126
Tobias Grosser74160242014-02-28 09:11:08 +0000127 :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000128
129.. option:: -pedantic
130
131 Warn on language extensions.
132
133.. option:: -pedantic-errors
134
135 Error on language extensions.
136
137.. option:: -Wsystem-headers
138
139 Enable warnings from system headers.
140
141.. option:: -ferror-limit=123
142
143 Stop emitting diagnostics after 123 errors have been produced. The default is
Aaron Ballman4f6b3ec2016-07-14 17:15:06 +0000144 20, and the error limit can be disabled with `-ferror-limit=0`.
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000145
146.. option:: -ftemplate-backtrace-limit=123
147
148 Only emit up to 123 template instantiation notes within the template
149 instantiation backtrace for a single warning or error. The default is 10, and
Aaron Ballman4f6b3ec2016-07-14 17:15:06 +0000150 the limit can be disabled with `-ftemplate-backtrace-limit=0`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000151
152.. _cl_diag_formatting:
153
154Formatting of Diagnostics
155^^^^^^^^^^^^^^^^^^^^^^^^^
156
157Clang aims to produce beautiful diagnostics by default, particularly for
158new users that first come to Clang. However, different people have
Douglas Katzman1e7bf362015-08-03 20:41:31 +0000159different preferences, and sometimes Clang is driven not by a human,
160but by a program that wants consistent and easily parsable output. For
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000161these cases, Clang provides a wide range of options to control the exact
162output format of the diagnostics that it generates.
163
164.. _opt_fshow-column:
165
166**-f[no-]show-column**
167 Print column number in diagnostic.
168
169 This option, which defaults to on, controls whether or not Clang
170 prints the column number of a diagnostic. For example, when this is
171 enabled, Clang will print something like:
172
173 ::
174
175 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
176 #endif bad
177 ^
178 //
179
180 When this is disabled, Clang will print "test.c:28: warning..." with
181 no column number.
182
183 The printed column numbers count bytes from the beginning of the
184 line; take care if your source contains multibyte characters.
185
186.. _opt_fshow-source-location:
187
188**-f[no-]show-source-location**
189 Print source file/line/column information in diagnostic.
190
191 This option, which defaults to on, controls whether or not Clang
192 prints the filename, line number and column number of a diagnostic.
193 For example, when this is enabled, Clang will print something like:
194
195 ::
196
197 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
198 #endif bad
199 ^
200 //
201
202 When this is disabled, Clang will not print the "test.c:28:8: "
203 part.
204
205.. _opt_fcaret-diagnostics:
206
207**-f[no-]caret-diagnostics**
208 Print source line and ranges from source code in diagnostic.
209 This option, which defaults to on, controls whether or not Clang
210 prints the source line, source ranges, and caret when emitting a
211 diagnostic. For example, when this is enabled, Clang will print
212 something like:
213
214 ::
215
216 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
217 #endif bad
218 ^
219 //
220
221**-f[no-]color-diagnostics**
222 This option, which defaults to on when a color-capable terminal is
223 detected, controls whether or not Clang prints diagnostics in color.
224
225 When this option is enabled, Clang will use colors to highlight
226 specific parts of the diagnostic, e.g.,
227
228 .. nasty hack to not lose our dignity
229
230 .. raw:: html
231
232 <pre>
233 <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>
234 #endif bad
235 <span style="color:green">^</span>
236 <span style="color:green">//</span>
237 </pre>
238
239 When this is disabled, Clang will just print:
240
241 ::
242
243 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
244 #endif bad
245 ^
246 //
247
Nico Rieck7857d462013-09-11 00:38:02 +0000248**-fansi-escape-codes**
249 Controls whether ANSI escape codes are used instead of the Windows Console
250 API to output colored diagnostics. This option is only used on Windows and
251 defaults to off.
252
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000253.. option:: -fdiagnostics-format=clang/msvc/vi
254
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000255 Changes diagnostic output format to better match IDEs and command line tools.
256
257 This option controls the output format of the filename, line number,
258 and column printed in diagnostic messages. The options, and their
259 affect on formatting a simple conversion diagnostic, follow:
260
261 **clang** (default)
262 ::
263
264 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
265
266 **msvc**
267 ::
268
269 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
270
271 **vi**
272 ::
273
274 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
275
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000276.. _opt_fdiagnostics-show-option:
277
278**-f[no-]diagnostics-show-option**
279 Enable ``[-Woption]`` information in diagnostic line.
280
281 This option, which defaults to on, controls whether or not Clang
282 prints the associated :ref:`warning group <cl_diag_warning_groups>`
283 option name when outputting a warning diagnostic. For example, in
284 this output:
285
286 ::
287
288 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
289 #endif bad
290 ^
291 //
292
293 Passing **-fno-diagnostics-show-option** will prevent Clang from
294 printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
295 the diagnostic. This information tells you the flag needed to enable
296 or disable the diagnostic, either from the command line or through
297 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
298
299.. _opt_fdiagnostics-show-category:
300
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000301.. option:: -fdiagnostics-show-category=none/id/name
302
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000303 Enable printing category information in diagnostic line.
304
305 This option, which defaults to "none", controls whether or not Clang
306 prints the category associated with a diagnostic when emitting it.
307 Each diagnostic may or many not have an associated category, if it
308 has one, it is listed in the diagnostic categorization field of the
309 diagnostic line (in the []'s).
310
311 For example, a format string warning will produce these three
312 renditions based on the setting of this option:
313
314 ::
315
316 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
317 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
318 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
319
320 This category can be used by clients that want to group diagnostics
321 by category, so it should be a high level category. We want dozens
322 of these, not hundreds or thousands of them.
323
Adam Nemet1eea3e52016-09-13 04:32:40 +0000324.. _opt_fdiagnostics-show-hotness:
325
326**-f[no-]diagnostics-show-hotness**
327 Enable profile hotness information in diagnostic line.
328
329 This option, which defaults to off, controls whether Clang prints the
330 profile hotness associated with a diagnostics in the presence of
331 profile-guided optimization information. This is currently supported with
332 optimization remarks (see :ref:`Options to Emit Optimization Reports
333 <rpass>`). The hotness information allows users to focus on the hot
334 optimization remarks that are likely to be more relevant for run-time
335 performance.
336
337 For example, in this output, the block containing the callsite of `foo` was
338 executed 3000 times according to the profile data:
339
340 ::
341
342 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
343 sum += foo(x, x - 2);
344 ^
345
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000346.. _opt_fdiagnostics-fixit-info:
347
348**-f[no-]diagnostics-fixit-info**
349 Enable "FixIt" information in the diagnostics output.
350
351 This option, which defaults to on, controls whether or not Clang
352 prints the information on how to fix a specific diagnostic
353 underneath it when it knows. For example, in this output:
354
355 ::
356
357 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
358 #endif bad
359 ^
360 //
361
362 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
363 printing the "//" line at the end of the message. This information
364 is useful for users who may not understand what is wrong, but can be
365 confusing for machine parsing.
366
367.. _opt_fdiagnostics-print-source-range-info:
368
Nico Weber69dce49c72013-01-09 05:06:41 +0000369**-fdiagnostics-print-source-range-info**
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000370 Print machine parsable information about source ranges.
Nico Weber69dce49c72013-01-09 05:06:41 +0000371 This option makes Clang print information about source ranges in a machine
372 parsable format after the file/line/column number information. The
373 information is a simple sequence of brace enclosed ranges, where each range
374 lists the start and end line/column locations. For example, in this output:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000375
376 ::
377
378 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
379 P = (P-42) + Gamma*4;
380 ~~~~~~ ^ ~~~~~~~
381
382 The {}'s are generated by -fdiagnostics-print-source-range-info.
383
384 The printed column numbers count bytes from the beginning of the
385 line; take care if your source contains multibyte characters.
386
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000387.. option:: -fdiagnostics-parseable-fixits
388
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000389 Print Fix-Its in a machine parseable form.
390
391 This option makes Clang print available Fix-Its in a machine
392 parseable format at the end of diagnostics. The following example
393 illustrates the format:
394
395 ::
396
397 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
398
399 The range printed is a half-open range, so in this example the
400 characters at column 25 up to but not including column 29 on line 7
401 in t.cpp should be replaced with the string "Gamma". Either the
402 range or the replacement string may be empty (representing strict
403 insertions and strict erasures, respectively). Both the file name
404 and the insertion string escape backslash (as "\\\\"), tabs (as
405 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
406 non-printable characters (as octal "\\xxx").
407
408 The printed column numbers count bytes from the beginning of the
409 line; take care if your source contains multibyte characters.
410
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000411.. option:: -fno-elide-type
412
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000413 Turns off elision in template type printing.
414
415 The default for template type printing is to elide as many template
416 arguments as possible, removing those which are the same in both
417 template types, leaving only the differences. Adding this flag will
418 print all the template arguments. If supported by the terminal,
419 highlighting will still appear on differing arguments.
420
421 Default:
422
423 ::
424
425 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;
426
427 -fno-elide-type:
428
429 ::
430
431 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;
432
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000433.. option:: -fdiagnostics-show-template-tree
434
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000435 Template type diffing prints a text tree.
436
437 For diffing large templated types, this option will cause Clang to
438 display the templates as an indented text tree, one argument per
439 line, with differences marked inline. This is compatible with
440 -fno-elide-type.
441
442 Default:
443
444 ::
445
446 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;
447
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000448 With :option:`-fdiagnostics-show-template-tree`:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000449
450 ::
451
452 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
453 vector<
454 map<
455 [...],
456 map<
Richard Trieu98ca59e2013-08-09 22:52:48 +0000457 [float != double],
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000458 [...]>>>
459
460.. _cl_diag_warning_groups:
461
462Individual Warning Groups
463^^^^^^^^^^^^^^^^^^^^^^^^^
464
465TODO: Generate this from tblgen. Define one anchor per warning group.
466
467.. _opt_wextra-tokens:
468
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000469.. option:: -Wextra-tokens
470
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000471 Warn about excess tokens at the end of a preprocessor directive.
472
473 This option, which defaults to on, enables warnings about extra
474 tokens at the end of preprocessor directives. For example:
475
476 ::
477
478 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
479 #endif bad
480 ^
481
482 These extra tokens are not strictly conforming, and are usually best
483 handled by commenting them out.
484
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000485.. option:: -Wambiguous-member-template
486
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000487 Warn about unqualified uses of a member template whose name resolves to
488 another template at the location of the use.
489
490 This option, which defaults to on, enables a warning in the
491 following code:
492
493 ::
494
495 template<typename T> struct set{};
496 template<typename T> struct trait { typedef const T& type; };
497 struct Value {
498 template<typename T> void set(typename trait<T>::type value) {}
499 };
500 void foo() {
501 Value v;
502 v.set<double>(3.2);
503 }
504
505 C++ [basic.lookup.classref] requires this to be an error, but,
506 because it's hard to work around, Clang downgrades it to a warning
507 as an extension.
508
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000509.. option:: -Wbind-to-temporary-copy
510
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000511 Warn about an unusable copy constructor when binding a reference to a
512 temporary.
513
Nico Weberacb35c02014-09-18 02:09:53 +0000514 This option enables warnings about binding a
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000515 reference to a temporary when the temporary doesn't have a usable
516 copy constructor. For example:
517
518 ::
519
520 struct NonCopyable {
521 NonCopyable();
522 private:
523 NonCopyable(const NonCopyable&);
524 };
525 void foo(const NonCopyable&);
526 void bar() {
527 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
528 }
529
530 ::
531
532 struct NonCopyable2 {
533 NonCopyable2();
534 NonCopyable2(NonCopyable2&);
535 };
536 void foo(const NonCopyable2&);
537 void bar() {
538 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
539 }
540
541 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
542 whose instantiation produces a compile error, that error will still
543 be a hard error in C++98 mode even if this warning is turned off.
544
545Options to Control Clang Crash Diagnostics
546------------------------------------------
547
548As unbelievable as it may sound, Clang does crash from time to time.
549Generally, this only occurs to those living on the `bleeding
550edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
551lengths to assist you in filing a bug report. Specifically, Clang
552generates preprocessed source file(s) and associated run script(s) upon
553a crash. These files should be attached to a bug report to ease
554reproducibility of the failure. Below are the command line options to
555control the crash diagnostics.
556
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000557.. option:: -fno-crash-diagnostics
558
559 Disable auto-generation of preprocessed source files during a clang crash.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000560
561The -fno-crash-diagnostics flag can be helpful for speeding the process
562of generating a delta reduced test case.
563
Adam Nemet1eea3e52016-09-13 04:32:40 +0000564.. _rpass:
565
Diego Novillo263ce212014-05-29 20:13:27 +0000566Options to Emit Optimization Reports
567------------------------------------
568
569Optimization reports trace, at a high-level, all the major decisions
570done by compiler transformations. For instance, when the inliner
571decides to inline function ``foo()`` into ``bar()``, or the loop unroller
572decides to unroll a loop N times, or the vectorizer decides to
573vectorize a loop body.
574
575Clang offers a family of flags which the optimizers can use to emit
576a diagnostic in three cases:
577
Aaron Ballman05efec82016-07-15 12:55:47 +00005781. When the pass makes a transformation (`-Rpass`).
Diego Novillo263ce212014-05-29 20:13:27 +0000579
Aaron Ballman05efec82016-07-15 12:55:47 +00005802. When the pass fails to make a transformation (`-Rpass-missed`).
Diego Novillo263ce212014-05-29 20:13:27 +0000581
5823. When the pass determines whether or not to make a transformation
Aaron Ballman05efec82016-07-15 12:55:47 +0000583 (`-Rpass-analysis`).
Diego Novillo263ce212014-05-29 20:13:27 +0000584
Aaron Ballman05efec82016-07-15 12:55:47 +0000585NOTE: Although the discussion below focuses on `-Rpass`, the exact
586same options apply to `-Rpass-missed` and `-Rpass-analysis`.
Diego Novillo263ce212014-05-29 20:13:27 +0000587
588Since there are dozens of passes inside the compiler, each of these flags
589take a regular expression that identifies the name of the pass which should
590emit the associated diagnostic. For example, to get a report from the inliner,
591compile the code with:
592
593.. code-block:: console
594
595 $ clang -O2 -Rpass=inline code.cc -o code
596 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
597 int bar(int j) { return foo(j, j - 2); }
598 ^
599
600Note that remarks from the inliner are identified with `[-Rpass=inline]`.
601To request a report from every optimization pass, you should use
Aaron Ballman05efec82016-07-15 12:55:47 +0000602`-Rpass=.*` (in fact, you can use any valid POSIX regular
Diego Novillo263ce212014-05-29 20:13:27 +0000603expression). However, do not expect a report from every transformation
604made by the compiler. Optimization remarks do not really make sense
605outside of the major transformations (e.g., inlining, vectorization,
606loop optimizations) and not every optimization pass supports this
607feature.
608
Adam Nemet1eea3e52016-09-13 04:32:40 +0000609Note that when using profile-guided optimization information, profile hotness
610information can be included in the remarks (see
611:ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
612
Diego Novillo263ce212014-05-29 20:13:27 +0000613Current limitations
614^^^^^^^^^^^^^^^^^^^
615
Diego Novillo94b276d2014-07-10 23:29:28 +00006161. Optimization remarks that refer to function names will display the
Diego Novillo263ce212014-05-29 20:13:27 +0000617 mangled name of the function. Since these remarks are emitted by the
618 back end of the compiler, it does not know anything about the input
619 language, nor its mangling rules.
620
Diego Novillo94b276d2014-07-10 23:29:28 +00006212. Some source locations are not displayed correctly. The front end has
Diego Novillo263ce212014-05-29 20:13:27 +0000622 a more detailed source location tracking than the locations included
623 in the debug info (e.g., the front end can locate code inside macro
Aaron Ballman05efec82016-07-15 12:55:47 +0000624 expansions). However, the locations used by `-Rpass` are
Diego Novillo263ce212014-05-29 20:13:27 +0000625 translated from debug annotations. That translation can be lossy,
626 which results in some remarks having no location information.
627
Paul Robinsond7214a72015-04-27 18:14:32 +0000628Other Options
629-------------
630Clang options that that don't fit neatly into other categories.
631
632.. option:: -MV
633
634 When emitting a dependency file, use formatting conventions appropriate
635 for NMake or Jom. Ignored unless another option causes Clang to emit a
636 dependency file.
637
638When Clang emits a dependency file (e.g., you supplied the -M option)
639most filenames can be written to the file without any special formatting.
640Different Make tools will treat different sets of characters as "special"
641and use different conventions for telling the Make tool that the character
642is actually part of the filename. Normally Clang uses backslash to "escape"
643a special character, which is the convention used by GNU Make. The -MV
644option tells Clang to put double-quotes around the entire filename, which
645is the convention used by NMake and Jom.
646
Diego Novillo263ce212014-05-29 20:13:27 +0000647
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000648Language and Target-Independent Features
649========================================
650
651Controlling Errors and Warnings
652-------------------------------
653
654Clang provides a number of ways to control which code constructs cause
655it to emit errors and warning messages, and how they are displayed to
656the console.
657
658Controlling How Clang Displays Diagnostics
659^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
660
661When Clang emits a diagnostic, it includes rich information in the
662output, and gives you fine-grain control over which information is
663printed. Clang has the ability to print this information, and these are
664the options that control it:
665
666#. A file/line/column indicator that shows exactly where the diagnostic
667 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
668 :ref:`-fshow-source-location <opt_fshow-source-location>`].
669#. A categorization of the diagnostic as a note, warning, error, or
670 fatal error.
671#. A text string that describes what the problem is.
672#. An option that indicates how to control the diagnostic (for
673 diagnostics that support it)
674 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
675#. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
676 for clients that want to group diagnostics by class (for diagnostics
677 that support it)
678 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
679#. The line of source code that the issue occurs on, along with a caret
680 and ranges that indicate the important locations
681 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
682#. "FixIt" information, which is a concise explanation of how to fix the
683 problem (when Clang is certain it knows)
684 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
685#. A machine-parsable representation of the ranges involved (off by
686 default)
687 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
688
689For more information please see :ref:`Formatting of
690Diagnostics <cl_diag_formatting>`.
691
692Diagnostic Mappings
693^^^^^^^^^^^^^^^^^^^
694
Alex Denisov793e0672015-02-11 07:56:16 +0000695All diagnostics are mapped into one of these 6 classes:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000696
697- Ignored
698- Note
Tobias Grosser74160242014-02-28 09:11:08 +0000699- Remark
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000700- Warning
701- Error
702- Fatal
703
704.. _diagnostics_categories:
705
706Diagnostic Categories
707^^^^^^^^^^^^^^^^^^^^^
708
709Though not shown by default, diagnostics may each be associated with a
710high-level category. This category is intended to make it possible to
711triage builds that produce a large number of errors or warnings in a
712grouped way.
713
714Categories are not shown by default, but they can be turned on with the
715:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
716When set to "``name``", the category is printed textually in the
717diagnostic output. When it is set to "``id``", a category number is
718printed. The mapping of category names to category id's can be obtained
719by running '``clang --print-diagnostic-categories``'.
720
721Controlling Diagnostics via Command Line Flags
722^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
723
724TODO: -W flags, -pedantic, etc
725
726.. _pragma_gcc_diagnostic:
727
728Controlling Diagnostics via Pragmas
729^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
730
731Clang can also control what diagnostics are enabled through the use of
732pragmas in the source code. This is useful for turning off specific
733warnings in a section of source code. Clang supports GCC's pragma for
734compatibility with existing source code, as well as several extensions.
735
736The pragma may control any warning that can be used from the command
737line. Warnings may be set to ignored, warning, error, or fatal. The
738following example code will tell Clang or GCC to ignore the -Wall
739warnings:
740
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000741.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000742
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000743 #pragma GCC diagnostic ignored "-Wall"
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000744
745In addition to all of the functionality provided by GCC's pragma, Clang
746also allows you to push and pop the current warning state. This is
747particularly useful when writing a header file that will be compiled by
748other people, because you don't know what warning flags they build with.
749
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000750In the below example :option:`-Wextra-tokens` is ignored for only a single line
751of code, after which the diagnostics return to whatever state had previously
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000752existed.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000753
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000754.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000755
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000756 #if foo
757 #endif foo // warning: extra tokens at end of #endif directive
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000758
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000759 #pragma clang diagnostic ignored "-Wextra-tokens"
760
761 #if foo
762 #endif foo // no warning
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000763
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000764 #pragma clang diagnostic pop
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000765
766The push and pop pragmas will save and restore the full diagnostic state
767of the compiler, regardless of how it was set. That means that it is
768possible to use push and pop around GCC compatible diagnostics and Clang
769will push and pop them appropriately, while GCC will ignore the pushes
770and pops as unknown pragmas. It should be noted that while Clang
771supports the GCC pragma, Clang and GCC do not support the exact same set
772of warnings, so even when using GCC compatible #pragmas there is no
773guarantee that they will have identical behaviour on both compilers.
774
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000775In addition to controlling warnings and errors generated by the compiler, it is
776possible to generate custom warning and error messages through the following
777pragmas:
778
779.. code-block:: c
780
781 // The following will produce warning messages
782 #pragma message "some diagnostic message"
783 #pragma GCC warning "TODO: replace deprecated feature"
784
785 // The following will produce an error message
786 #pragma GCC error "Not supported"
787
788These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
789directives, except that they may also be embedded into preprocessor macros via
790the C99 ``_Pragma`` operator, for example:
791
792.. code-block:: c
793
794 #define STR(X) #X
795 #define DEFER(M,...) M(__VA_ARGS__)
796 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
797
798 CUSTOM_ERROR("Feature not available");
799
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000800Controlling Diagnostics in System Headers
801^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
802
803Warnings are suppressed when they occur in system headers. By default,
804an included file is treated as a system header if it is found in an
805include path specified by ``-isystem``, but this can be overridden in
806several ways.
807
808The ``system_header`` pragma can be used to mark the current file as
809being a system header. No warnings will be produced from the location of
810the pragma onwards within the same file.
811
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000812.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000813
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000814 #if foo
815 #endif foo // warning: extra tokens at end of #endif directive
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000816
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000817 #pragma clang system_header
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000818
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000819 #if foo
820 #endif foo // no warning
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000821
Aaron Ballman51fb0312016-07-15 13:13:45 +0000822The `--system-header-prefix=` and `--no-system-header-prefix=`
Alexander Kornienko18fa48c2014-03-26 01:39:59 +0000823command-line arguments can be used to override whether subsets of an include
824path are treated as system headers. When the name in a ``#include`` directive
825is found within a header search path and starts with a system prefix, the
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000826header is treated as a system header. The last prefix on the
827command-line which matches the specified header name takes precedence.
828For instance:
829
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000830.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000831
Alexander Kornienko18fa48c2014-03-26 01:39:59 +0000832 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
833 --no-system-header-prefix=x/y/
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000834
835Here, ``#include "x/a.h"`` is treated as including a system header, even
836if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
837as not including a system header, even if the header is found in
838``bar``.
839
840A ``#include`` directive which finds a file relative to the current
841directory is treated as including a system header if the including file
842is treated as a system header.
843
844.. _diagnostics_enable_everything:
845
Tobias Grosser74160242014-02-28 09:11:08 +0000846Enabling All Diagnostics
847^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000848
849In addition to the traditional ``-W`` flags, one can enable **all**
Tobias Grosser74160242014-02-28 09:11:08 +0000850diagnostics by passing :option:`-Weverything`. This works as expected
851with
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000852:option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000853
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000854Note that when combined with :option:`-w` (which disables all warnings), that
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000855flag wins.
856
857Controlling Static Analyzer Diagnostics
858^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
859
860While not strictly part of the compiler, the diagnostics from Clang's
861`static analyzer <http://clang-analyzer.llvm.org>`_ can also be
862influenced by the user via changes to the source code. See the available
863`annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
864analyzer's `FAQ
865page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
866information.
867
Dmitri Gribenko7ac0cc32012-12-15 21:10:51 +0000868.. _usersmanual-precompiled-headers:
869
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000870Precompiled Headers
871-------------------
872
873`Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
874are a general approach employed by many compilers to reduce compilation
875time. The underlying motivation of the approach is that it is common for
876the same (and often large) header files to be included by multiple
877source files. Consequently, compile times can often be greatly improved
878by caching some of the (redundant) work done by a compiler to process
879headers. Precompiled header files, which represent one of many ways to
880implement this optimization, are literally files that represent an
881on-disk cache that contains the vital information necessary to reduce
882some of the work needed to process a corresponding header file. While
883details of precompiled headers vary between compilers, precompiled
884headers have been shown to be highly effective at speeding up program
Nico Weberab88f0b2014-03-07 18:09:57 +0000885compilation on systems with very large system headers (e.g., Mac OS X).
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000886
887Generating a PCH File
888^^^^^^^^^^^^^^^^^^^^^
889
890To generate a PCH file using Clang, one invokes Clang with the
Aaron Ballman51fb0312016-07-15 13:13:45 +0000891`-x <language>-header` option. This mirrors the interface in GCC
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000892for generating PCH files:
893
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000894.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000895
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000896 $ gcc -x c-header test.h -o test.h.gch
897 $ clang -x c-header test.h -o test.h.pch
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000898
899Using a PCH File
900^^^^^^^^^^^^^^^^
901
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000902A PCH file can then be used as a prefix header when a :option:`-include`
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000903option is passed to ``clang``:
904
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000905.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000906
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000907 $ clang -include test.h test.c -o test
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000908
909The ``clang`` driver will first check if a PCH file for ``test.h`` is
910available; if so, the contents of ``test.h`` (and the files it includes)
911will be processed from the PCH file. Otherwise, Clang falls back to
912directly processing the content of ``test.h``. This mirrors the behavior
913of GCC.
914
915.. note::
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000916
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000917 Clang does *not* automatically use PCH files for headers that are directly
918 included within a source file. For example:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000919
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000920 .. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000921
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000922 $ clang -x c-header test.h -o test.h.pch
923 $ cat test.c
924 #include "test.h"
925 $ clang test.c -o test
926
927 In this example, ``clang`` will not automatically use the PCH file for
928 ``test.h`` since ``test.h`` was included directly in the source file and not
929 specified on the command line using :option:`-include`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000930
931Relocatable PCH Files
932^^^^^^^^^^^^^^^^^^^^^
933
934It is sometimes necessary to build a precompiled header from headers
935that are not yet in their final, installed locations. For example, one
936might build a precompiled header within the build tree that is then
937meant to be installed alongside the headers. Clang permits the creation
938of "relocatable" precompiled headers, which are built with a given path
939(into the build directory) and can later be used from an installed
940location.
941
942To build a relocatable precompiled header, place your headers into a
943subdirectory whose structure mimics the installed location. For example,
944if you want to build a precompiled header for the header ``mylib.h``
945that will be installed into ``/usr/include``, create a subdirectory
946``build/usr/include`` and place the header ``mylib.h`` into that
947subdirectory. If ``mylib.h`` depends on other headers, then they can be
948stored within ``build/usr/include`` in a way that mimics the installed
949location.
950
951Building a relocatable precompiled header requires two additional
952arguments. First, pass the ``--relocatable-pch`` flag to indicate that
953the resulting PCH file should be relocatable. Second, pass
Aaron Ballman51fb0312016-07-15 13:13:45 +0000954`-isysroot /path/to/build`, which makes all includes for your library
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000955relative to the build directory. For example:
956
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000957.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000958
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000959 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000960
961When loading the relocatable PCH file, the various headers used in the
962PCH file are found from the system header root. For example, ``mylib.h``
963can be found in ``/usr/include/mylib.h``. If the headers are installed
Aaron Ballman51fb0312016-07-15 13:13:45 +0000964in some other system root, the `-isysroot` option can be used provide
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000965a different system root from which the headers will be based. For
Aaron Ballman51fb0312016-07-15 13:13:45 +0000966example, `-isysroot /Developer/SDKs/MacOSX10.4u.sdk` will look for
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000967``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
968
969Relocatable precompiled headers are intended to be used in a limited
970number of cases where the compilation environment is tightly controlled
971and the precompiled header cannot be generated after headers have been
Argyrios Kyrtzidisf0ad09f2013-02-14 00:12:44 +0000972installed.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000973
Peter Collingbourne915df992015-05-15 18:33:32 +0000974.. _controlling-code-generation:
975
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000976Controlling Code Generation
977---------------------------
978
979Clang provides a number of ways to control code generation. The options
980are listed below.
981
Sean Silva4c280bd2013-06-21 23:50:58 +0000982**-f[no-]sanitize=check1,check2,...**
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000983 Turn on runtime checks for various forms of undefined or suspicious
984 behavior.
985
986 This option controls whether Clang adds runtime checks for various
987 forms of undefined or suspicious behavior, and is disabled by
988 default. If a check fails, a diagnostic message is produced at
989 runtime explaining the problem. The main checks are:
990
Richard Smithbb741f42012-12-13 07:29:23 +0000991 - .. _opt_fsanitize_address:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000992
Richard Smithbb741f42012-12-13 07:29:23 +0000993 ``-fsanitize=address``:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000994 :doc:`AddressSanitizer`, a memory error
995 detector.
Richard Smithbb741f42012-12-13 07:29:23 +0000996 - .. _opt_fsanitize_thread:
997
Dmitry Vyukov42de1082012-12-21 08:21:25 +0000998 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
Evgeniy Stepanov17d55902012-12-21 10:50:00 +0000999 - .. _opt_fsanitize_memory:
1000
1001 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
Alexey Samsonov1f7051e2015-12-04 22:50:44 +00001002 a detector of uninitialized reads. Requires instrumentation of all
1003 program code.
Richard Smithbb741f42012-12-13 07:29:23 +00001004 - .. _opt_fsanitize_undefined:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001005
Alexey Samsonov778fc722015-12-04 17:30:29 +00001006 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
1007 a fast and compatible undefined behavior checker.
Peter Collingbourne9881b782015-06-18 23:59:22 +00001008
Peter Collingbournec3772752013-08-07 22:47:34 +00001009 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
1010 flow analysis.
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001011 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
Alexey Samsonov907880e2015-06-19 19:57:46 +00001012 checks. Requires ``-flto``.
Peter Collingbournec4122c12015-06-15 21:08:13 +00001013 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
1014 protection against stack-based memory corruption errors.
Chad Rosierae229d52013-01-29 23:31:22 +00001015
Alexey Samsonov778fc722015-12-04 17:30:29 +00001016 There are more fine-grained checks available: see
1017 the :ref:`list <ubsan-checks>` of specific kinds of
Alexey Samsonov9eda6402015-12-04 21:30:58 +00001018 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
1019 of control flow integrity schemes.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001020
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001021 The ``-fsanitize=`` argument must also be provided when linking, in
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001022 order to link to the appropriate runtime library.
Richard Smith83c728b2013-07-19 19:06:48 +00001023
1024 It is not possible to combine more than one of the ``-fsanitize=address``,
1025 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
Alexey Samsonov88460172015-12-04 17:35:47 +00001026 program.
Richard Smith83c728b2013-07-19 19:06:48 +00001027
Alexey Samsonov88459522015-01-12 22:39:12 +00001028**-f[no-]sanitize-recover=check1,check2,...**
Kostya Serebryany40b82152016-05-04 20:24:54 +00001029
Kostya Serebryanyceb1add2016-05-04 20:21:47 +00001030**-f[no-]sanitize-recover=all**
Alexey Samsonov88459522015-01-12 22:39:12 +00001031
1032 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
1033 If the check is fatal, program will halt after the first error
1034 of this kind is detected and error report is printed.
1035
Alexey Samsonov778fc722015-12-04 17:30:29 +00001036 By default, non-fatal checks are those enabled by
1037 :doc:`UndefinedBehaviorSanitizer`,
Alexey Samsonov88459522015-01-12 22:39:12 +00001038 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
Yury Gribov5bfeca12015-11-11 10:45:48 +00001039 sanitizers may not support recovery (or not support it by default
1040 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
1041 is detected.
Alexey Samsonov88459522015-01-12 22:39:12 +00001042
Peter Collingbourne9881b782015-06-18 23:59:22 +00001043 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
1044 This means that if a check has been configured to trap elsewhere on the
1045 command line, or if the check traps by default, this flag will not have
1046 any effect unless that sanitizer's trapping behavior is disabled with
1047 ``-fno-sanitize-trap``.
1048
1049 For example, if a command line contains the flags ``-fsanitize=undefined
1050 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
1051 will have no effect on its own; it will need to be accompanied by
1052 ``-fno-sanitize-trap=alignment``.
1053
1054**-f[no-]sanitize-trap=check1,check2,...**
1055
1056 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
1057 option is intended for use in cases where the sanitizer runtime cannot
1058 be used (for instance, when building libc or a kernel module), or where
1059 the binary size increase caused by the sanitizer runtime is a concern.
1060
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001061 This flag is only compatible with :doc:`control flow integrity
1062 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
1063 checks other than ``vptr``. If this flag
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001064 is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
1065 will be implicitly disabled.
1066
1067 This flag is enabled by default for sanitizers in the ``cfi`` group.
Peter Collingbourne9881b782015-06-18 23:59:22 +00001068
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001069.. option:: -fsanitize-blacklist=/path/to/blacklist/file
1070
1071 Disable or modify sanitizer checks for objects (source files, functions,
1072 variables, types) listed in the file. See
1073 :doc:`SanitizerSpecialCaseList` for file format description.
1074
1075.. option:: -fno-sanitize-blacklist
1076
1077 Don't use blacklist file, if it was specified earlier in the command line.
1078
Alexey Samsonov8fffba12015-05-07 23:04:19 +00001079**-f[no-]sanitize-coverage=[type,features,...]**
1080
1081 Enable simple code coverage in addition to certain sanitizers.
1082 See :doc:`SanitizerCoverage` for more details.
1083
Peter Collingbournedc134532016-01-16 00:31:22 +00001084**-f[no-]sanitize-stats**
1085
1086 Enable simple statistics gathering for the enabled sanitizers.
1087 See :doc:`SanitizerStats` for more details.
1088
Peter Collingbourne9881b782015-06-18 23:59:22 +00001089.. option:: -fsanitize-undefined-trap-on-error
1090
1091 Deprecated alias for ``-fsanitize-trap=undefined``.
1092
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001093.. option:: -fsanitize-cfi-cross-dso
1094
1095 Enable cross-DSO control flow integrity checks. This flag modifies
1096 the behavior of sanitizers in the ``cfi`` group to allow checking
1097 of cross-DSO virtual and indirect calls.
1098
Justin Lebar84da8b22016-05-20 21:33:01 +00001099.. option:: -ffast-math
1100
1101 Enable fast-math mode. This defines the ``__FAST_MATH__`` preprocessor
1102 macro, and lets the compiler make aggressive, potentially-lossy assumptions
1103 about floating-point math. These include:
1104
1105 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1106 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1107 ``(a + b) * c == a * c + b * c``),
1108 * operands to floating-point operations are not equal to ``NaN`` and
1109 ``Inf``, and
1110 * ``+0`` and ``-0`` are interchangeable.
1111
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001112.. option:: -fdenormal-fp-math=[values]
1113
1114 Select which denormal numbers the code is permitted to require.
1115
1116 Valid values are: ``ieee``, ``preserve-sign``, and ``positive-zero``,
1117 which correspond to IEEE 754 denormal numbers, the sign of a
1118 flushed-to-zero number is preserved in the sign of 0, denormals are
1119 flushed to positive zero, respectively.
1120
Peter Collingbournefb532b92016-02-24 20:46:36 +00001121.. option:: -fwhole-program-vtables
1122
1123 Enable whole-program vtable optimizations, such as single-implementation
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001124 devirtualization and virtual constant propagation, for classes with
1125 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
Peter Collingbournefb532b92016-02-24 20:46:36 +00001126
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001127.. option:: -fno-assume-sane-operator-new
1128
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001129 Don't assume that the C++'s new operator is sane.
1130
1131 This option tells the compiler to do not assume that C++'s global
1132 new operator will always return a pointer that does not alias any
1133 other pointer when the function returns.
1134
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001135.. option:: -ftrap-function=[name]
1136
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001137 Instruct code generator to emit a function call to the specified
1138 function name for ``__builtin_trap()``.
1139
1140 LLVM code generator translates ``__builtin_trap()`` to a trap
1141 instruction if it is supported by the target ISA. Otherwise, the
1142 builtin is translated into a call to ``abort``. If this option is
1143 set, then the code generator will always lower the builtin to a call
1144 to the specified function regardless of whether the target ISA has a
1145 trap instruction. This option is useful for environments (e.g.
1146 deeply embedded) where a trap cannot be properly handled, or when
1147 some custom behavior is desired.
1148
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001149.. option:: -ftls-model=[model]
1150
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001151 Select which TLS model to use.
1152
1153 Valid values are: ``global-dynamic``, ``local-dynamic``,
1154 ``initial-exec`` and ``local-exec``. The default value is
1155 ``global-dynamic``. The compiler may use a different model if the
1156 selected model is not supported by the target, or if a more
1157 efficient model can be used. The TLS model can be overridden per
1158 variable using the ``tls_model`` attribute.
1159
Chih-Hung Hsieh2c656c92015-07-28 16:27:56 +00001160.. option:: -femulated-tls
1161
1162 Select emulated TLS model, which overrides all -ftls-model choices.
1163
1164 In emulated TLS mode, all access to TLS variables are converted to
1165 calls to __emutls_get_address in the runtime library.
1166
Silviu Barangaf9671dd2013-10-21 10:54:53 +00001167.. option:: -mhwdiv=[values]
1168
1169 Select the ARM modes (arm or thumb) that support hardware division
1170 instructions.
1171
1172 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
1173 This option is used to indicate which mode (arm or thumb) supports
1174 hardware division instructions. This only applies to the ARM
1175 architecture.
1176
Bernard Ogden18b57012013-10-29 09:47:51 +00001177.. option:: -m[no-]crc
1178
1179 Enable or disable CRC instructions.
1180
1181 This option is used to indicate whether CRC instructions are to
1182 be generated. This only applies to the ARM architecture.
1183
1184 CRC instructions are enabled by default on ARMv8.
1185
Amara Emerson05d816d2014-01-24 15:15:27 +00001186.. option:: -mgeneral-regs-only
Amara Emerson04e2ecf2014-01-23 15:48:30 +00001187
1188 Generate code which only uses the general purpose registers.
1189
1190 This option restricts the generated code to use general registers
1191 only. This only applies to the AArch64 architecture.
1192
Simon Dardisd0e83ba2016-05-27 15:13:31 +00001193.. option:: -mcompact-branches=[values]
1194
1195 Control the usage of compact branches for MIPSR6.
1196
1197 Valid values are: ``never``, ``optimal`` and ``always``.
1198 The default value is ``optimal`` which generates compact branches
1199 when a delay slot cannot be filled. ``never`` disables the usage of
1200 compact branches and ``always`` generates compact branches whenever
1201 possible.
1202
Yunzhong Gaoeecc9e972015-12-10 01:37:18 +00001203**-f[no-]max-type-align=[number]**
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00001204 Instruct the code generator to not enforce a higher alignment than the given
1205 number (of bytes) when accessing memory via an opaque pointer or reference.
1206 This cap is ignored when directly accessing a variable or when the pointee
1207 type has an explicit “aligned” attribute.
1208
1209 The value should usually be determined by the properties of the system allocator.
1210 Some builtin types, especially vector types, have very high natural alignments;
1211 when working with values of those types, Clang usually wants to use instructions
1212 that take advantage of that alignment. However, many system allocators do
1213 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
1214 this option to limit the alignment that the compiler can assume for an arbitrary
1215 pointer, which may point onto the heap.
1216
1217 This option does not affect the ABI alignment of types; the layout of structs and
1218 unions and the value returned by the alignof operator remain the same.
1219
1220 This option can be overridden on a case-by-case basis by putting an explicit
1221 “aligned” alignment on a struct, union, or typedef. For example:
1222
1223 .. code-block:: console
1224
1225 #include <immintrin.h>
1226 // Make an aligned typedef of the AVX-512 16-int vector type.
1227 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
1228
1229 void initialize_vector(__aligned_v16si *v) {
1230 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
Yunzhong Gaoeecc9e972015-12-10 01:37:18 +00001231 // value of -fmax-type-align.
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00001232 }
1233
Silviu Barangaf9671dd2013-10-21 10:54:53 +00001234
Bob Wilson3f2ed172014-06-17 00:45:30 +00001235Profile Guided Optimization
1236---------------------------
1237
1238Profile information enables better optimization. For example, knowing that a
1239branch is taken very frequently helps the compiler make better decisions when
1240ordering basic blocks. Knowing that a function ``foo`` is called more
1241frequently than another function ``bar`` helps the inliner.
1242
1243Clang supports profile guided optimization with two different kinds of
1244profiling. A sampling profiler can generate a profile with very low runtime
1245overhead, or you can build an instrumented version of the code that collects
1246more detailed profile information. Both kinds of profiles can provide execution
1247counts for instructions in the code and information on branches taken and
1248function invocation.
1249
1250Regardless of which kind of profiling you use, be careful to collect profiles
1251by running your code with inputs that are representative of the typical
1252behavior. Code that is not exercised in the profile will be optimized as if it
1253is unimportant, and the compiler may make poor optimization choices for code
1254that is disproportionately used while profiling.
1255
Diego Novillo46ab35d2015-05-28 21:30:04 +00001256Differences Between Sampling and Instrumentation
1257^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1258
1259Although both techniques are used for similar purposes, there are important
1260differences between the two:
1261
12621. Profile data generated with one cannot be used by the other, and there is no
1263 conversion tool that can convert one to the other. So, a profile generated
1264 via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
1265 Similarly, sampling profiles generated by external profilers must be
1266 converted and used with ``-fprofile-sample-use``.
1267
12682. Instrumentation profile data can be used for code coverage analysis and
1269 optimization.
1270
12713. Sampling profiles can only be used for optimization. They cannot be used for
1272 code coverage analysis. Although it would be technically possible to use
1273 sampling profiles for code coverage, sample-based profiles are too
1274 coarse-grained for code coverage purposes; it would yield poor results.
1275
12764. Sampling profiles must be generated by an external tool. The profile
1277 generated by that tool must then be converted into a format that can be read
1278 by LLVM. The section on sampling profilers describes one of the supported
1279 sampling profile formats.
1280
1281
Bob Wilson3f2ed172014-06-17 00:45:30 +00001282Using Sampling Profilers
1283^^^^^^^^^^^^^^^^^^^^^^^^
Diego Novilloa5256bf2014-04-23 15:21:07 +00001284
1285Sampling profilers are used to collect runtime information, such as
1286hardware counters, while your application executes. They are typically
Diego Novillo8ebff322014-04-23 15:21:20 +00001287very efficient and do not incur a large runtime overhead. The
Diego Novilloa5256bf2014-04-23 15:21:07 +00001288sample data collected by the profiler can be used during compilation
Diego Novillo8ebff322014-04-23 15:21:20 +00001289to determine what the most executed areas of the code are.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001290
Diego Novilloa5256bf2014-04-23 15:21:07 +00001291Using the data from a sample profiler requires some changes in the way
1292a program is built. Before the compiler can use profiling information,
1293the code needs to execute under the profiler. The following is the
1294usual build cycle when using sample profilers for optimization:
1295
12961. Build the code with source line table information. You can use all the
1297 usual build flags that you always build your application with. The only
Diego Novillo8ebff322014-04-23 15:21:20 +00001298 requirement is that you add ``-gline-tables-only`` or ``-g`` to the
Diego Novilloa5256bf2014-04-23 15:21:07 +00001299 command line. This is important for the profiler to be able to map
1300 instructions back to source line locations.
1301
1302 .. code-block:: console
1303
1304 $ clang++ -O2 -gline-tables-only code.cc -o code
1305
13062. Run the executable under a sampling profiler. The specific profiler
1307 you use does not really matter, as long as its output can be converted
1308 into the format that the LLVM optimizer understands. Currently, there
1309 exists a conversion tool for the Linux Perf profiler
1310 (https://perf.wiki.kernel.org/), so these examples assume that you
1311 are using Linux Perf to profile your code.
1312
1313 .. code-block:: console
1314
1315 $ perf record -b ./code
1316
1317 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
1318 Record (LBR) to record call chains. While this is not strictly required,
1319 it provides better call information, which improves the accuracy of
1320 the profile data.
1321
13223. Convert the collected profile data to LLVM's sample profile format.
1323 This is currently supported via the AutoFDO converter ``create_llvm_prof``.
1324 It is available at http://github.com/google/autofdo. Once built and
1325 installed, you can convert the ``perf.data`` file to LLVM using
1326 the command:
1327
1328 .. code-block:: console
1329
1330 $ create_llvm_prof --binary=./code --out=code.prof
1331
Diego Novillo9e430842014-04-23 15:21:23 +00001332 This will read ``perf.data`` and the binary file ``./code`` and emit
Diego Novilloa5256bf2014-04-23 15:21:07 +00001333 the profile data in ``code.prof``. Note that if you ran ``perf``
1334 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
1335 calling ``create_llvm_prof``.
1336
13374. Build the code again using the collected profile. This step feeds
1338 the profile back to the optimizers. This should result in a binary
Diego Novillo8ebff322014-04-23 15:21:20 +00001339 that executes faster than the original one. Note that you are not
1340 required to build the code with the exact same arguments that you
1341 used in the first step. The only requirement is that you build the code
1342 with ``-gline-tables-only`` and ``-fprofile-sample-use``.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001343
1344 .. code-block:: console
1345
1346 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
1347
1348
Diego Novillo46ab35d2015-05-28 21:30:04 +00001349Sample Profile Formats
1350""""""""""""""""""""""
Diego Novilloa5256bf2014-04-23 15:21:07 +00001351
Diego Novillo46ab35d2015-05-28 21:30:04 +00001352Since external profilers generate profile data in a variety of custom formats,
1353the data generated by the profiler must be converted into a format that can be
1354read by the backend. LLVM supports three different sample profile formats:
Diego Novilloa5256bf2014-04-23 15:21:07 +00001355
Diego Novillo46ab35d2015-05-28 21:30:04 +000013561. ASCII text. This is the easiest one to generate. The file is divided into
1357 sections, which correspond to each of the functions with profile
Diego Novillo33452762015-10-14 18:37:39 +00001358 information. The format is described below. It can also be generated from
1359 the binary or gcov formats using the ``llvm-profdata`` tool.
Diego Novilloe0d289e2015-05-22 16:05:07 +00001360
Diego Novillo46ab35d2015-05-28 21:30:04 +000013612. Binary encoding. This uses a more efficient encoding that yields smaller
Diego Novillo33452762015-10-14 18:37:39 +00001362 profile files. This is the format generated by the ``create_llvm_prof`` tool
1363 in http://github.com/google/autofdo.
Diego Novillo46ab35d2015-05-28 21:30:04 +00001364
13653. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
Diego Novillo33452762015-10-14 18:37:39 +00001366 is only interesting in environments where GCC and Clang co-exist. This
1367 encoding is only generated by the ``create_gcov`` tool in
1368 http://github.com/google/autofdo. It can be read by LLVM and
1369 ``llvm-profdata``, but it cannot be generated by either.
Diego Novillo46ab35d2015-05-28 21:30:04 +00001370
1371If you are using Linux Perf to generate sampling profiles, you can use the
1372conversion tool ``create_llvm_prof`` described in the previous section.
1373Otherwise, you will need to write a conversion tool that converts your
1374profiler's native format into one of these three.
1375
1376
1377Sample Profile Text Format
1378""""""""""""""""""""""""""
1379
1380This section describes the ASCII text format for sampling profiles. It is,
1381arguably, the easiest one to generate. If you are interested in generating any
1382of the other two, consult the ``ProfileData`` library in in LLVM's source tree
Diego Novillo843dc6f2015-10-19 15:53:17 +00001383(specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
Diego Novilloa5256bf2014-04-23 15:21:07 +00001384
1385.. code-block:: console
1386
1387 function1:total_samples:total_head_samples
Diego Novillo33452762015-10-14 18:37:39 +00001388 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
1389 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
1390 ...
1391 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
1392 offsetA[.discriminator]: fnA:num_of_total_samples
1393 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
1394 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
1395 offsetB[.discriminator]: fnB:num_of_total_samples
1396 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
Diego Novilloa5256bf2014-04-23 15:21:07 +00001397
Diego Novillo33452762015-10-14 18:37:39 +00001398This is a nested tree in which the identation represents the nesting level
1399of the inline stack. There are no blank lines in the file. And the spacing
1400within a single line is fixed. Additional spaces will result in an error
1401while reading the file.
1402
1403Any line starting with the '#' character is completely ignored.
1404
1405Inlined calls are represented with indentation. The Inline stack is a
1406stack of source locations in which the top of the stack represents the
1407leaf function, and the bottom of the stack represents the actual
1408symbol to which the instruction belongs.
Diego Novillo8ebff322014-04-23 15:21:20 +00001409
Diego Novilloa5256bf2014-04-23 15:21:07 +00001410Function names must be mangled in order for the profile loader to
1411match them in the current translation unit. The two numbers in the
1412function header specify how many total samples were accumulated in the
1413function (first number), and the total number of samples accumulated
Diego Novillo8ebff322014-04-23 15:21:20 +00001414in the prologue of the function (second number). This head sample
1415count provides an indicator of how frequently the function is invoked.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001416
Diego Novillo33452762015-10-14 18:37:39 +00001417There are two types of lines in the function body.
1418
1419- Sampled line represents the profile information of a source location.
1420 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
1421
1422- Callsite line represents the profile information of an inlined callsite.
1423 ``offsetA[.discriminator]: fnA:num_of_total_samples``
1424
Diego Novilloa5256bf2014-04-23 15:21:07 +00001425Each sampled line may contain several items. Some are optional (marked
1426below):
1427
1428a. Source line offset. This number represents the line number
1429 in the function where the sample was collected. The line number is
1430 always relative to the line where symbol of the function is
1431 defined. So, if the function has its header at line 280, the offset
1432 13 is at line 293 in the file.
1433
Diego Novillo897c59c2014-04-23 15:21:21 +00001434 Note that this offset should never be a negative number. This could
1435 happen in cases like macros. The debug machinery will register the
1436 line number at the point of macro expansion. So, if the macro was
1437 expanded in a line before the start of the function, the profile
1438 converter should emit a 0 as the offset (this means that the optimizers
1439 will not be able to associate a meaningful weight to the instructions
1440 in the macro).
1441
Diego Novilloa5256bf2014-04-23 15:21:07 +00001442b. [OPTIONAL] Discriminator. This is used if the sampled program
1443 was compiled with DWARF discriminator support
Diego Novillo8ebff322014-04-23 15:21:20 +00001444 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
Diego Novillo897c59c2014-04-23 15:21:21 +00001445 DWARF discriminators are unsigned integer values that allow the
1446 compiler to distinguish between multiple execution paths on the
1447 same source line location.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001448
Diego Novillo8ebff322014-04-23 15:21:20 +00001449 For example, consider the line of code ``if (cond) foo(); else bar();``.
1450 If the predicate ``cond`` is true 80% of the time, then the edge
1451 into function ``foo`` should be considered to be taken most of the
1452 time. But both calls to ``foo`` and ``bar`` are at the same source
1453 line, so a sample count at that line is not sufficient. The
1454 compiler needs to know which part of that line is taken more
1455 frequently.
1456
1457 This is what discriminators provide. In this case, the calls to
1458 ``foo`` and ``bar`` will be at the same line, but will have
1459 different discriminator values. This allows the compiler to correctly
1460 set edge weights into ``foo`` and ``bar``.
1461
1462c. Number of samples. This is an integer quantity representing the
1463 number of samples collected by the profiler at this source
1464 location.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001465
1466d. [OPTIONAL] Potential call targets and samples. If present, this
1467 line contains a call instruction. This models both direct and
Diego Novilloa5256bf2014-04-23 15:21:07 +00001468 number of samples. For example,
1469
1470 .. code-block:: console
1471
1472 130: 7 foo:3 bar:2 baz:7
1473
1474 The above means that at relative line offset 130 there is a call
Diego Novillo8ebff322014-04-23 15:21:20 +00001475 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
1476 with ``baz()`` being the relatively more frequently called target.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001477
Diego Novillo33452762015-10-14 18:37:39 +00001478As an example, consider a program with the call chain ``main -> foo -> bar``.
1479When built with optimizations enabled, the compiler may inline the
1480calls to ``bar`` and ``foo`` inside ``main``. The generated profile
1481could then be something like this:
1482
1483.. code-block:: console
1484
1485 main:35504:0
1486 1: _Z3foov:35504
1487 2: _Z32bari:31977
1488 1.1: 31977
1489 2: 0
1490
1491This profile indicates that there were a total of 35,504 samples
1492collected in main. All of those were at line 1 (the call to ``foo``).
1493Of those, 31,977 were spent inside the body of ``bar``. The last line
1494of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
1495samples were collected there.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001496
Bob Wilson3f2ed172014-06-17 00:45:30 +00001497Profiling with Instrumentation
1498^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1499
1500Clang also supports profiling via instrumentation. This requires building a
1501special instrumented version of the code and has some runtime
1502overhead during the profiling, but it provides more detailed results than a
1503sampling profiler. It also provides reproducible results, at least to the
1504extent that the code behaves consistently across runs.
1505
1506Here are the steps for using profile guided optimization with
1507instrumentation:
1508
15091. Build an instrumented version of the code by compiling and linking with the
1510 ``-fprofile-instr-generate`` option.
1511
1512 .. code-block:: console
1513
1514 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
1515
15162. Run the instrumented executable with inputs that reflect the typical usage.
1517 By default, the profile data will be written to a ``default.profraw`` file
Xinliang David Li7cd5e382016-07-20 23:32:50 +00001518 in the current directory. You can override that default by using option
1519 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
1520 environment variable to specify an alternate file. If non-default file name
1521 is specified by both the environment variable and the command line option,
1522 the environment variable takes precedence. The file name pattern specified
1523 can include different modifiers: ``%p``, ``%h``, and ``%m``.
1524
Bob Wilson3f2ed172014-06-17 00:45:30 +00001525 Any instance of ``%p`` in that file name will be replaced by the process
1526 ID, so that you can easily distinguish the profile output from multiple
1527 runs.
1528
1529 .. code-block:: console
1530
1531 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
1532
Xinliang David Li7cd5e382016-07-20 23:32:50 +00001533 The modifier ``%h`` can be used in scenarios where the same instrumented
1534 binary is run in multiple different host machines dumping profile data
1535 to a shared network based storage. The ``%h`` specifier will be substituted
1536 with the hostname so that profiles collected from different hosts do not
1537 clobber each other.
1538
1539 While the use of ``%p`` specifier can reduce the likelihood for the profiles
1540 dumped from different processes to clobber each other, such clobbering can still
1541 happen because of the ``pid`` re-use by the OS. Another side-effect of using
1542 ``%p`` is that the storage requirement for raw profile data files is greatly
1543 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
1544 name. When this specifier is used, the profiler runtime will substitute ``%m``
1545 with a unique integer identifier associated with the instrumented binary. Additionally,
1546 multiple raw profiles dumped from different processes that share a file system (can be
1547 on different hosts) will be automatically merged by the profiler runtime during the
1548 dumping. If the program links in multiple instrumented shared libraries, each library
1549 will dump the profile data into its own profile data file (with its unique integer
1550 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
1551 profile data generated by profiler runtime. The resulting merged "raw" profile data
1552 file still needs to be converted to a different format expected by the compiler (
1553 see step 3 below).
1554
1555 .. code-block:: console
1556
1557 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
1558
1559
Bob Wilson3f2ed172014-06-17 00:45:30 +000015603. Combine profiles from multiple runs and convert the "raw" profile format to
Diego Novillo46ab35d2015-05-28 21:30:04 +00001561 the input expected by clang. Use the ``merge`` command of the
1562 ``llvm-profdata`` tool to do this.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001563
1564 .. code-block:: console
1565
1566 $ llvm-profdata merge -output=code.profdata code-*.profraw
1567
1568 Note that this step is necessary even when there is only one "raw" profile,
1569 since the merge operation also changes the file format.
1570
15714. Build the code again using the ``-fprofile-instr-use`` option to specify the
1572 collected profile data.
1573
1574 .. code-block:: console
1575
1576 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
1577
1578 You can repeat step 4 as often as you like without regenerating the
1579 profile. As you make changes to your code, clang may no longer be able to
1580 use the profile data. It will warn you when this happens.
1581
Sean Silvaa834ff22016-07-16 02:54:58 +00001582Profile generation using an alternative instrumentation method can be
1583controlled by the GCC-compatible flags ``-fprofile-generate`` and
1584``-fprofile-use``. Although these flags are semantically equivalent to
1585their GCC counterparts, they *do not* handle GCC-compatible profiles.
1586They are only meant to implement GCC's semantics with respect to
1587profile creation and use.
Diego Novillo578caf52015-07-09 17:23:53 +00001588
1589.. option:: -fprofile-generate[=<dirname>]
1590
Sean Silvaa834ff22016-07-16 02:54:58 +00001591 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
1592 an alterantive instrumentation method for profile generation. When
1593 given a directory name, it generates the profile file
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001594 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
1595 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
1596 will be substibuted with a unique id documented in step 2 above. In other words,
1597 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
1598 merging is turned on by default, so there will no longer any risk of profile
1599 clobbering from different running processes. For example,
Diego Novillo578caf52015-07-09 17:23:53 +00001600
1601 .. code-block:: console
1602
1603 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
1604
1605 When ``code`` is executed, the profile will be written to the file
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001606 ``yyy/zzz/default_xxxx.profraw``.
Diego Novillo578caf52015-07-09 17:23:53 +00001607
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001608 To generate the profile data file with the compiler readable format, the
1609 ``llvm-profdata`` tool can be used with the profile directory as the input:
Diego Novillo578caf52015-07-09 17:23:53 +00001610
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001611 .. code-block:: console
Diego Novillo578caf52015-07-09 17:23:53 +00001612
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001613 $ llvm-profdata merge -output=code.profdata yyy/zzz/
1614
1615 If the user wants to turn off the auto-merging feature, or simply override the
1616 the profile dumping path specified at command line, the environment variable
1617 ``LLVM_PROFILE_FILE`` can still be used to override
1618 the directory and filename for the profile file at runtime.
Diego Novillo578caf52015-07-09 17:23:53 +00001619
1620.. option:: -fprofile-use[=<pathname>]
1621
1622 Without any other arguments, ``-fprofile-use`` behaves identically to
1623 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
1624 profile file, it reads from that file. If ``pathname`` is a directory name,
1625 it reads from ``pathname/default.profdata``.
1626
Diego Novillo758f3f52015-08-05 21:49:51 +00001627Disabling Instrumentation
1628^^^^^^^^^^^^^^^^^^^^^^^^^
1629
1630In certain situations, it may be useful to disable profile generation or use
1631for specific files in a build, without affecting the main compilation flags
1632used for the other files in the project.
1633
1634In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
1635``-fno-profile-generate``) to disable profile generation, and
1636``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
1637
1638Note that these flags should appear after the corresponding profile
1639flags to have an effect.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001640
Paul Robinson0334a042015-12-19 19:41:48 +00001641Controlling Debug Information
1642-----------------------------
1643
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001644Controlling Size of Debug Information
Paul Robinson0334a042015-12-19 19:41:48 +00001645^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001646
1647Debug info kind generated by Clang can be set by one of the flags listed
1648below. If multiple flags are present, the last one is used.
1649
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001650.. option:: -g0
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001651
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001652 Don't generate any debug info (default).
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001653
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001654.. option:: -gline-tables-only
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001655
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001656 Generate line number tables only.
1657
1658 This kind of debug info allows to obtain stack traces with function names,
1659 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
1660 doesn't contain any other data (e.g. description of local variables or
1661 function parameters).
1662
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001663.. option:: -fstandalone-debug
Adrian Prantl36b80672014-06-13 21:12:31 +00001664
1665 Clang supports a number of optimizations to reduce the size of debug
1666 information in the binary. They work based on the assumption that
1667 the debug type information can be spread out over multiple
1668 compilation units. For instance, Clang will not emit type
1669 definitions for types that are not needed by a module and could be
1670 replaced with a forward declaration. Further, Clang will only emit
1671 type info for a dynamic C++ class in the module that contains the
1672 vtable for the class.
1673
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001674 The **-fstandalone-debug** option turns off these optimizations.
Adrian Prantl36b80672014-06-13 21:12:31 +00001675 This is useful when working with 3rd-party libraries that don't come
1676 with debug information. Note that Clang will never emit type
1677 information for types that are not referenced at all by the program.
1678
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001679.. option:: -fno-standalone-debug
1680
1681 On Darwin **-fstandalone-debug** is enabled by default. The
1682 **-fno-standalone-debug** option can be used to get to turn on the
1683 vtable-based optimization described above.
1684
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001685.. option:: -g
1686
1687 Generate complete debug info.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001688
Paul Robinson0334a042015-12-19 19:41:48 +00001689Controlling Debugger "Tuning"
1690^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1691
1692While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
1693different debuggers may know how to take advantage of different specific DWARF
1694features. You can "tune" the debug info for one of several different debuggers.
1695
1696.. option:: -ggdb, -glldb, -gsce
1697
Paul Robinson8ce9b442016-08-15 18:45:52 +00001698 Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg|
Paul Robinson0334a042015-12-19 19:41:48 +00001699 debugger, respectively. Each of these options implies **-g**. (Therefore, if
1700 you want both **-gline-tables-only** and debugger tuning, the tuning option
1701 must come first.)
1702
1703
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001704Comment Parsing Options
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001705-----------------------
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001706
1707Clang parses Doxygen and non-Doxygen style documentation comments and attaches
1708them to the appropriate declaration nodes. By default, it only parses
1709Doxygen-style comments and ignores ordinary comments starting with ``//`` and
1710``/*``.
1711
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001712.. option:: -Wdocumentation
1713
1714 Emit warnings about use of documentation comments. This warning group is off
1715 by default.
1716
1717 This includes checking that ``\param`` commands name parameters that actually
1718 present in the function signature, checking that ``\returns`` is used only on
1719 functions that actually return a value etc.
1720
1721.. option:: -Wno-documentation-unknown-command
1722
1723 Don't warn when encountering an unknown Doxygen command.
1724
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001725.. option:: -fparse-all-comments
1726
1727 Parse all comments as documentation comments (including ordinary comments
1728 starting with ``//`` and ``/*``).
1729
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001730.. option:: -fcomment-block-commands=[commands]
1731
1732 Define custom documentation commands as block commands. This allows Clang to
1733 construct the correct AST for these custom commands, and silences warnings
1734 about unknown commands. Several commands must be separated by a comma
1735 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
1736 custom commands ``\foo`` and ``\bar``.
1737
1738 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
1739 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
1740 as above.
1741
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001742.. _c:
1743
1744C Language Features
1745===================
1746
1747The support for standard C in clang is feature-complete except for the
1748C99 floating-point pragmas.
1749
1750Extensions supported by clang
1751-----------------------------
1752
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001753See :doc:`LanguageExtensions`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001754
1755Differences between various standard modes
1756------------------------------------------
1757
1758clang supports the -std option, which changes what language mode clang
Richard Smithab506ad2014-10-20 23:26:58 +00001759uses. The supported modes for C are c89, gnu89, c94, c99, gnu99, c11,
1760gnu11, and various aliases for those modes. If no -std option is
1761specified, clang defaults to gnu11 mode. Many C99 and C11 features are
1762supported in earlier modes as a conforming extension, with a warning. Use
1763``-pedantic-errors`` to request an error if a feature from a later standard
1764revision is used in an earlier mode.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001765
1766Differences between all ``c*`` and ``gnu*`` modes:
1767
1768- ``c*`` modes define "``__STRICT_ANSI__``".
1769- Target-specific defines not prefixed by underscores, like "linux",
1770 are defined in ``gnu*`` modes.
1771- Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
1772 the -trigraphs option.
1773- The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
1774 the variants "``__asm__``" and "``__typeof__``" are recognized in all
1775 modes.
1776- The Apple "blocks" extension is recognized by default in ``gnu*`` modes
1777 on some platforms; it can be enabled in any mode with the "-fblocks"
1778 option.
1779- Arrays that are VLA's according to the standard, but which can be
1780 constant folded by the frontend are treated as fixed size arrays.
1781 This occurs for things like "int X[(1, 2)];", which is technically a
1782 VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
1783
1784Differences between ``*89`` and ``*99`` modes:
1785
1786- The ``*99`` modes default to implementing "inline" as specified in C99,
1787 while the ``*89`` modes implement the GNU version. This can be
1788 overridden for individual functions with the ``__gnu_inline__``
1789 attribute.
1790- Digraphs are not recognized in c89 mode.
1791- The scope of names defined inside a "for", "if", "switch", "while",
1792 or "do" statement is different. (example: "``if ((struct x {int
1793 x;}*)0) {}``".)
1794- ``__STDC_VERSION__`` is not defined in ``*89`` modes.
1795- "inline" is not recognized as a keyword in c89 mode.
1796- "restrict" is not recognized as a keyword in ``*89`` modes.
1797- Commas are allowed in integer constant expressions in ``*99`` modes.
1798- Arrays which are not lvalues are not implicitly promoted to pointers
1799 in ``*89`` modes.
1800- Some warnings are different.
1801
Richard Smithab506ad2014-10-20 23:26:58 +00001802Differences between ``*99`` and ``*11`` modes:
1803
1804- Warnings for use of C11 features are disabled.
1805- ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
1806
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001807c94 mode is identical to c89 mode except that digraphs are enabled in
1808c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
1809
1810GCC extensions not implemented yet
1811----------------------------------
1812
1813clang tries to be compatible with gcc as much as possible, but some gcc
1814extensions are not implemented yet:
1815
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001816- clang does not support decimal floating point types (``_Decimal32`` and
1817 friends) or fixed-point types (``_Fract`` and friends); nobody has
1818 expressed interest in these features yet, so it's hard to say when
1819 they will be implemented.
1820- clang does not support nested functions; this is a complex feature
1821 which is infrequently used, so it is unlikely to be implemented
1822 anytime soon. In C++11 it can be emulated by assigning lambda
1823 functions to local variables, e.g:
1824
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001825 .. code-block:: cpp
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001826
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001827 auto const local_function = [&](int parameter) {
1828 // Do something
1829 };
1830 ...
1831 local_function(1);
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001832
Michael Kuperstein94b25ec2016-12-12 19:11:39 +00001833- clang only supports global register variables when the register specified
1834 is non-allocatable (e.g. the stack pointer). Support for general global
1835 register variables is unlikely to be implemented soon because it requires
1836 additional LLVM backend support.
Andrey Bokhanko5dfd5b62016-02-11 13:27:02 +00001837- clang does not support static initialization of flexible array
1838 members. This appears to be a rarely used extension, but could be
1839 implemented pending user demand.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001840- clang does not support
1841 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
1842 used rarely, but in some potentially interesting places, like the
1843 glibc headers, so it may be implemented pending user demand. Note
1844 that because clang pretends to be like GCC 4.2, and this extension
1845 was introduced in 4.3, the glibc headers will not try to use this
1846 extension with clang at the moment.
1847- clang does not support the gcc extension for forward-declaring
1848 function parameters; this has not shown up in any real-world code
1849 yet, though, so it might never be implemented.
1850
1851This is not a complete list; if you find an unsupported extension
1852missing from this list, please send an e-mail to cfe-dev. This list
1853currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
1854list does not include bugs in mostly-implemented features; please see
1855the `bug
1856tracker <http://llvm.org/bugs/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
1857for known existing bugs (FIXME: Is there a section for bug-reporting
1858guidelines somewhere?).
1859
1860Intentionally unsupported GCC extensions
1861----------------------------------------
1862
1863- clang does not support the gcc extension that allows variable-length
1864 arrays in structures. This is for a few reasons: one, it is tricky to
1865 implement, two, the extension is completely undocumented, and three,
1866 the extension appears to be rarely used. Note that clang *does*
1867 support flexible array members (arrays with a zero or unspecified
1868 size at the end of a structure).
1869- clang does not have an equivalent to gcc's "fold"; this means that
1870 clang doesn't accept some constructs gcc might accept in contexts
1871 where a constant expression is required, like "x-x" where x is a
1872 variable.
1873- clang does not support ``__builtin_apply`` and friends; this extension
1874 is extremely obscure and difficult to implement reliably.
1875
1876.. _c_ms:
1877
1878Microsoft extensions
1879--------------------
1880
Reid Kleckner2a5d34b2016-03-28 20:42:41 +00001881clang has support for many extensions from Microsoft Visual C++. To enable these
1882extensions, use the ``-fms-extensions`` command-line option. This is the default
1883for Windows targets. Clang does not implement every pragma or declspec provided
1884by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
1885comment(lib)`` are well supported.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001886
Richard Smith48d1b652013-12-12 02:42:17 +00001887clang has a ``-fms-compatibility`` flag that makes clang accept enough
Reid Kleckner993e72a2013-09-20 17:04:25 +00001888invalid C++ to be able to parse most Microsoft headers. For example, it
1889allows `unqualified lookup of dependent base class members
Reid Klecknereb248d72013-09-20 17:54:39 +00001890<http://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
1891a common compatibility issue with clang. This flag is enabled by default
Reid Kleckner993e72a2013-09-20 17:04:25 +00001892for Windows targets.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001893
Richard Smith48d1b652013-12-12 02:42:17 +00001894``-fdelayed-template-parsing`` lets clang delay parsing of function template
1895definitions until the end of a translation unit. This flag is enabled by
1896default for Windows targets.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001897
Reid Kleckner2a5d34b2016-03-28 20:42:41 +00001898For compatibility with existing code that compiles with MSVC, clang defines the
1899``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
1900and 180000000 respectively, making clang look like an early release of Visual
1901C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It
1902accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
1903compatibility version makes clang behave more like that version of MSVC. For
1904example, ``-fms-compatibility-version=19`` will enable C++14 features and define
1905``char16_t`` and ``char32_t`` as builtin types.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001906
1907.. _cxx:
1908
1909C++ Language Features
1910=====================
1911
1912clang fully implements all of standard C++98 except for exported
Richard Smith48d1b652013-12-12 02:42:17 +00001913templates (which were removed in C++11), and all of standard C++11
1914and the current draft standard for C++1y.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001915
1916Controlling implementation limits
1917---------------------------------
1918
Richard Smithb3a14522013-02-22 01:59:51 +00001919.. option:: -fbracket-depth=N
1920
1921 Sets the limit for nested parentheses, brackets, and braces to N. The
1922 default is 256.
1923
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001924.. option:: -fconstexpr-depth=N
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001925
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001926 Sets the limit for recursive constexpr function invocations to N. The
1927 default is 512.
1928
1929.. option:: -ftemplate-depth=N
1930
1931 Sets the limit for recursively nested template instantiations to N. The
Richard Smith79c927b2013-11-06 19:31:51 +00001932 default is 256.
1933
1934.. option:: -foperator-arrow-depth=N
1935
1936 Sets the limit for iterative calls to 'operator->' functions to N. The
1937 default is 256.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001938
1939.. _objc:
1940
1941Objective-C Language Features
1942=============================
1943
1944.. _objcxx:
1945
1946Objective-C++ Language Features
1947===============================
1948
Alexey Bataevae8c17e2015-08-24 05:31:10 +00001949.. _openmp:
1950
1951OpenMP Features
1952===============
1953
1954Clang supports all OpenMP 3.1 directives and clauses. In addition, some
1955features of OpenMP 4.0 are supported. For example, ``#pragma omp simd``,
1956``#pragma omp for simd``, ``#pragma omp parallel for simd`` directives, extended
1957set of atomic constructs, ``proc_bind`` clause for all parallel-based
1958directives, ``depend`` clause for ``#pragma omp task`` directive (except for
1959array sections), ``#pragma omp cancel`` and ``#pragma omp cancellation point``
1960directives, and ``#pragma omp taskgroup`` directive.
1961
Aaron Ballman51fb0312016-07-15 13:13:45 +00001962Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
1963`-fno-openmp`.
Alexey Bataevae8c17e2015-08-24 05:31:10 +00001964
1965Controlling implementation limits
1966---------------------------------
1967
1968.. option:: -fopenmp-use-tls
1969
1970 Controls code generation for OpenMP threadprivate variables. In presence of
1971 this option all threadprivate variables are generated the same way as thread
Aaron Ballman51fb0312016-07-15 13:13:45 +00001972 local variables, using TLS support. If `-fno-openmp-use-tls`
Alexey Bataevae8c17e2015-08-24 05:31:10 +00001973 is provided or target does not support TLS, code generation for threadprivate
1974 variables relies on OpenMP runtime library.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001975
1976.. _target_features:
1977
1978Target-Specific Features and Limitations
1979========================================
1980
1981CPU Architectures Features and Limitations
1982------------------------------------------
1983
1984X86
1985^^^
1986
1987The support for X86 (both 32-bit and 64-bit) is considered stable on
Nico Weberab88f0b2014-03-07 18:09:57 +00001988Darwin (Mac OS X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001989to correctly compile many large C, C++, Objective-C, and Objective-C++
1990codebases.
1991
Richard Smith48d1b652013-12-12 02:42:17 +00001992On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
David Woodhouseddf89852014-01-23 14:32:46 +00001993Microsoft x64 calling convention. You might need to tweak
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001994``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
1995
Aaron Ballman51fb0312016-07-15 13:13:45 +00001996For the X86 target, clang supports the `-m16` command line
David Woodhouseddf89852014-01-23 14:32:46 +00001997argument which enables 16-bit code output. This is broadly similar to
1998using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
1999and the ABI remains 32-bit but the assembler emits instructions
2000appropriate for a CPU running in 16-bit mode, with address-size and
2001operand-size prefixes to enable 32-bit addressing and operations.
2002
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002003ARM
2004^^^
2005
2006The support for ARM (specifically ARMv6 and ARMv7) is considered stable
2007on Darwin (iOS): it has been tested to correctly compile many large C,
2008C++, Objective-C, and Objective-C++ codebases. Clang only supports a
2009limited number of ARM architectures. It does not yet fully support
2010ARMv5, for example.
2011
Roman Divacky786d32e2013-09-11 17:12:49 +00002012PowerPC
2013^^^^^^^
2014
2015The support for PowerPC (especially PowerPC64) is considered stable
2016on Linux and FreeBSD: it has been tested to correctly compile many
2017large C and C++ codebases. PowerPC (32bit) is still missing certain
2018features (e.g. PIC code on ELF platforms).
2019
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002020Other platforms
2021^^^^^^^^^^^^^^^
2022
Roman Divacky786d32e2013-09-11 17:12:49 +00002023clang currently contains some support for other architectures (e.g. Sparc);
2024however, significant pieces of code generation are still missing, and they
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002025haven't undergone significant testing.
2026
2027clang contains limited support for the MSP430 embedded processor, but
2028both the clang support and the LLVM backend support are highly
2029experimental.
2030
2031Other platforms are completely unsupported at the moment. Adding the
2032minimal support needed for parsing and semantic analysis on a new
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002033platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002034tree. This level of support is also sufficient for conversion to LLVM IR
2035for simple programs. Proper support for conversion to LLVM IR requires
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002036adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002037change soon, though. Generating assembly requires a suitable LLVM
2038backend.
2039
2040Operating System Features and Limitations
2041-----------------------------------------
2042
Nico Weberab88f0b2014-03-07 18:09:57 +00002043Darwin (Mac OS X)
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002044^^^^^^^^^^^^^^^^^
2045
Nico Weberc7cb9402014-03-07 18:11:40 +00002046Thread Sanitizer is not supported.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002047
2048Windows
2049^^^^^^^
2050
Richard Smith48d1b652013-12-12 02:42:17 +00002051Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
2052platforms.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002053
Reid Kleckner725b7b32013-09-05 21:29:35 +00002054See also :ref:`Microsoft Extensions <c_ms>`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002055
2056Cygwin
2057""""""
2058
2059Clang works on Cygwin-1.7.
2060
2061MinGW32
2062"""""""
2063
2064Clang works on some mingw32 distributions. Clang assumes directories as
2065below;
2066
2067- ``C:/mingw/include``
2068- ``C:/mingw/lib``
2069- ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
2070
2071On MSYS, a few tests might fail.
2072
2073MinGW-w64
2074"""""""""
2075
2076For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
2077assumes as below;
2078
2079- ``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)``
2080- ``some_directory/bin/gcc.exe``
2081- ``some_directory/bin/clang.exe``
2082- ``some_directory/bin/clang++.exe``
2083- ``some_directory/bin/../include/c++/GCC_version``
2084- ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
2085- ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
2086- ``some_directory/bin/../include/c++/GCC_version/backward``
2087- ``some_directory/bin/../x86_64-w64-mingw32/include``
2088- ``some_directory/bin/../i686-w64-mingw32/include``
2089- ``some_directory/bin/../include``
2090
2091This directory layout is standard for any toolchain you will find on the
2092official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
2093
2094Clang expects the GCC executable "gcc.exe" compiled for
2095``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
2096
2097`Some tests might fail <http://llvm.org/bugs/show_bug.cgi?id=9072>`_ on
2098``x86_64-w64-mingw32``.
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002099
2100.. _clang-cl:
2101
2102clang-cl
2103========
2104
2105clang-cl is an alternative command-line interface to Clang driver, designed for
2106compatibility with the Visual C++ compiler, cl.exe.
2107
2108To enable clang-cl to find system headers, libraries, and the linker when run
2109from the command-line, it should be executed inside a Visual Studio Native Tools
2110Command Prompt or a regular Command Prompt where the environment has been set
2111up using e.g. `vcvars32.bat <http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
2112
2113clang-cl can also be used from inside Visual Studio by using an LLVM Platform
2114Toolset.
2115
2116Command-Line Options
2117--------------------
2118
2119To be compatible with cl.exe, clang-cl supports most of the same command-line
2120options. Those options can start with either ``/`` or ``-``. It also supports
2121some of Clang's core options, such as the ``-W`` options.
2122
2123Options that are known to clang-cl, but not currently supported, are ignored
2124with a warning. For example:
2125
2126 ::
2127
Hans Wennborg0d080622015-08-12 19:35:01 +00002128 clang-cl.exe: warning: argument unused during compilation: '/AI'
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002129
2130To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
2131
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002132Options that are not known to clang-cl will be ignored by default. Use the
2133``-Werror=unknown-argument`` option in order to treat them as errors. If these
2134options are spelled with a leading ``/``, they will be mistaken for a filename:
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002135
2136 ::
2137
2138 clang-cl.exe: error: no such file or directory: '/foobar'
2139
2140Please `file a bug <http://llvm.org/bugs/enter_bug.cgi?product=clang&component=Driver>`_
2141for any valid cl.exe flags that clang-cl does not understand.
2142
2143Execute ``clang-cl /?`` to see a list of supported options:
2144
2145 ::
2146
Hans Wennborg35487d82014-08-04 21:07:58 +00002147 CL.EXE COMPATIBILITY OPTIONS:
2148 /? Display available options
2149 /arch:<value> Set architecture for code generation
Hans Wennborge8178e82016-02-12 01:01:37 +00002150 /Brepro- Emit an object file which cannot be reproduced over time
2151 /Brepro Emit an object file which can be reproduced over time
Hans Wennborg35487d82014-08-04 21:07:58 +00002152 /C Don't discard comments when preprocessing
2153 /c Compile only
2154 /D <macro[=value]> Define macro
2155 /EH<value> Exception handling model
2156 /EP Disable linemarker output and preprocess to stdout
2157 /E Preprocess to stdout
2158 /fallback Fall back to cl.exe if clang-cl fails to compile
2159 /FA Output assembly code file during compilation
Hans Wennborg0d080622015-08-12 19:35:01 +00002160 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
Hans Wennborg35487d82014-08-04 21:07:58 +00002161 /Fe<file or directory> Set output executable file or directory (ends in / or \)
2162 /FI <value> Include file before parsing
Hans Wennborg0d080622015-08-12 19:35:01 +00002163 /Fi<file> Set preprocess output file name (with /P)
2164 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
2165 /fp:except-
2166 /fp:except
2167 /fp:fast
2168 /fp:precise
2169 /fp:strict
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002170 /Fp<filename> Set pch filename (with /Yc and /Yu)
Hans Wennborg0d080622015-08-12 19:35:01 +00002171 /GA Assume thread-local variables are defined in the executable
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002172 /Gd Set __cdecl as a default calling convention
Hans Wennborg35487d82014-08-04 21:07:58 +00002173 /GF- Disable string pooling
2174 /GR- Disable emission of RTTI data
2175 /GR Enable emission of RTTI data
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002176 /Gr Set __fastcall as a default calling convention
2177 /GS- Disable buffer security check
2178 /GS Enable buffer security check
Hans Wennborg0d080622015-08-12 19:35:01 +00002179 /Gs<value> Set stack probe size
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002180 /Gv Set __vectorcall as a default calling convention
Hans Wennborg35487d82014-08-04 21:07:58 +00002181 /Gw- Don't put each data item in its own section
2182 /Gw Put each data item in its own section
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002183 /GX- Enable exception handling
2184 /GX Enable exception handling
Hans Wennborg35487d82014-08-04 21:07:58 +00002185 /Gy- Don't put each function in its own section
2186 /Gy Put each function in its own section
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002187 /Gz Set __stdcall as a default calling convention
Hans Wennborg35487d82014-08-04 21:07:58 +00002188 /help Display available options
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002189 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
Hans Wennborg35487d82014-08-04 21:07:58 +00002190 /I <dir> Add directory to include search path
2191 /J Make char type unsigned
2192 /LDd Create debug DLL
2193 /LD Create DLL
2194 /link <options> Forward options to the linker
2195 /MDd Use DLL debug run-time
2196 /MD Use DLL run-time
2197 /MTd Use static debug run-time
2198 /MT Use static run-time
Hans Wennborg35487d82014-08-04 21:07:58 +00002199 /Od Disable optimization
2200 /Oi- Disable use of builtin functions
2201 /Oi Enable use of builtin functions
2202 /Os Optimize for size
2203 /Ot Optimize for speed
Hans Wennborg0d080622015-08-12 19:35:01 +00002204 /O<value> Optimization level
2205 /o <file or directory> Set output file or directory (ends in / or \)
Hans Wennborg35487d82014-08-04 21:07:58 +00002206 /P Preprocess to file
Hans Wennborg0d080622015-08-12 19:35:01 +00002207 /Qvec- Disable the loop vectorization passes
2208 /Qvec Enable the loop vectorization passes
Hans Wennborg35487d82014-08-04 21:07:58 +00002209 /showIncludes Print info about included files to stderr
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002210 /std:<value> Language standard to compile for
Hans Wennborg35487d82014-08-04 21:07:58 +00002211 /TC Treat all source files as C
2212 /Tc <filename> Specify a C source file
2213 /TP Treat all source files as C++
2214 /Tp <filename> Specify a C++ source file
2215 /U <macro> Undefine macro
2216 /vd<value> Control vtordisp placement
2217 /vmb Use a best-case representation method for member pointers
2218 /vmg Use a most-general representation for member pointers
2219 /vmm Set the default most-general representation to multiple inheritance
2220 /vms Set the default most-general representation to single inheritance
2221 /vmv Set the default most-general representation to virtual inheritance
Hans Wennborg0d080622015-08-12 19:35:01 +00002222 /volatile:iso Volatile loads and stores have standard semantics
2223 /volatile:ms Volatile loads and stores have acquire and release semantics
Hans Wennborg35487d82014-08-04 21:07:58 +00002224 /W0 Disable all warnings
2225 /W1 Enable -Wall
2226 /W2 Enable -Wall
2227 /W3 Enable -Wall
Nico Weberc8036742015-12-11 22:31:16 +00002228 /W4 Enable -Wall and -Wextra
Hans Wennborge8178e82016-02-12 01:01:37 +00002229 /Wall Enable -Wall and -Wextra
Hans Wennborg35487d82014-08-04 21:07:58 +00002230 /WX- Do not treat warnings as errors
2231 /WX Treat warnings as errors
2232 /w Disable all warnings
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002233 /Y- Disable precompiled headers, overrides /Yc and /Yu
2234 /Yc<filename> Generate a pch file for all code up to and including <filename>
2235 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
Hans Wennborg0d080622015-08-12 19:35:01 +00002236 /Z7 Enable CodeView debug information in object files
2237 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
2238 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
2239 /Zc:strictStrings Treat string literals as const
2240 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
2241 /Zc:threadSafeInit Enable thread-safe initialization of static variables
2242 /Zc:trigraphs- Disable trigraphs (default)
2243 /Zc:trigraphs Enable trigraphs
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002244 /Zd Emit debug line number tables only
Hans Wennborg0d080622015-08-12 19:35:01 +00002245 /Zi Alias for /Z7. Does not produce PDBs.
2246 /Zl Don't mention any default libraries in the object file
Hans Wennborg35487d82014-08-04 21:07:58 +00002247 /Zp Set the default maximum struct packing alignment to 1
2248 /Zp<value> Specify the default maximum struct packing alignment
2249 /Zs Syntax-check only
2250
2251 OPTIONS:
Hans Wennborg0d080622015-08-12 19:35:01 +00002252 -### Print (but do not run) the commands to run for this compilation
2253 --analyze Run the static analyzer
2254 -fansi-escape-codes Use ANSI escape codes for diagnostics
2255 -fcolor-diagnostics Use colors in diagnostics
2256 -fdiagnostics-parseable-fixits
2257 Print fix-its in machine parseable form
Hans Wennborg35487d82014-08-04 21:07:58 +00002258 -fms-compatibility-version=<value>
Hans Wennborg0d080622015-08-12 19:35:01 +00002259 Dot-separated value representing the Microsoft compiler version
2260 number to report in _MSC_VER (0 = don't define it (default))
Hans Wennborge8178e82016-02-12 01:01:37 +00002261 -fms-compatibility Enable full Microsoft Visual C++ compatibility
2262 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
2263 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
2264 (0 = don't define it (default))
Hans Wennborg0d080622015-08-12 19:35:01 +00002265 -fno-sanitize-coverage=<value>
2266 Disable specified features of coverage instrumentation for Sanitizers
2267 -fno-sanitize-recover=<value>
2268 Disable recovery for specified sanitizers
2269 -fno-sanitize-trap=<value>
2270 Disable trapping for specified sanitizers
Hans Wennborg35487d82014-08-04 21:07:58 +00002271 -fsanitize-blacklist=<value>
Hans Wennborg0d080622015-08-12 19:35:01 +00002272 Path to blacklist file for sanitizers
2273 -fsanitize-coverage=<value>
2274 Specify the type of coverage instrumentation for Sanitizers
2275 -fsanitize-recover=<value>
2276 Enable recovery for specified sanitizers
2277 -fsanitize-trap=<value> Enable trapping for specified sanitizers
2278 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
2279 behavior. See user manual for available checks
2280 -gcodeview Generate CodeView debug information
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002281 -gline-tables-only Emit debug line number tables only
2282 -miamcu Use Intel MCU ABI
Hans Wennborg0d080622015-08-12 19:35:01 +00002283 -mllvm <value> Additional arguments to forward to LLVM's option processing
2284 -Qunused-arguments Don't emit warning for unused driver arguments
2285 -R<remark> Enable the specified remark
2286 --target=<value> Generate code for the given target
2287 -v Show commands to run and use verbose output
2288 -W<warning> Enable the specified warning
2289 -Xclang <arg> Pass <arg> to the clang compiler
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002290
2291The /fallback Option
2292^^^^^^^^^^^^^^^^^^^^
2293
2294When clang-cl is run with the ``/fallback`` option, it will first try to
2295compile files itself. For any file that it fails to compile, it will fall back
2296and try to compile the file by invoking cl.exe.
2297
2298This option is intended to be used as a temporary means to build projects where
2299clang-cl cannot successfully compile all the files. clang-cl may fail to compile
2300a file either because it cannot generate code for some C++ feature, or because
2301it cannot parse some Microsoft language extension.