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