blob: de28d77671517d36f26e07004bc98358e18b5e73 [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
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +000018`Clang Web Site <https://clang.llvm.org>`_ or the `LLVM Web
19Site <https://llvm.org>`_.
Sean Silvabf9b4cd2012-12-13 01:10:46 +000020
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
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +000025`Clang Static Analyzer <https://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
Reka Kovacsf616a892017-09-23 12:13:32 +0000110 Turn warning "foo" into a 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
Brian Gesiak562eab92017-07-01 05:45:26 +0000325.. _opt_fsave-optimization-record:
326
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +0000327.. option:: -fsave-optimization-record[=<format>]
328
329 Write optimization remarks to a separate file.
Brian Gesiak562eab92017-07-01 05:45:26 +0000330
331 This option, which defaults to off, controls whether Clang writes
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +0000332 optimization reports to a separate file. By recording diagnostics in a file,
333 users can parse or sort the remarks in a convenient way.
334
335 By default, the serialization format is YAML.
336
337 The supported serialization formats are:
338
339 - .. _opt_fsave_optimization_record_yaml:
340
341 ``-fsave-optimization-record=yaml``: A structured YAML format.
Brian Gesiak562eab92017-07-01 05:45:26 +0000342
Brian Gesiakbb83ce462017-07-05 19:55:51 +0000343.. _opt_foptimization-record-file:
344
345**-foptimization-record-file**
346 Control the file to which optimization reports are written.
347
348 When optimization reports are being output (see
349 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
350 option controls the file to which those reports are written.
351
352 If this option is not used, optimization records are output to a file named
353 after the primary file being compiled. If that's "foo.c", for example,
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +0000354 optimization records are output to "foo.opt.yaml". If a specific
355 serialization format is specified, the file will be named
356 "foo.opt.<format>".
Brian Gesiakbb83ce462017-07-05 19:55:51 +0000357
Francis Visoiu Mistrih5501dda2019-06-14 21:38:57 +0000358.. _opt_foptimization-record-passes:
359
360**-foptimization-record-passes**
361 Only include passes which match a specified regular expression.
362
363 When optimization reports are being output (see
364 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
365 option controls the passes that will be included in the final report.
366
367 If this option is not used, all the passes are included in the optimization
368 record.
369
Adam Nemet1eea3e52016-09-13 04:32:40 +0000370.. _opt_fdiagnostics-show-hotness:
371
372**-f[no-]diagnostics-show-hotness**
373 Enable profile hotness information in diagnostic line.
374
Brian Gesiak562eab92017-07-01 05:45:26 +0000375 This option controls whether Clang prints the profile hotness associated
376 with diagnostics in the presence of profile-guided optimization information.
377 This is currently supported with optimization remarks (see
378 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
379 allows users to focus on the hot optimization remarks that are likely to be
380 more relevant for run-time performance.
Adam Nemet1eea3e52016-09-13 04:32:40 +0000381
382 For example, in this output, the block containing the callsite of `foo` was
383 executed 3000 times according to the profile data:
384
385 ::
386
387 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
388 sum += foo(x, x - 2);
389 ^
390
Brian Gesiak562eab92017-07-01 05:45:26 +0000391 This option is implied when
392 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
393 Otherwise, it defaults to off.
394
395.. _opt_fdiagnostics-hotness-threshold:
396
397**-fdiagnostics-hotness-threshold**
398 Prevent optimization remarks from being output if they do not have at least
399 this hotness value.
400
401 This option, which defaults to zero, controls the minimum hotness an
402 optimization remark would need in order to be output by Clang. This is
403 currently supported with optimization remarks (see :ref:`Options to Emit
404 Optimization Reports <rpass>`) when profile hotness information in
405 diagnostics is enabled (see
406 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
407
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000408.. _opt_fdiagnostics-fixit-info:
409
410**-f[no-]diagnostics-fixit-info**
411 Enable "FixIt" information in the diagnostics output.
412
413 This option, which defaults to on, controls whether or not Clang
414 prints the information on how to fix a specific diagnostic
415 underneath it when it knows. For example, in this output:
416
417 ::
418
419 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
420 #endif bad
421 ^
422 //
423
424 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
425 printing the "//" line at the end of the message. This information
426 is useful for users who may not understand what is wrong, but can be
427 confusing for machine parsing.
428
429.. _opt_fdiagnostics-print-source-range-info:
430
Nico Weber69dce49c72013-01-09 05:06:41 +0000431**-fdiagnostics-print-source-range-info**
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000432 Print machine parsable information about source ranges.
Nico Weber69dce49c72013-01-09 05:06:41 +0000433 This option makes Clang print information about source ranges in a machine
434 parsable format after the file/line/column number information. The
435 information is a simple sequence of brace enclosed ranges, where each range
436 lists the start and end line/column locations. For example, in this output:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000437
438 ::
439
440 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
441 P = (P-42) + Gamma*4;
442 ~~~~~~ ^ ~~~~~~~
443
444 The {}'s are generated by -fdiagnostics-print-source-range-info.
445
446 The printed column numbers count bytes from the beginning of the
447 line; take care if your source contains multibyte characters.
448
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000449.. option:: -fdiagnostics-parseable-fixits
450
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000451 Print Fix-Its in a machine parseable form.
452
453 This option makes Clang print available Fix-Its in a machine
454 parseable format at the end of diagnostics. The following example
455 illustrates the format:
456
457 ::
458
459 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
460
461 The range printed is a half-open range, so in this example the
462 characters at column 25 up to but not including column 29 on line 7
463 in t.cpp should be replaced with the string "Gamma". Either the
464 range or the replacement string may be empty (representing strict
465 insertions and strict erasures, respectively). Both the file name
466 and the insertion string escape backslash (as "\\\\"), tabs (as
467 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
468 non-printable characters (as octal "\\xxx").
469
470 The printed column numbers count bytes from the beginning of the
471 line; take care if your source contains multibyte characters.
472
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000473.. option:: -fno-elide-type
474
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000475 Turns off elision in template type printing.
476
477 The default for template type printing is to elide as many template
478 arguments as possible, removing those which are the same in both
479 template types, leaving only the differences. Adding this flag will
480 print all the template arguments. If supported by the terminal,
481 highlighting will still appear on differing arguments.
482
483 Default:
484
485 ::
486
487 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;
488
489 -fno-elide-type:
490
491 ::
492
493 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;
494
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000495.. option:: -fdiagnostics-show-template-tree
496
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000497 Template type diffing prints a text tree.
498
499 For diffing large templated types, this option will cause Clang to
500 display the templates as an indented text tree, one argument per
501 line, with differences marked inline. This is compatible with
502 -fno-elide-type.
503
504 Default:
505
506 ::
507
508 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;
509
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000510 With :option:`-fdiagnostics-show-template-tree`:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000511
512 ::
513
514 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
515 vector<
516 map<
517 [...],
518 map<
Richard Trieu98ca59e2013-08-09 22:52:48 +0000519 [float != double],
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000520 [...]>>>
521
522.. _cl_diag_warning_groups:
523
524Individual Warning Groups
525^^^^^^^^^^^^^^^^^^^^^^^^^
526
527TODO: Generate this from tblgen. Define one anchor per warning group.
528
529.. _opt_wextra-tokens:
530
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000531.. option:: -Wextra-tokens
532
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000533 Warn about excess tokens at the end of a preprocessor directive.
534
535 This option, which defaults to on, enables warnings about extra
536 tokens at the end of preprocessor directives. For example:
537
538 ::
539
540 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
541 #endif bad
542 ^
543
544 These extra tokens are not strictly conforming, and are usually best
545 handled by commenting them out.
546
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000547.. option:: -Wambiguous-member-template
548
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000549 Warn about unqualified uses of a member template whose name resolves to
550 another template at the location of the use.
551
552 This option, which defaults to on, enables a warning in the
553 following code:
554
555 ::
556
557 template<typename T> struct set{};
558 template<typename T> struct trait { typedef const T& type; };
559 struct Value {
560 template<typename T> void set(typename trait<T>::type value) {}
561 };
562 void foo() {
563 Value v;
564 v.set<double>(3.2);
565 }
566
567 C++ [basic.lookup.classref] requires this to be an error, but,
568 because it's hard to work around, Clang downgrades it to a warning
569 as an extension.
570
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000571.. option:: -Wbind-to-temporary-copy
572
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000573 Warn about an unusable copy constructor when binding a reference to a
574 temporary.
575
Nico Weberacb35c02014-09-18 02:09:53 +0000576 This option enables warnings about binding a
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000577 reference to a temporary when the temporary doesn't have a usable
578 copy constructor. For example:
579
580 ::
581
582 struct NonCopyable {
583 NonCopyable();
584 private:
585 NonCopyable(const NonCopyable&);
586 };
587 void foo(const NonCopyable&);
588 void bar() {
589 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
590 }
591
592 ::
593
594 struct NonCopyable2 {
595 NonCopyable2();
596 NonCopyable2(NonCopyable2&);
597 };
598 void foo(const NonCopyable2&);
599 void bar() {
600 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
601 }
602
603 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
604 whose instantiation produces a compile error, that error will still
605 be a hard error in C++98 mode even if this warning is turned off.
606
607Options to Control Clang Crash Diagnostics
608------------------------------------------
609
610As unbelievable as it may sound, Clang does crash from time to time.
611Generally, this only occurs to those living on the `bleeding
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +0000612edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000613lengths to assist you in filing a bug report. Specifically, Clang
614generates preprocessed source file(s) and associated run script(s) upon
615a crash. These files should be attached to a bug report to ease
616reproducibility of the failure. Below are the command line options to
617control the crash diagnostics.
618
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000619.. option:: -fno-crash-diagnostics
620
621 Disable auto-generation of preprocessed source files during a clang crash.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000622
623The -fno-crash-diagnostics flag can be helpful for speeding the process
624of generating a delta reduced test case.
625
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000626Clang is also capable of generating preprocessed source file(s) and associated
627run script(s) even without a crash. This is specially useful when trying to
628generate a reproducer for warnings or errors while using modules.
629
630.. option:: -gen-reproducer
631
632 Generates preprocessed source files, a reproducer script and if relevant, a
633 cache containing: built module pcm's and all headers needed to rebuilt the
634 same modules.
635
Adam Nemet1eea3e52016-09-13 04:32:40 +0000636.. _rpass:
637
Diego Novillo263ce212014-05-29 20:13:27 +0000638Options to Emit Optimization Reports
639------------------------------------
640
641Optimization reports trace, at a high-level, all the major decisions
642done by compiler transformations. For instance, when the inliner
643decides to inline function ``foo()`` into ``bar()``, or the loop unroller
644decides to unroll a loop N times, or the vectorizer decides to
645vectorize a loop body.
646
647Clang offers a family of flags which the optimizers can use to emit
648a diagnostic in three cases:
649
Aaron Ballman05efec82016-07-15 12:55:47 +00006501. When the pass makes a transformation (`-Rpass`).
Diego Novillo263ce212014-05-29 20:13:27 +0000651
Aaron Ballman05efec82016-07-15 12:55:47 +00006522. When the pass fails to make a transformation (`-Rpass-missed`).
Diego Novillo263ce212014-05-29 20:13:27 +0000653
6543. When the pass determines whether or not to make a transformation
Aaron Ballman05efec82016-07-15 12:55:47 +0000655 (`-Rpass-analysis`).
Diego Novillo263ce212014-05-29 20:13:27 +0000656
Aaron Ballman05efec82016-07-15 12:55:47 +0000657NOTE: Although the discussion below focuses on `-Rpass`, the exact
658same options apply to `-Rpass-missed` and `-Rpass-analysis`.
Diego Novillo263ce212014-05-29 20:13:27 +0000659
660Since there are dozens of passes inside the compiler, each of these flags
661take a regular expression that identifies the name of the pass which should
662emit the associated diagnostic. For example, to get a report from the inliner,
663compile the code with:
664
665.. code-block:: console
666
667 $ clang -O2 -Rpass=inline code.cc -o code
668 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
669 int bar(int j) { return foo(j, j - 2); }
670 ^
671
672Note that remarks from the inliner are identified with `[-Rpass=inline]`.
673To request a report from every optimization pass, you should use
Aaron Ballman05efec82016-07-15 12:55:47 +0000674`-Rpass=.*` (in fact, you can use any valid POSIX regular
Diego Novillo263ce212014-05-29 20:13:27 +0000675expression). However, do not expect a report from every transformation
676made by the compiler. Optimization remarks do not really make sense
677outside of the major transformations (e.g., inlining, vectorization,
678loop optimizations) and not every optimization pass supports this
679feature.
680
Adam Nemet1eea3e52016-09-13 04:32:40 +0000681Note that when using profile-guided optimization information, profile hotness
682information can be included in the remarks (see
683:ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
684
Diego Novillo263ce212014-05-29 20:13:27 +0000685Current limitations
686^^^^^^^^^^^^^^^^^^^
687
Diego Novillo94b276d2014-07-10 23:29:28 +00006881. Optimization remarks that refer to function names will display the
Diego Novillo263ce212014-05-29 20:13:27 +0000689 mangled name of the function. Since these remarks are emitted by the
690 back end of the compiler, it does not know anything about the input
691 language, nor its mangling rules.
692
Diego Novillo94b276d2014-07-10 23:29:28 +00006932. Some source locations are not displayed correctly. The front end has
Diego Novillo263ce212014-05-29 20:13:27 +0000694 a more detailed source location tracking than the locations included
695 in the debug info (e.g., the front end can locate code inside macro
Aaron Ballman05efec82016-07-15 12:55:47 +0000696 expansions). However, the locations used by `-Rpass` are
Diego Novillo263ce212014-05-29 20:13:27 +0000697 translated from debug annotations. That translation can be lossy,
698 which results in some remarks having no location information.
699
Paul Robinsond7214a72015-04-27 18:14:32 +0000700Other Options
701-------------
Reka Kovacsf616a892017-09-23 12:13:32 +0000702Clang options that don't fit neatly into other categories.
Paul Robinsond7214a72015-04-27 18:14:32 +0000703
Reid Kleckner5e866e42019-10-10 21:04:25 +0000704.. option:: -fgnuc-version=
705
706 This flag controls the value of ``__GNUC__`` and related macros. This flag
707 does not enable or disable any GCC extensions implemented in Clang. Setting
708 the version to zero causes Clang to leave ``__GNUC__`` and other
709 GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined.
710
Paul Robinsond7214a72015-04-27 18:14:32 +0000711.. option:: -MV
712
713 When emitting a dependency file, use formatting conventions appropriate
714 for NMake or Jom. Ignored unless another option causes Clang to emit a
715 dependency file.
716
717When Clang emits a dependency file (e.g., you supplied the -M option)
718most filenames can be written to the file without any special formatting.
719Different Make tools will treat different sets of characters as "special"
720and use different conventions for telling the Make tool that the character
721is actually part of the filename. Normally Clang uses backslash to "escape"
722a special character, which is the convention used by GNU Make. The -MV
723option tells Clang to put double-quotes around the entire filename, which
724is the convention used by NMake and Jom.
725
Serge Pavlov208ac652018-01-01 13:27:01 +0000726Configuration files
727-------------------
728
729Configuration files group command-line options and allow all of them to be
730specified just by referencing the configuration file. They may be used, for
731example, to collect options required to tune compilation for particular
732target, such as -L, -I, -l, --sysroot, codegen options, etc.
733
734The command line option `--config` can be used to specify configuration
735file in a Clang invocation. For example:
736
737::
738
739 clang --config /home/user/cfgs/testing.txt
740 clang --config debug.cfg
741
742If the provided argument contains a directory separator, it is considered as
743a file path, and options are read from that file. Otherwise the argument is
744treated as a file name and is searched for sequentially in the directories:
745
746 - user directory,
747 - system directory,
748 - the directory where Clang executable resides.
749
750Both user and system directories for configuration files are specified during
751clang build using CMake parameters, CLANG_CONFIG_FILE_USER_DIR and
752CLANG_CONFIG_FILE_SYSTEM_DIR respectively. The first file found is used. It is
753an error if the required file cannot be found.
754
755Another way to specify a configuration file is to encode it in executable name.
756For example, if the Clang executable is named `armv7l-clang` (it may be a
757symbolic link to `clang`), then Clang will search for file `armv7l.cfg` in the
758directory where Clang resides.
759
760If a driver mode is specified in invocation, Clang tries to find a file specific
761for the specified mode. For example, if the executable file is named
762`x86_64-clang-cl`, Clang first looks for `x86_64-cl.cfg` and if it is not found,
Serge Pavlov93581c52018-01-01 15:53:16 +0000763looks for `x86_64.cfg`.
Serge Pavlov208ac652018-01-01 13:27:01 +0000764
765If the command line contains options that effectively change target architecture
766(these are -m32, -EL, and some others) and the configuration file starts with an
767architecture name, Clang tries to load the configuration file for the effective
768architecture. For example, invocation:
769
770::
771
772 x86_64-clang -m32 abc.c
773
774causes Clang search for a file `i368.cfg` first, and if no such file is found,
775Clang looks for the file `x86_64.cfg`.
776
777The configuration file consists of command-line options specified on one or
778more lines. Lines composed of whitespace characters only are ignored as well as
779lines in which the first non-blank character is `#`. Long options may be split
780between several lines by a trailing backslash. Here is example of a
781configuration file:
782
783::
784
785 # Several options on line
786 -c --target=x86_64-unknown-linux-gnu
787
788 # Long option split between lines
789 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\
790 include/c++/5.4.0
791
792 # other config files may be included
793 @linux.options
794
795Files included by `@file` directives in configuration files are resolved
796relative to the including file. For example, if a configuration file
797`~/.llvm/target.cfg` contains the directive `@os/linux.opts`, the file
798`linux.opts` is searched for in the directory `~/.llvm/os`.
Diego Novillo263ce212014-05-29 20:13:27 +0000799
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000800Language and Target-Independent Features
801========================================
802
803Controlling Errors and Warnings
804-------------------------------
805
806Clang provides a number of ways to control which code constructs cause
807it to emit errors and warning messages, and how they are displayed to
808the console.
809
810Controlling How Clang Displays Diagnostics
811^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
812
813When Clang emits a diagnostic, it includes rich information in the
814output, and gives you fine-grain control over which information is
815printed. Clang has the ability to print this information, and these are
816the options that control it:
817
818#. A file/line/column indicator that shows exactly where the diagnostic
819 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
820 :ref:`-fshow-source-location <opt_fshow-source-location>`].
821#. A categorization of the diagnostic as a note, warning, error, or
822 fatal error.
823#. A text string that describes what the problem is.
824#. An option that indicates how to control the diagnostic (for
825 diagnostics that support it)
826 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
827#. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
828 for clients that want to group diagnostics by class (for diagnostics
829 that support it)
830 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
831#. The line of source code that the issue occurs on, along with a caret
832 and ranges that indicate the important locations
833 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
834#. "FixIt" information, which is a concise explanation of how to fix the
835 problem (when Clang is certain it knows)
836 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
837#. A machine-parsable representation of the ranges involved (off by
838 default)
839 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
840
841For more information please see :ref:`Formatting of
842Diagnostics <cl_diag_formatting>`.
843
844Diagnostic Mappings
845^^^^^^^^^^^^^^^^^^^
846
Alex Denisov793e0672015-02-11 07:56:16 +0000847All diagnostics are mapped into one of these 6 classes:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000848
849- Ignored
850- Note
Tobias Grosser74160242014-02-28 09:11:08 +0000851- Remark
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000852- Warning
853- Error
854- Fatal
855
856.. _diagnostics_categories:
857
858Diagnostic Categories
859^^^^^^^^^^^^^^^^^^^^^
860
861Though not shown by default, diagnostics may each be associated with a
862high-level category. This category is intended to make it possible to
863triage builds that produce a large number of errors or warnings in a
864grouped way.
865
866Categories are not shown by default, but they can be turned on with the
867:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
868When set to "``name``", the category is printed textually in the
869diagnostic output. When it is set to "``id``", a category number is
870printed. The mapping of category names to category id's can be obtained
871by running '``clang --print-diagnostic-categories``'.
872
873Controlling Diagnostics via Command Line Flags
874^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
875
876TODO: -W flags, -pedantic, etc
877
878.. _pragma_gcc_diagnostic:
879
880Controlling Diagnostics via Pragmas
881^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
882
883Clang can also control what diagnostics are enabled through the use of
884pragmas in the source code. This is useful for turning off specific
885warnings in a section of source code. Clang supports GCC's pragma for
886compatibility with existing source code, as well as several extensions.
887
888The pragma may control any warning that can be used from the command
889line. Warnings may be set to ignored, warning, error, or fatal. The
890following example code will tell Clang or GCC to ignore the -Wall
891warnings:
892
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000893.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000894
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000895 #pragma GCC diagnostic ignored "-Wall"
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000896
897In addition to all of the functionality provided by GCC's pragma, Clang
898also allows you to push and pop the current warning state. This is
899particularly useful when writing a header file that will be compiled by
900other people, because you don't know what warning flags they build with.
901
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000902In the below example :option:`-Wextra-tokens` is ignored for only a single line
903of code, after which the diagnostics return to whatever state had previously
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000904existed.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000905
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000906.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000907
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000908 #if foo
909 #endif foo // warning: extra tokens at end of #endif directive
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000910
Asiri Rathnayakeb0bbb7d2017-02-02 10:35:18 +0000911 #pragma clang diagnostic push
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000912 #pragma clang diagnostic ignored "-Wextra-tokens"
913
914 #if foo
915 #endif foo // no warning
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000916
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000917 #pragma clang diagnostic pop
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000918
919The push and pop pragmas will save and restore the full diagnostic state
920of the compiler, regardless of how it was set. That means that it is
921possible to use push and pop around GCC compatible diagnostics and Clang
922will push and pop them appropriately, while GCC will ignore the pushes
923and pops as unknown pragmas. It should be noted that while Clang
924supports the GCC pragma, Clang and GCC do not support the exact same set
925of warnings, so even when using GCC compatible #pragmas there is no
926guarantee that they will have identical behaviour on both compilers.
927
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000928In addition to controlling warnings and errors generated by the compiler, it is
929possible to generate custom warning and error messages through the following
930pragmas:
931
932.. code-block:: c
933
934 // The following will produce warning messages
935 #pragma message "some diagnostic message"
936 #pragma GCC warning "TODO: replace deprecated feature"
937
938 // The following will produce an error message
939 #pragma GCC error "Not supported"
940
941These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
942directives, except that they may also be embedded into preprocessor macros via
943the C99 ``_Pragma`` operator, for example:
944
945.. code-block:: c
946
947 #define STR(X) #X
948 #define DEFER(M,...) M(__VA_ARGS__)
949 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
950
951 CUSTOM_ERROR("Feature not available");
952
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000953Controlling Diagnostics in System Headers
954^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
955
956Warnings are suppressed when they occur in system headers. By default,
957an included file is treated as a system header if it is found in an
958include path specified by ``-isystem``, but this can be overridden in
959several ways.
960
961The ``system_header`` pragma can be used to mark the current file as
962being a system header. No warnings will be produced from the location of
963the pragma onwards within the same file.
964
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000965.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000966
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000967 #if foo
968 #endif foo // warning: extra tokens at end of #endif directive
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000969
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000970 #pragma clang system_header
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000971
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000972 #if foo
973 #endif foo // no warning
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000974
Aaron Ballman51fb0312016-07-15 13:13:45 +0000975The `--system-header-prefix=` and `--no-system-header-prefix=`
Alexander Kornienko18fa48c2014-03-26 01:39:59 +0000976command-line arguments can be used to override whether subsets of an include
977path are treated as system headers. When the name in a ``#include`` directive
978is found within a header search path and starts with a system prefix, the
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000979header is treated as a system header. The last prefix on the
980command-line which matches the specified header name takes precedence.
981For instance:
982
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000983.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000984
Alexander Kornienko18fa48c2014-03-26 01:39:59 +0000985 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
986 --no-system-header-prefix=x/y/
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000987
988Here, ``#include "x/a.h"`` is treated as including a system header, even
989if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
990as not including a system header, even if the header is found in
991``bar``.
992
993A ``#include`` directive which finds a file relative to the current
994directory is treated as including a system header if the including file
995is treated as a system header.
996
997.. _diagnostics_enable_everything:
998
Tobias Grosser74160242014-02-28 09:11:08 +0000999Enabling All Diagnostics
1000^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001001
JF Bastiendf22ff12019-08-05 16:53:45 +00001002In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
1003by passing :option:`-Weverything`. This works as expected with
1004:option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some
1005diagnostics contradict each other, therefore, users of :option:`-Weverything`
JF Bastien36eab652019-08-05 19:45:23 +00001006often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat`
1007because they contradict recent C++ standards.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001008
JF Bastiendf22ff12019-08-05 16:53:45 +00001009Since :option:`-Weverything` enables every diagnostic, we generally don't
JF Bastien6e33c642019-08-05 19:59:07 +00001010recommend using it. `-Wall` `-Wextra` are a better choice for most projects.
1011Using :option:`-Weverything` means that updating your compiler is more difficult
1012because you're exposed to experimental diagnostics which might be of lower
1013quality than the default ones. If you do use :option:`-Weverything` then we
1014advise that you address all new compiler diagnostics as they get added to Clang,
1015either by fixing everything they find or explicitly disabling that diagnostic
1016with its corresponding `Wno-` option.
JF Bastiendf22ff12019-08-05 16:53:45 +00001017
1018Note that when combined with :option:`-w` (which disables all warnings),
1019disabling all warnings wins.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001020
1021Controlling Static Analyzer Diagnostics
1022^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1023
1024While not strictly part of the compiler, the diagnostics from Clang's
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001025`static analyzer <https://clang-analyzer.llvm.org>`_ can also be
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001026influenced by the user via changes to the source code. See the available
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001027`annotations <https://clang-analyzer.llvm.org/annotations.html>`_ and the
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001028analyzer's `FAQ
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00001029page <https://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001030information.
1031
Dmitri Gribenko7ac0cc32012-12-15 21:10:51 +00001032.. _usersmanual-precompiled-headers:
1033
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001034Precompiled Headers
1035-------------------
1036
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001037`Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001038are a general approach employed by many compilers to reduce compilation
1039time. The underlying motivation of the approach is that it is common for
1040the same (and often large) header files to be included by multiple
1041source files. Consequently, compile times can often be greatly improved
1042by caching some of the (redundant) work done by a compiler to process
1043headers. Precompiled header files, which represent one of many ways to
1044implement this optimization, are literally files that represent an
1045on-disk cache that contains the vital information necessary to reduce
1046some of the work needed to process a corresponding header file. While
1047details of precompiled headers vary between compilers, precompiled
1048headers have been shown to be highly effective at speeding up program
J. Ryan Stinnettd45eaf92019-05-30 16:46:22 +00001049compilation on systems with very large system headers (e.g., macOS).
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001050
1051Generating a PCH File
1052^^^^^^^^^^^^^^^^^^^^^
1053
1054To generate a PCH file using Clang, one invokes Clang with the
Aaron Ballman51fb0312016-07-15 13:13:45 +00001055`-x <language>-header` option. This mirrors the interface in GCC
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001056for generating PCH files:
1057
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001058.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001059
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001060 $ gcc -x c-header test.h -o test.h.gch
1061 $ clang -x c-header test.h -o test.h.pch
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001062
1063Using a PCH File
1064^^^^^^^^^^^^^^^^
1065
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001066A PCH file can then be used as a prefix header when a :option:`-include`
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001067option is passed to ``clang``:
1068
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001069.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001070
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001071 $ clang -include test.h test.c -o test
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001072
1073The ``clang`` driver will first check if a PCH file for ``test.h`` is
1074available; if so, the contents of ``test.h`` (and the files it includes)
1075will be processed from the PCH file. Otherwise, Clang falls back to
1076directly processing the content of ``test.h``. This mirrors the behavior
1077of GCC.
1078
1079.. note::
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001080
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001081 Clang does *not* automatically use PCH files for headers that are directly
1082 included within a source file. For example:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001083
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001084 .. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001085
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001086 $ clang -x c-header test.h -o test.h.pch
1087 $ cat test.c
1088 #include "test.h"
1089 $ clang test.c -o test
1090
1091 In this example, ``clang`` will not automatically use the PCH file for
1092 ``test.h`` since ``test.h`` was included directly in the source file and not
1093 specified on the command line using :option:`-include`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001094
1095Relocatable PCH Files
1096^^^^^^^^^^^^^^^^^^^^^
1097
1098It is sometimes necessary to build a precompiled header from headers
1099that are not yet in their final, installed locations. For example, one
1100might build a precompiled header within the build tree that is then
1101meant to be installed alongside the headers. Clang permits the creation
1102of "relocatable" precompiled headers, which are built with a given path
1103(into the build directory) and can later be used from an installed
1104location.
1105
1106To build a relocatable precompiled header, place your headers into a
1107subdirectory whose structure mimics the installed location. For example,
1108if you want to build a precompiled header for the header ``mylib.h``
1109that will be installed into ``/usr/include``, create a subdirectory
1110``build/usr/include`` and place the header ``mylib.h`` into that
1111subdirectory. If ``mylib.h`` depends on other headers, then they can be
1112stored within ``build/usr/include`` in a way that mimics the installed
1113location.
1114
1115Building a relocatable precompiled header requires two additional
1116arguments. First, pass the ``--relocatable-pch`` flag to indicate that
1117the resulting PCH file should be relocatable. Second, pass
Brian Gesiak49956142018-01-13 18:34:07 +00001118``-isysroot /path/to/build``, which makes all includes for your library
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001119relative to the build directory. For example:
1120
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001121.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001122
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001123 # 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 +00001124
1125When loading the relocatable PCH file, the various headers used in the
1126PCH file are found from the system header root. For example, ``mylib.h``
1127can be found in ``/usr/include/mylib.h``. If the headers are installed
Brian Gesiak49956142018-01-13 18:34:07 +00001128in some other system root, the ``-isysroot`` option can be used provide
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001129a different system root from which the headers will be based. For
Brian Gesiak49956142018-01-13 18:34:07 +00001130example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001131``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
1132
1133Relocatable precompiled headers are intended to be used in a limited
1134number of cases where the compilation environment is tightly controlled
1135and the precompiled header cannot be generated after headers have been
Argyrios Kyrtzidisf0ad09f2013-02-14 00:12:44 +00001136installed.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001137
Erich Keanef124ab92019-09-18 15:09:49 +00001138.. _controlling-fp-behavior:
1139
1140Controlling Floating Point Behavior
1141-----------------------------------
1142
1143Clang provides a number of ways to control floating point behavior. The options
1144are listed below.
1145
1146.. option:: -ffast-math
1147
1148 Enable fast-math mode. This option lets the
1149 compiler make aggressive, potentially-lossy assumptions about
1150 floating-point math. These include:
1151
1152 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1153 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1154 ``(a + b) * c == a * c + b * c``),
1155 * Operands to floating-point operations are not equal to ``NaN`` and
1156 ``Inf``, and
1157 * ``+0`` and ``-0`` are interchangeable.
1158
1159 ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor
1160 macro. Some math libraries recognize this macro and change their behavior.
1161 With the exception of ``-ffp-contract=fast``, using any of the options
1162 below to disable any of the individual optimizations in ``-ffast-math``
1163 will cause ``__FAST_MATH__`` to no longer be set.
1164
1165 This option implies:
1166
1167 * ``-fno-honor-infinities``
1168
1169 * ``-fno-honor-nans``
1170
1171 * ``-fno-math-errno``
1172
1173 * ``-ffinite-math``
1174
1175 * ``-fassociative-math``
1176
1177 * ``-freciprocal-math``
1178
1179 * ``-fno-signed-zeros``
1180
1181 * ``-fno-trapping-math``
1182
1183 * ``-ffp-contract=fast``
1184
1185.. option:: -fdenormal-fp-math=<value>
1186
1187 Select which denormal numbers the code is permitted to require.
1188
1189 Valid values are:
1190
1191 * ``ieee`` - IEEE 754 denormal numbers
1192 * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 0
1193 * ``positive-zero`` - denormals are flushed to positive zero
1194
1195 Defaults to ``ieee``.
1196
1197.. _opt_fstrict-float-cast-overflow:
1198
1199**-f[no-]strict-float-cast-overflow**
1200
1201 When a floating-point value is not representable in a destination integer
1202 type, the code has undefined behavior according to the language standard.
1203 By default, Clang will not guarantee any particular result in that case.
1204 With the 'no-strict' option, Clang attempts to match the overflowing behavior
1205 of the target's native float-to-int conversion instructions.
1206
1207.. _opt_fmath-errno:
1208
1209**-f[no-]math-errno**
1210
1211 Require math functions to indicate errors by setting errno.
1212 The default varies by ToolChain. ``-fno-math-errno`` allows optimizations
1213 that might cause standard C math functions to not set ``errno``.
1214 For example, on some systems, the math function ``sqrt`` is specified
1215 as setting ``errno`` to ``EDOM`` when the input is negative. On these
1216 systems, the compiler cannot normally optimize a call to ``sqrt`` to use
1217 inline code (e.g. the x86 ``sqrtsd`` instruction) without additional
1218 checking to ensure that ``errno`` is set appropriately.
1219 ``-fno-math-errno`` permits these transformations.
1220
1221 On some targets, math library functions never set ``errno``, and so
1222 ``-fno-math-errno`` is the default. This includes most BSD-derived
1223 systems, including Darwin.
1224
1225.. _opt_ftrapping-math:
1226
1227**-f[no-]trapping-math**
1228
1229 ``-fno-trapping-math`` allows optimizations that assume that
1230 floating point operations cannot generate traps such as divide-by-zero,
1231 overflow and underflow. Defaults to ``-ftrapping-math``.
1232 Currently this option has no effect.
1233
1234.. option:: -ffp-contract=<value>
1235
1236 Specify when the compiler is permitted to form fused floating-point
1237 operations, such as fused multiply-add (FMA). Fused operations are
1238 permitted to produce more precise results than performing the same
1239 operations separately.
1240
1241 The C standard permits intermediate floating-point results within an
1242 expression to be computed with more precision than their type would
1243 normally allow. This permits operation fusing, and Clang takes advantage
1244 of this by default. This behavior can be controlled with the
1245 ``FP_CONTRACT`` pragma. Please refer to the pragma documentation for a
1246 description of how the pragma interacts with this option.
1247
1248 Valid values are:
1249
1250 * ``fast`` (everywhere)
1251 * ``on`` (according to FP_CONTRACT pragma, default)
1252 * ``off`` (never fuse)
1253
1254.. _opt_fhonor-infinities:
1255
1256**-f[no-]honor-infinities**
1257
1258 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1259 has the same effect as specifying ``-ffinite-math``.
1260
1261.. _opt_fhonor-nans:
1262
1263**-f[no-]honor-nans**
1264
1265 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1266 has the same effect as specifying ``-ffinite-math``.
1267
1268.. _opt_fsigned-zeros:
1269
1270**-f[no-]signed-zeros**
1271
1272 Allow optimizations that ignore the sign of floating point zeros.
1273 Defaults to ``-fno-signed-zeros``.
1274
1275.. _opt_fassociative-math:
1276
1277**-f[no-]associative-math**
1278
1279 Allow floating point operations to be reassociated.
1280 Defaults to ``-fno-associative-math``.
1281
1282.. _opt_freciprocal-math:
1283
1284**-f[no-]reciprocal-math**
1285
1286 Allow division operations to be transformed into multiplication by a
1287 reciprocal. This can be significantly faster than an ordinary division
1288 but can also have significantly less precision. Defaults to
1289 ``-fno-reciprocal-math``.
1290
1291.. _opt_funsafe-math-optimizations:
1292
1293**-f[no-]unsafe-math-optimizations**
1294
1295 Allow unsafe floating-point optimizations. Also implies:
1296
1297 * ``-fassociative-math``
1298 * ``-freciprocal-math``
1299 * ``-fno-signed-zeroes``
1300 * ``-fno-trapping-math``.
1301
1302 Defaults to ``-fno-unsafe-math-optimizations``.
1303
1304.. _opt_ffinite-math:
1305
1306**-f[no-]finite-math**
1307
1308 Allow floating-point optimizations that assume arguments and results are
1309 not NaNs or +-Inf. This defines the ``__FINITE_MATH_ONLY__`` preprocessor macro.
1310 Also implies:
1311
1312 * ``-fno-honor-infinities``
1313 * ``-fno-honor-nans``
1314
1315 Defaults to ``-fno-finite-math``.
1316
Peter Collingbourne915df992015-05-15 18:33:32 +00001317.. _controlling-code-generation:
1318
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001319Controlling Code Generation
1320---------------------------
1321
1322Clang provides a number of ways to control code generation. The options
1323are listed below.
1324
Sean Silva4c280bd2013-06-21 23:50:58 +00001325**-f[no-]sanitize=check1,check2,...**
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001326 Turn on runtime checks for various forms of undefined or suspicious
1327 behavior.
1328
1329 This option controls whether Clang adds runtime checks for various
1330 forms of undefined or suspicious behavior, and is disabled by
1331 default. If a check fails, a diagnostic message is produced at
1332 runtime explaining the problem. The main checks are:
1333
Richard Smithbb741f42012-12-13 07:29:23 +00001334 - .. _opt_fsanitize_address:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001335
Richard Smithbb741f42012-12-13 07:29:23 +00001336 ``-fsanitize=address``:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001337 :doc:`AddressSanitizer`, a memory error
1338 detector.
Richard Smithbb741f42012-12-13 07:29:23 +00001339 - .. _opt_fsanitize_thread:
1340
Dmitry Vyukov42de1082012-12-21 08:21:25 +00001341 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
Evgeniy Stepanov17d55902012-12-21 10:50:00 +00001342 - .. _opt_fsanitize_memory:
1343
1344 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
Alexey Samsonov1f7051e2015-12-04 22:50:44 +00001345 a detector of uninitialized reads. Requires instrumentation of all
1346 program code.
Richard Smithbb741f42012-12-13 07:29:23 +00001347 - .. _opt_fsanitize_undefined:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001348
Alexey Samsonov778fc722015-12-04 17:30:29 +00001349 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
1350 a fast and compatible undefined behavior checker.
Peter Collingbourne9881b782015-06-18 23:59:22 +00001351
Peter Collingbournec3772752013-08-07 22:47:34 +00001352 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
1353 flow analysis.
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001354 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
Alexey Samsonov907880e2015-06-19 19:57:46 +00001355 checks. Requires ``-flto``.
Peter Collingbournec4122c12015-06-15 21:08:13 +00001356 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
1357 protection against stack-based memory corruption errors.
Chad Rosierae229d52013-01-29 23:31:22 +00001358
Alexey Samsonov778fc722015-12-04 17:30:29 +00001359 There are more fine-grained checks available: see
1360 the :ref:`list <ubsan-checks>` of specific kinds of
Alexey Samsonov9eda6402015-12-04 21:30:58 +00001361 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
1362 of control flow integrity schemes.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001363
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001364 The ``-fsanitize=`` argument must also be provided when linking, in
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001365 order to link to the appropriate runtime library.
Richard Smith83c728b2013-07-19 19:06:48 +00001366
1367 It is not possible to combine more than one of the ``-fsanitize=address``,
1368 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
Alexey Samsonov88460172015-12-04 17:35:47 +00001369 program.
Richard Smith83c728b2013-07-19 19:06:48 +00001370
Alexey Samsonov88459522015-01-12 22:39:12 +00001371**-f[no-]sanitize-recover=check1,check2,...**
Kostya Serebryany40b82152016-05-04 20:24:54 +00001372
Kostya Serebryanyceb1add2016-05-04 20:21:47 +00001373**-f[no-]sanitize-recover=all**
Alexey Samsonov88459522015-01-12 22:39:12 +00001374
1375 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
1376 If the check is fatal, program will halt after the first error
1377 of this kind is detected and error report is printed.
1378
Alexey Samsonov778fc722015-12-04 17:30:29 +00001379 By default, non-fatal checks are those enabled by
1380 :doc:`UndefinedBehaviorSanitizer`,
Alexey Samsonov88459522015-01-12 22:39:12 +00001381 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
Yury Gribov5bfeca12015-11-11 10:45:48 +00001382 sanitizers may not support recovery (or not support it by default
1383 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
1384 is detected.
Alexey Samsonov88459522015-01-12 22:39:12 +00001385
Peter Collingbourne9881b782015-06-18 23:59:22 +00001386 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
1387 This means that if a check has been configured to trap elsewhere on the
1388 command line, or if the check traps by default, this flag will not have
1389 any effect unless that sanitizer's trapping behavior is disabled with
1390 ``-fno-sanitize-trap``.
1391
1392 For example, if a command line contains the flags ``-fsanitize=undefined
1393 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
1394 will have no effect on its own; it will need to be accompanied by
1395 ``-fno-sanitize-trap=alignment``.
1396
1397**-f[no-]sanitize-trap=check1,check2,...**
1398
1399 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
1400 option is intended for use in cases where the sanitizer runtime cannot
1401 be used (for instance, when building libc or a kernel module), or where
1402 the binary size increase caused by the sanitizer runtime is a concern.
1403
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001404 This flag is only compatible with :doc:`control flow integrity
1405 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
1406 checks other than ``vptr``. If this flag
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001407 is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
1408 will be implicitly disabled.
1409
1410 This flag is enabled by default for sanitizers in the ``cfi`` group.
Peter Collingbourne9881b782015-06-18 23:59:22 +00001411
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001412.. option:: -fsanitize-blacklist=/path/to/blacklist/file
1413
1414 Disable or modify sanitizer checks for objects (source files, functions,
1415 variables, types) listed in the file. See
1416 :doc:`SanitizerSpecialCaseList` for file format description.
1417
1418.. option:: -fno-sanitize-blacklist
1419
1420 Don't use blacklist file, if it was specified earlier in the command line.
1421
Alexey Samsonov8fffba12015-05-07 23:04:19 +00001422**-f[no-]sanitize-coverage=[type,features,...]**
1423
1424 Enable simple code coverage in addition to certain sanitizers.
1425 See :doc:`SanitizerCoverage` for more details.
1426
Peter Collingbournedc134532016-01-16 00:31:22 +00001427**-f[no-]sanitize-stats**
1428
1429 Enable simple statistics gathering for the enabled sanitizers.
1430 See :doc:`SanitizerStats` for more details.
1431
Peter Collingbourne9881b782015-06-18 23:59:22 +00001432.. option:: -fsanitize-undefined-trap-on-error
1433
1434 Deprecated alias for ``-fsanitize-trap=undefined``.
1435
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001436.. option:: -fsanitize-cfi-cross-dso
1437
1438 Enable cross-DSO control flow integrity checks. This flag modifies
1439 the behavior of sanitizers in the ``cfi`` group to allow checking
1440 of cross-DSO virtual and indirect calls.
1441
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001442.. option:: -fsanitize-cfi-icall-generalize-pointers
1443
1444 Generalize pointers in return and argument types in function type signatures
1445 checked by Control Flow Integrity indirect call checking. See
1446 :doc:`ControlFlowIntegrity` for more details.
Piotr Padlewskieb9dd5a2017-01-16 13:20:08 +00001447
1448.. option:: -fstrict-vtable-pointers
Hans Wennborgf6d61d42017-01-17 21:31:57 +00001449
Piotr Padlewskieb9dd5a2017-01-16 13:20:08 +00001450 Enable optimizations based on the strict rules for overwriting polymorphic
1451 C++ objects, i.e. the vptr is invariant during an object's lifetime.
1452 This enables better devirtualization. Turned off by default, because it is
1453 still experimental.
1454
Peter Collingbournefb532b92016-02-24 20:46:36 +00001455.. option:: -fwhole-program-vtables
1456
1457 Enable whole-program vtable optimizations, such as single-implementation
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001458 devirtualization and virtual constant propagation, for classes with
1459 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
Peter Collingbournefb532b92016-02-24 20:46:36 +00001460
Piotr Padlewskie368de32018-06-13 13:55:42 +00001461.. option:: -fforce-emit-vtables
1462
1463 In order to improve devirtualization, forces emitting of vtables even in
1464 modules where it isn't necessary. It causes more inline virtual functions
1465 to be emitted.
1466
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001467.. option:: -fno-assume-sane-operator-new
1468
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001469 Don't assume that the C++'s new operator is sane.
1470
1471 This option tells the compiler to do not assume that C++'s global
1472 new operator will always return a pointer that does not alias any
1473 other pointer when the function returns.
1474
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001475.. option:: -ftrap-function=[name]
1476
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001477 Instruct code generator to emit a function call to the specified
1478 function name for ``__builtin_trap()``.
1479
1480 LLVM code generator translates ``__builtin_trap()`` to a trap
1481 instruction if it is supported by the target ISA. Otherwise, the
1482 builtin is translated into a call to ``abort``. If this option is
1483 set, then the code generator will always lower the builtin to a call
1484 to the specified function regardless of whether the target ISA has a
1485 trap instruction. This option is useful for environments (e.g.
1486 deeply embedded) where a trap cannot be properly handled, or when
1487 some custom behavior is desired.
1488
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001489.. option:: -ftls-model=[model]
1490
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001491 Select which TLS model to use.
1492
1493 Valid values are: ``global-dynamic``, ``local-dynamic``,
1494 ``initial-exec`` and ``local-exec``. The default value is
1495 ``global-dynamic``. The compiler may use a different model if the
1496 selected model is not supported by the target, or if a more
1497 efficient model can be used. The TLS model can be overridden per
1498 variable using the ``tls_model`` attribute.
1499
Chih-Hung Hsieh2c656c92015-07-28 16:27:56 +00001500.. option:: -femulated-tls
1501
1502 Select emulated TLS model, which overrides all -ftls-model choices.
1503
1504 In emulated TLS mode, all access to TLS variables are converted to
1505 calls to __emutls_get_address in the runtime library.
1506
Silviu Barangaf9671dd2013-10-21 10:54:53 +00001507.. option:: -mhwdiv=[values]
1508
1509 Select the ARM modes (arm or thumb) that support hardware division
1510 instructions.
1511
1512 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
1513 This option is used to indicate which mode (arm or thumb) supports
1514 hardware division instructions. This only applies to the ARM
1515 architecture.
1516
Bernard Ogden18b57012013-10-29 09:47:51 +00001517.. option:: -m[no-]crc
1518
1519 Enable or disable CRC instructions.
1520
1521 This option is used to indicate whether CRC instructions are to
1522 be generated. This only applies to the ARM architecture.
1523
1524 CRC instructions are enabled by default on ARMv8.
1525
Amara Emerson05d816d2014-01-24 15:15:27 +00001526.. option:: -mgeneral-regs-only
Amara Emerson04e2ecf2014-01-23 15:48:30 +00001527
1528 Generate code which only uses the general purpose registers.
1529
1530 This option restricts the generated code to use general registers
1531 only. This only applies to the AArch64 architecture.
1532
Simon Dardisd0e83ba2016-05-27 15:13:31 +00001533.. option:: -mcompact-branches=[values]
1534
1535 Control the usage of compact branches for MIPSR6.
1536
1537 Valid values are: ``never``, ``optimal`` and ``always``.
1538 The default value is ``optimal`` which generates compact branches
1539 when a delay slot cannot be filled. ``never`` disables the usage of
1540 compact branches and ``always`` generates compact branches whenever
1541 possible.
1542
Yunzhong Gaoeecc9e972015-12-10 01:37:18 +00001543**-f[no-]max-type-align=[number]**
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00001544 Instruct the code generator to not enforce a higher alignment than the given
1545 number (of bytes) when accessing memory via an opaque pointer or reference.
1546 This cap is ignored when directly accessing a variable or when the pointee
1547 type has an explicit “aligned” attribute.
1548
1549 The value should usually be determined by the properties of the system allocator.
1550 Some builtin types, especially vector types, have very high natural alignments;
1551 when working with values of those types, Clang usually wants to use instructions
1552 that take advantage of that alignment. However, many system allocators do
1553 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
1554 this option to limit the alignment that the compiler can assume for an arbitrary
1555 pointer, which may point onto the heap.
1556
1557 This option does not affect the ABI alignment of types; the layout of structs and
1558 unions and the value returned by the alignof operator remain the same.
1559
1560 This option can be overridden on a case-by-case basis by putting an explicit
1561 “aligned” alignment on a struct, union, or typedef. For example:
1562
1563 .. code-block:: console
1564
1565 #include <immintrin.h>
1566 // Make an aligned typedef of the AVX-512 16-int vector type.
1567 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
1568
1569 void initialize_vector(__aligned_v16si *v) {
1570 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
Yunzhong Gaoeecc9e972015-12-10 01:37:18 +00001571 // value of -fmax-type-align.
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00001572 }
1573
Peter Collingbourne14b468b2018-07-18 00:27:07 +00001574.. option:: -faddrsig, -fno-addrsig
1575
1576 Controls whether Clang emits an address-significance table into the object
1577 file. Address-significance tables allow linkers to implement `safe ICF
1578 <https://research.google.com/pubs/archive/36912.pdf>`_ without the false
1579 positives that can result from other implementation techniques such as
1580 relocation scanning. Address-significance tables are enabled by default
1581 on ELF targets when using the integrated assembler. This flag currently
1582 only has an effect on ELF targets.
Silviu Barangaf9671dd2013-10-21 10:54:53 +00001583
Bob Wilson3f2ed172014-06-17 00:45:30 +00001584Profile Guided Optimization
1585---------------------------
1586
1587Profile information enables better optimization. For example, knowing that a
1588branch is taken very frequently helps the compiler make better decisions when
1589ordering basic blocks. Knowing that a function ``foo`` is called more
Eric Christopherc61c9b62018-01-31 19:52:58 +00001590frequently than another function ``bar`` helps the inliner. Optimization
1591levels ``-O2`` and above are recommended for use of profile guided optimization.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001592
1593Clang supports profile guided optimization with two different kinds of
1594profiling. A sampling profiler can generate a profile with very low runtime
1595overhead, or you can build an instrumented version of the code that collects
1596more detailed profile information. Both kinds of profiles can provide execution
1597counts for instructions in the code and information on branches taken and
1598function invocation.
1599
1600Regardless of which kind of profiling you use, be careful to collect profiles
1601by running your code with inputs that are representative of the typical
1602behavior. Code that is not exercised in the profile will be optimized as if it
1603is unimportant, and the compiler may make poor optimization choices for code
1604that is disproportionately used while profiling.
1605
Diego Novillo46ab35d2015-05-28 21:30:04 +00001606Differences Between Sampling and Instrumentation
1607^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1608
1609Although both techniques are used for similar purposes, there are important
1610differences between the two:
1611
16121. Profile data generated with one cannot be used by the other, and there is no
1613 conversion tool that can convert one to the other. So, a profile generated
1614 via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
1615 Similarly, sampling profiles generated by external profilers must be
1616 converted and used with ``-fprofile-sample-use``.
1617
16182. Instrumentation profile data can be used for code coverage analysis and
1619 optimization.
1620
16213. Sampling profiles can only be used for optimization. They cannot be used for
1622 code coverage analysis. Although it would be technically possible to use
1623 sampling profiles for code coverage, sample-based profiles are too
1624 coarse-grained for code coverage purposes; it would yield poor results.
1625
16264. Sampling profiles must be generated by an external tool. The profile
1627 generated by that tool must then be converted into a format that can be read
1628 by LLVM. The section on sampling profilers describes one of the supported
1629 sampling profile formats.
1630
1631
Bob Wilson3f2ed172014-06-17 00:45:30 +00001632Using Sampling Profilers
1633^^^^^^^^^^^^^^^^^^^^^^^^
Diego Novilloa5256bf2014-04-23 15:21:07 +00001634
1635Sampling profilers are used to collect runtime information, such as
1636hardware counters, while your application executes. They are typically
Diego Novillo8ebff322014-04-23 15:21:20 +00001637very efficient and do not incur a large runtime overhead. The
Diego Novilloa5256bf2014-04-23 15:21:07 +00001638sample data collected by the profiler can be used during compilation
Diego Novillo8ebff322014-04-23 15:21:20 +00001639to determine what the most executed areas of the code are.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001640
Diego Novilloa5256bf2014-04-23 15:21:07 +00001641Using the data from a sample profiler requires some changes in the way
1642a program is built. Before the compiler can use profiling information,
1643the code needs to execute under the profiler. The following is the
1644usual build cycle when using sample profilers for optimization:
1645
16461. Build the code with source line table information. You can use all the
1647 usual build flags that you always build your application with. The only
Diego Novillo8ebff322014-04-23 15:21:20 +00001648 requirement is that you add ``-gline-tables-only`` or ``-g`` to the
Diego Novilloa5256bf2014-04-23 15:21:07 +00001649 command line. This is important for the profiler to be able to map
1650 instructions back to source line locations.
1651
1652 .. code-block:: console
1653
1654 $ clang++ -O2 -gline-tables-only code.cc -o code
1655
16562. Run the executable under a sampling profiler. The specific profiler
1657 you use does not really matter, as long as its output can be converted
1658 into the format that the LLVM optimizer understands. Currently, there
1659 exists a conversion tool for the Linux Perf profiler
1660 (https://perf.wiki.kernel.org/), so these examples assume that you
1661 are using Linux Perf to profile your code.
1662
1663 .. code-block:: console
1664
1665 $ perf record -b ./code
1666
1667 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
1668 Record (LBR) to record call chains. While this is not strictly required,
1669 it provides better call information, which improves the accuracy of
1670 the profile data.
1671
16723. Convert the collected profile data to LLVM's sample profile format.
1673 This is currently supported via the AutoFDO converter ``create_llvm_prof``.
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001674 It is available at https://github.com/google/autofdo. Once built and
Diego Novilloa5256bf2014-04-23 15:21:07 +00001675 installed, you can convert the ``perf.data`` file to LLVM using
1676 the command:
1677
1678 .. code-block:: console
1679
1680 $ create_llvm_prof --binary=./code --out=code.prof
1681
Diego Novillo9e430842014-04-23 15:21:23 +00001682 This will read ``perf.data`` and the binary file ``./code`` and emit
Diego Novilloa5256bf2014-04-23 15:21:07 +00001683 the profile data in ``code.prof``. Note that if you ran ``perf``
1684 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
1685 calling ``create_llvm_prof``.
1686
16874. Build the code again using the collected profile. This step feeds
1688 the profile back to the optimizers. This should result in a binary
Diego Novillo8ebff322014-04-23 15:21:20 +00001689 that executes faster than the original one. Note that you are not
1690 required to build the code with the exact same arguments that you
1691 used in the first step. The only requirement is that you build the code
1692 with ``-gline-tables-only`` and ``-fprofile-sample-use``.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001693
1694 .. code-block:: console
1695
1696 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
1697
1698
Diego Novillo46ab35d2015-05-28 21:30:04 +00001699Sample Profile Formats
1700""""""""""""""""""""""
Diego Novilloa5256bf2014-04-23 15:21:07 +00001701
Diego Novillo46ab35d2015-05-28 21:30:04 +00001702Since external profilers generate profile data in a variety of custom formats,
1703the data generated by the profiler must be converted into a format that can be
1704read by the backend. LLVM supports three different sample profile formats:
Diego Novilloa5256bf2014-04-23 15:21:07 +00001705
Diego Novillo46ab35d2015-05-28 21:30:04 +000017061. ASCII text. This is the easiest one to generate. The file is divided into
1707 sections, which correspond to each of the functions with profile
Diego Novillo33452762015-10-14 18:37:39 +00001708 information. The format is described below. It can also be generated from
1709 the binary or gcov formats using the ``llvm-profdata`` tool.
Diego Novilloe0d289e2015-05-22 16:05:07 +00001710
Diego Novillo46ab35d2015-05-28 21:30:04 +000017112. Binary encoding. This uses a more efficient encoding that yields smaller
Diego Novillo33452762015-10-14 18:37:39 +00001712 profile files. This is the format generated by the ``create_llvm_prof`` tool
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001713 in https://github.com/google/autofdo.
Diego Novillo46ab35d2015-05-28 21:30:04 +00001714
17153. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
Diego Novillo33452762015-10-14 18:37:39 +00001716 is only interesting in environments where GCC and Clang co-exist. This
1717 encoding is only generated by the ``create_gcov`` tool in
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00001718 https://github.com/google/autofdo. It can be read by LLVM and
Diego Novillo33452762015-10-14 18:37:39 +00001719 ``llvm-profdata``, but it cannot be generated by either.
Diego Novillo46ab35d2015-05-28 21:30:04 +00001720
1721If you are using Linux Perf to generate sampling profiles, you can use the
1722conversion tool ``create_llvm_prof`` described in the previous section.
1723Otherwise, you will need to write a conversion tool that converts your
1724profiler's native format into one of these three.
1725
1726
1727Sample Profile Text Format
1728""""""""""""""""""""""""""
1729
1730This section describes the ASCII text format for sampling profiles. It is,
1731arguably, the easiest one to generate. If you are interested in generating any
Sylvestre Ledru6fd88392017-08-27 17:34:06 +00001732of the other two, consult the ``ProfileData`` library in LLVM's source tree
Diego Novillo843dc6f2015-10-19 15:53:17 +00001733(specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
Diego Novilloa5256bf2014-04-23 15:21:07 +00001734
1735.. code-block:: console
1736
1737 function1:total_samples:total_head_samples
Diego Novillo33452762015-10-14 18:37:39 +00001738 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
1739 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
1740 ...
1741 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
1742 offsetA[.discriminator]: fnA:num_of_total_samples
1743 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
1744 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
1745 offsetB[.discriminator]: fnB:num_of_total_samples
1746 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
Diego Novilloa5256bf2014-04-23 15:21:07 +00001747
Sylvestre Ledru6fd88392017-08-27 17:34:06 +00001748This is a nested tree in which the indentation represents the nesting level
Diego Novillo33452762015-10-14 18:37:39 +00001749of the inline stack. There are no blank lines in the file. And the spacing
1750within a single line is fixed. Additional spaces will result in an error
1751while reading the file.
1752
1753Any line starting with the '#' character is completely ignored.
1754
1755Inlined calls are represented with indentation. The Inline stack is a
1756stack of source locations in which the top of the stack represents the
1757leaf function, and the bottom of the stack represents the actual
1758symbol to which the instruction belongs.
Diego Novillo8ebff322014-04-23 15:21:20 +00001759
Diego Novilloa5256bf2014-04-23 15:21:07 +00001760Function names must be mangled in order for the profile loader to
1761match them in the current translation unit. The two numbers in the
1762function header specify how many total samples were accumulated in the
1763function (first number), and the total number of samples accumulated
Diego Novillo8ebff322014-04-23 15:21:20 +00001764in the prologue of the function (second number). This head sample
1765count provides an indicator of how frequently the function is invoked.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001766
Diego Novillo33452762015-10-14 18:37:39 +00001767There are two types of lines in the function body.
1768
1769- Sampled line represents the profile information of a source location.
1770 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
1771
1772- Callsite line represents the profile information of an inlined callsite.
1773 ``offsetA[.discriminator]: fnA:num_of_total_samples``
1774
Diego Novilloa5256bf2014-04-23 15:21:07 +00001775Each sampled line may contain several items. Some are optional (marked
1776below):
1777
1778a. Source line offset. This number represents the line number
1779 in the function where the sample was collected. The line number is
1780 always relative to the line where symbol of the function is
1781 defined. So, if the function has its header at line 280, the offset
1782 13 is at line 293 in the file.
1783
Diego Novillo897c59c2014-04-23 15:21:21 +00001784 Note that this offset should never be a negative number. This could
1785 happen in cases like macros. The debug machinery will register the
1786 line number at the point of macro expansion. So, if the macro was
1787 expanded in a line before the start of the function, the profile
1788 converter should emit a 0 as the offset (this means that the optimizers
1789 will not be able to associate a meaningful weight to the instructions
1790 in the macro).
1791
Diego Novilloa5256bf2014-04-23 15:21:07 +00001792b. [OPTIONAL] Discriminator. This is used if the sampled program
1793 was compiled with DWARF discriminator support
Diego Novillo8ebff322014-04-23 15:21:20 +00001794 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
Diego Novillo897c59c2014-04-23 15:21:21 +00001795 DWARF discriminators are unsigned integer values that allow the
1796 compiler to distinguish between multiple execution paths on the
1797 same source line location.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001798
Diego Novillo8ebff322014-04-23 15:21:20 +00001799 For example, consider the line of code ``if (cond) foo(); else bar();``.
1800 If the predicate ``cond`` is true 80% of the time, then the edge
1801 into function ``foo`` should be considered to be taken most of the
1802 time. But both calls to ``foo`` and ``bar`` are at the same source
1803 line, so a sample count at that line is not sufficient. The
1804 compiler needs to know which part of that line is taken more
1805 frequently.
1806
1807 This is what discriminators provide. In this case, the calls to
1808 ``foo`` and ``bar`` will be at the same line, but will have
1809 different discriminator values. This allows the compiler to correctly
1810 set edge weights into ``foo`` and ``bar``.
1811
1812c. Number of samples. This is an integer quantity representing the
1813 number of samples collected by the profiler at this source
1814 location.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001815
1816d. [OPTIONAL] Potential call targets and samples. If present, this
1817 line contains a call instruction. This models both direct and
Diego Novilloa5256bf2014-04-23 15:21:07 +00001818 number of samples. For example,
1819
1820 .. code-block:: console
1821
1822 130: 7 foo:3 bar:2 baz:7
1823
1824 The above means that at relative line offset 130 there is a call
Diego Novillo8ebff322014-04-23 15:21:20 +00001825 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
1826 with ``baz()`` being the relatively more frequently called target.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001827
Diego Novillo33452762015-10-14 18:37:39 +00001828As an example, consider a program with the call chain ``main -> foo -> bar``.
1829When built with optimizations enabled, the compiler may inline the
1830calls to ``bar`` and ``foo`` inside ``main``. The generated profile
1831could then be something like this:
1832
1833.. code-block:: console
1834
1835 main:35504:0
1836 1: _Z3foov:35504
1837 2: _Z32bari:31977
1838 1.1: 31977
1839 2: 0
1840
1841This profile indicates that there were a total of 35,504 samples
1842collected in main. All of those were at line 1 (the call to ``foo``).
1843Of those, 31,977 were spent inside the body of ``bar``. The last line
1844of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
1845samples were collected there.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001846
Bob Wilson3f2ed172014-06-17 00:45:30 +00001847Profiling with Instrumentation
1848^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1849
1850Clang also supports profiling via instrumentation. This requires building a
1851special instrumented version of the code and has some runtime
1852overhead during the profiling, but it provides more detailed results than a
1853sampling profiler. It also provides reproducible results, at least to the
1854extent that the code behaves consistently across runs.
1855
1856Here are the steps for using profile guided optimization with
1857instrumentation:
1858
18591. Build an instrumented version of the code by compiling and linking with the
1860 ``-fprofile-instr-generate`` option.
1861
1862 .. code-block:: console
1863
1864 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
1865
18662. Run the instrumented executable with inputs that reflect the typical usage.
1867 By default, the profile data will be written to a ``default.profraw`` file
Xinliang David Li7cd5e382016-07-20 23:32:50 +00001868 in the current directory. You can override that default by using option
1869 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
1870 environment variable to specify an alternate file. If non-default file name
1871 is specified by both the environment variable and the command line option,
1872 the environment variable takes precedence. The file name pattern specified
1873 can include different modifiers: ``%p``, ``%h``, and ``%m``.
1874
Bob Wilson3f2ed172014-06-17 00:45:30 +00001875 Any instance of ``%p`` in that file name will be replaced by the process
1876 ID, so that you can easily distinguish the profile output from multiple
1877 runs.
1878
1879 .. code-block:: console
1880
1881 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
1882
Xinliang David Li7cd5e382016-07-20 23:32:50 +00001883 The modifier ``%h`` can be used in scenarios where the same instrumented
1884 binary is run in multiple different host machines dumping profile data
1885 to a shared network based storage. The ``%h`` specifier will be substituted
1886 with the hostname so that profiles collected from different hosts do not
1887 clobber each other.
1888
1889 While the use of ``%p`` specifier can reduce the likelihood for the profiles
1890 dumped from different processes to clobber each other, such clobbering can still
1891 happen because of the ``pid`` re-use by the OS. Another side-effect of using
1892 ``%p`` is that the storage requirement for raw profile data files is greatly
1893 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
1894 name. When this specifier is used, the profiler runtime will substitute ``%m``
1895 with a unique integer identifier associated with the instrumented binary. Additionally,
1896 multiple raw profiles dumped from different processes that share a file system (can be
1897 on different hosts) will be automatically merged by the profiler runtime during the
1898 dumping. If the program links in multiple instrumented shared libraries, each library
1899 will dump the profile data into its own profile data file (with its unique integer
1900 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
1901 profile data generated by profiler runtime. The resulting merged "raw" profile data
1902 file still needs to be converted to a different format expected by the compiler (
1903 see step 3 below).
1904
1905 .. code-block:: console
1906
1907 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
1908
1909
Bob Wilson3f2ed172014-06-17 00:45:30 +000019103. Combine profiles from multiple runs and convert the "raw" profile format to
Diego Novillo46ab35d2015-05-28 21:30:04 +00001911 the input expected by clang. Use the ``merge`` command of the
1912 ``llvm-profdata`` tool to do this.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001913
1914 .. code-block:: console
1915
1916 $ llvm-profdata merge -output=code.profdata code-*.profraw
1917
1918 Note that this step is necessary even when there is only one "raw" profile,
1919 since the merge operation also changes the file format.
1920
19214. Build the code again using the ``-fprofile-instr-use`` option to specify the
1922 collected profile data.
1923
1924 .. code-block:: console
1925
1926 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
1927
1928 You can repeat step 4 as often as you like without regenerating the
1929 profile. As you make changes to your code, clang may no longer be able to
1930 use the profile data. It will warn you when this happens.
1931
Sean Silvaa834ff22016-07-16 02:54:58 +00001932Profile generation using an alternative instrumentation method can be
1933controlled by the GCC-compatible flags ``-fprofile-generate`` and
1934``-fprofile-use``. Although these flags are semantically equivalent to
1935their GCC counterparts, they *do not* handle GCC-compatible profiles.
1936They are only meant to implement GCC's semantics with respect to
Rong Xua4a09b22019-03-04 20:21:31 +00001937profile creation and use. Flag ``-fcs-profile-generate`` also instruments
1938programs using the same instrumentation method as ``-fprofile-generate``.
Diego Novillo578caf52015-07-09 17:23:53 +00001939
1940.. option:: -fprofile-generate[=<dirname>]
1941
Sean Silvaa834ff22016-07-16 02:54:58 +00001942 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
Joel Galenson267ea722018-05-07 16:23:46 +00001943 an alternative instrumentation method for profile generation. When
Sean Silvaa834ff22016-07-16 02:54:58 +00001944 given a directory name, it generates the profile file
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001945 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
1946 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
Joel Galenson267ea722018-05-07 16:23:46 +00001947 will be substituted with a unique id documented in step 2 above. In other words,
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001948 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
1949 merging is turned on by default, so there will no longer any risk of profile
1950 clobbering from different running processes. For example,
Diego Novillo578caf52015-07-09 17:23:53 +00001951
1952 .. code-block:: console
1953
1954 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
1955
1956 When ``code`` is executed, the profile will be written to the file
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001957 ``yyy/zzz/default_xxxx.profraw``.
Diego Novillo578caf52015-07-09 17:23:53 +00001958
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001959 To generate the profile data file with the compiler readable format, the
1960 ``llvm-profdata`` tool can be used with the profile directory as the input:
Diego Novillo578caf52015-07-09 17:23:53 +00001961
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001962 .. code-block:: console
Diego Novillo578caf52015-07-09 17:23:53 +00001963
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001964 $ llvm-profdata merge -output=code.profdata yyy/zzz/
1965
1966 If the user wants to turn off the auto-merging feature, or simply override the
1967 the profile dumping path specified at command line, the environment variable
1968 ``LLVM_PROFILE_FILE`` can still be used to override
1969 the directory and filename for the profile file at runtime.
Diego Novillo578caf52015-07-09 17:23:53 +00001970
Rong Xua4a09b22019-03-04 20:21:31 +00001971.. option:: -fcs-profile-generate[=<dirname>]
1972
1973 The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use
1974 the same instrumentation method, and generate the same profile as in the
1975 ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is
1976 that the instrumentation is performed after inlining so that the resulted
1977 profile has a better context sensitive information. They cannot be used
1978 together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags.
1979 They are typically used in conjunction with ``-fprofile-use`` flag.
1980 The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate``
1981 can be merged by llvm-profdata. A use example:
1982
1983 .. code-block:: console
1984
1985 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
1986 $ ./code
1987 $ llvm-profdata merge -output=code.profdata yyy/zzz/
1988
1989 The first few steps are the same as that in ``-fprofile-generate``
1990 compilation. Then perform a second round of instrumentation.
1991
1992 .. code-block:: console
1993
1994 $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \
1995 -o cs_code
1996 $ ./cs_code
1997 $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata
1998
1999 The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile
2000 generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by
2001 ``-fprofile-use`` compilaton.
2002
2003 .. code-block:: console
2004
2005 $ clang++ -O2 -fprofile-use=cs_code.profdata
2006
2007 The above command will read both profiles to the compiler at the identical
2008 point of instrumenations.
2009
Diego Novillo578caf52015-07-09 17:23:53 +00002010.. option:: -fprofile-use[=<pathname>]
2011
2012 Without any other arguments, ``-fprofile-use`` behaves identically to
2013 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
2014 profile file, it reads from that file. If ``pathname`` is a directory name,
2015 it reads from ``pathname/default.profdata``.
2016
Diego Novillo758f3f52015-08-05 21:49:51 +00002017Disabling Instrumentation
2018^^^^^^^^^^^^^^^^^^^^^^^^^
2019
2020In certain situations, it may be useful to disable profile generation or use
2021for specific files in a build, without affecting the main compilation flags
2022used for the other files in the project.
2023
2024In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
2025``-fno-profile-generate``) to disable profile generation, and
2026``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
2027
2028Note that these flags should appear after the corresponding profile
2029flags to have an effect.
Bob Wilson3f2ed172014-06-17 00:45:30 +00002030
Richard Smith8654ae52018-10-10 23:13:35 +00002031Profile remapping
2032^^^^^^^^^^^^^^^^^
2033
2034When the program is compiled after a change that affects many symbol names,
2035pre-existing profile data may no longer match the program. For example:
2036
2037 * switching from libstdc++ to libc++ will result in the mangled names of all
2038 functions taking standard library types to change
2039 * renaming a widely-used type in C++ will result in the mangled names of all
2040 functions that have parameters involving that type to change
2041 * moving from a 32-bit compilation to a 64-bit compilation may change the
2042 underlying type of ``size_t`` and similar types, resulting in changes to
2043 manglings
2044
2045Clang allows use of a profile remapping file to specify that such differences
2046in mangled names should be ignored when matching the profile data against the
2047program.
2048
2049.. option:: -fprofile-remapping-file=<file>
2050
2051 Specifies a file containing profile remapping information, that will be
2052 used to match mangled names in the profile data to mangled names in the
2053 program.
2054
2055The profile remapping file is a text file containing lines of the form
2056
Jonas Toth30f6c632018-10-12 17:44:01 +00002057.. code-block:: text
Richard Smith8654ae52018-10-10 23:13:35 +00002058
2059 fragmentkind fragment1 fragment2
2060
2061where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``,
2062indicating whether the following mangled name fragments are
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00002063<`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s,
2064<`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or
2065<`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s,
Richard Smith8654ae52018-10-10 23:13:35 +00002066respectively.
Richard Smith8654ae52018-10-10 23:13:35 +00002067Blank lines and lines starting with ``#`` are ignored.
2068
Richard Smithdf398bd2018-10-11 23:48:11 +00002069For convenience, built-in <substitution>s such as ``St`` and ``Ss``
2070are accepted as <name>s (even though they technically are not <name>s).
2071
Richard Smith8654ae52018-10-10 23:13:35 +00002072For example, to specify that ``absl::string_view`` and ``std::string_view``
2073should be treated as equivalent when matching profile data, the following
2074remapping file could be used:
2075
Jonas Toth20ab6952018-10-12 17:57:18 +00002076.. code-block:: text
Richard Smith8654ae52018-10-10 23:13:35 +00002077
2078 # absl::string_view is considered equivalent to std::string_view
2079 type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE
2080
2081 # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++
2082 name 3std St3__1
2083 name 3std St7__cxx11
2084
2085Matching profile data using a profile remapping file is supported on a
2086best-effort basis. For example, information regarding indirect call targets is
2087currently not remapped. For best results, you are encouraged to generate new
Richard Smithdf398bd2018-10-11 23:48:11 +00002088profile data matching the updated program, or to remap the profile data
2089using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools.
Richard Smith8654ae52018-10-10 23:13:35 +00002090
2091.. note::
2092
Richard Smithcee53ce2018-10-10 23:33:18 +00002093 Profile data remapping support is currently only implemented for LLVM's
2094 new pass manager, which can be enabled with
2095 ``-fexperimental-new-pass-manager``.
2096
2097.. note::
2098
Richard Smith8654ae52018-10-10 23:13:35 +00002099 Profile data remapping is currently only supported for C++ mangled names
2100 following the Itanium C++ ABI mangling scheme. This covers all C++ targets
2101 supported by Clang other than Windows.
2102
Calixte Denizetf4bf6712018-11-17 19:41:39 +00002103GCOV-based Profiling
2104--------------------
2105
2106GCOV is a test coverage program, it helps to know how often a line of code
2107is executed. When instrumenting the code with ``--coverage`` option, some
2108counters are added for each edge linking basic blocks.
2109
2110At compile time, gcno files are generated containing information about
2111blocks and edges between them. At runtime the counters are incremented and at
2112exit the counters are dumped in gcda files.
2113
2114The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate
2115a report ``.c.gcov``.
2116
2117.. option:: -fprofile-filter-files=[regexes]
2118
2119 Define a list of regexes separated by a semi-colon.
2120 If a file name matches any of the regexes then the file is instrumented.
2121
2122 .. code-block:: console
2123
2124 $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c
2125
2126 For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files.
2127
2128.. option:: -fprofile-exclude-files=[regexes]
2129
2130 Define a list of regexes separated by a semi-colon.
2131 If a file name doesn't match all the regexes then the file is instrumented.
2132
2133 .. code-block:: console
2134
2135 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c
2136
2137 For example, this will instrument all the files except the ones in ``/usr/include``.
2138
2139If both options are used then a file is instrumented if its name matches any
2140of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes
2141from ``-fprofile-exclude-list``.
2142
2143.. code-block:: console
2144
2145 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \
2146 -fprofile-filter-files="^/usr/.*$"
2147
2148In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and
2149doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches
2150the exclude regex.
2151
Paul Robinson0334a042015-12-19 19:41:48 +00002152Controlling Debug Information
2153-----------------------------
2154
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002155Controlling Size of Debug Information
Paul Robinson0334a042015-12-19 19:41:48 +00002156^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002157
2158Debug info kind generated by Clang can be set by one of the flags listed
2159below. If multiple flags are present, the last one is used.
2160
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002161.. option:: -g0
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002162
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002163 Don't generate any debug info (default).
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002164
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002165.. option:: -gline-tables-only
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002166
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002167 Generate line number tables only.
2168
2169 This kind of debug info allows to obtain stack traces with function names,
2170 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
2171 doesn't contain any other data (e.g. description of local variables or
2172 function parameters).
2173
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00002174.. option:: -fstandalone-debug
Adrian Prantl36b80672014-06-13 21:12:31 +00002175
2176 Clang supports a number of optimizations to reduce the size of debug
2177 information in the binary. They work based on the assumption that
2178 the debug type information can be spread out over multiple
2179 compilation units. For instance, Clang will not emit type
2180 definitions for types that are not needed by a module and could be
2181 replaced with a forward declaration. Further, Clang will only emit
2182 type info for a dynamic C++ class in the module that contains the
2183 vtable for the class.
2184
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00002185 The **-fstandalone-debug** option turns off these optimizations.
Adrian Prantl36b80672014-06-13 21:12:31 +00002186 This is useful when working with 3rd-party libraries that don't come
2187 with debug information. Note that Clang will never emit type
2188 information for types that are not referenced at all by the program.
2189
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00002190.. option:: -fno-standalone-debug
2191
2192 On Darwin **-fstandalone-debug** is enabled by default. The
2193 **-fno-standalone-debug** option can be used to get to turn on the
2194 vtable-based optimization described above.
2195
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002196.. option:: -g
2197
2198 Generate complete debug info.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002199
Amjad Aboud546bc112017-02-09 22:07:24 +00002200Controlling Macro Debug Info Generation
2201^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2202
2203Debug info for C preprocessor macros increases the size of debug information in
2204the binary. Macro debug info generated by Clang can be controlled by the flags
2205listed below.
2206
2207.. option:: -fdebug-macro
2208
2209 Generate debug info for preprocessor macros. This flag is discarded when
2210 **-g0** is enabled.
2211
2212.. option:: -fno-debug-macro
2213
2214 Do not generate debug info for preprocessor macros (default).
2215
Paul Robinson0334a042015-12-19 19:41:48 +00002216Controlling Debugger "Tuning"
2217^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2218
2219While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
2220different debuggers may know how to take advantage of different specific DWARF
2221features. You can "tune" the debug info for one of several different debuggers.
2222
2223.. option:: -ggdb, -glldb, -gsce
2224
Paul Robinson8ce9b442016-08-15 18:45:52 +00002225 Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg|
Paul Robinson0334a042015-12-19 19:41:48 +00002226 debugger, respectively. Each of these options implies **-g**. (Therefore, if
2227 you want both **-gline-tables-only** and debugger tuning, the tuning option
2228 must come first.)
2229
2230
Eric Fiselier123c7492018-02-07 18:36:51 +00002231Controlling LLVM IR Output
2232--------------------------
2233
2234Controlling Value Names in LLVM IR
2235^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2236
2237Emitting value names in LLVM IR increases the size and verbosity of the IR.
2238By default, value names are only emitted in assertion-enabled builds of Clang.
2239However, when reading IR it can be useful to re-enable the emission of value
2240names to improve readability.
2241
2242.. option:: -fdiscard-value-names
2243
2244 Discard value names when generating LLVM IR.
2245
2246.. option:: -fno-discard-value-names
2247
2248 Do not discard value names when generating LLVM IR. This option can be used
2249 to re-enable names for release builds of Clang.
2250
2251
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00002252Comment Parsing Options
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00002253-----------------------
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00002254
2255Clang parses Doxygen and non-Doxygen style documentation comments and attaches
2256them to the appropriate declaration nodes. By default, it only parses
2257Doxygen-style comments and ignores ordinary comments starting with ``//`` and
2258``/*``.
2259
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00002260.. option:: -Wdocumentation
2261
2262 Emit warnings about use of documentation comments. This warning group is off
2263 by default.
2264
2265 This includes checking that ``\param`` commands name parameters that actually
2266 present in the function signature, checking that ``\returns`` is used only on
2267 functions that actually return a value etc.
2268
2269.. option:: -Wno-documentation-unknown-command
2270
2271 Don't warn when encountering an unknown Doxygen command.
2272
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00002273.. option:: -fparse-all-comments
2274
2275 Parse all comments as documentation comments (including ordinary comments
2276 starting with ``//`` and ``/*``).
2277
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00002278.. option:: -fcomment-block-commands=[commands]
2279
2280 Define custom documentation commands as block commands. This allows Clang to
2281 construct the correct AST for these custom commands, and silences warnings
2282 about unknown commands. Several commands must be separated by a comma
2283 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
2284 custom commands ``\foo`` and ``\bar``.
2285
2286 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
2287 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
2288 as above.
2289
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002290.. _c:
2291
2292C Language Features
2293===================
2294
2295The support for standard C in clang is feature-complete except for the
2296C99 floating-point pragmas.
2297
2298Extensions supported by clang
2299-----------------------------
2300
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002301See :doc:`LanguageExtensions`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002302
2303Differences between various standard modes
2304------------------------------------------
2305
2306clang supports the -std option, which changes what language mode clang
Aaron Ballman567d9a32018-03-12 13:09:13 +00002307uses. The supported modes for C are c89, gnu89, c99, gnu99, c11, gnu11,
2308c17, gnu17, and various aliases for those modes. If no -std option is
Richard Smithab506ad2014-10-20 23:26:58 +00002309specified, clang defaults to gnu11 mode. Many C99 and C11 features are
2310supported in earlier modes as a conforming extension, with a warning. Use
2311``-pedantic-errors`` to request an error if a feature from a later standard
2312revision is used in an earlier mode.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002313
2314Differences between all ``c*`` and ``gnu*`` modes:
2315
2316- ``c*`` modes define "``__STRICT_ANSI__``".
2317- Target-specific defines not prefixed by underscores, like "linux",
2318 are defined in ``gnu*`` modes.
2319- Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
2320 the -trigraphs option.
2321- The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
2322 the variants "``__asm__``" and "``__typeof__``" are recognized in all
2323 modes.
2324- The Apple "blocks" extension is recognized by default in ``gnu*`` modes
2325 on some platforms; it can be enabled in any mode with the "-fblocks"
2326 option.
2327- Arrays that are VLA's according to the standard, but which can be
2328 constant folded by the frontend are treated as fixed size arrays.
2329 This occurs for things like "int X[(1, 2)];", which is technically a
2330 VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
2331
2332Differences between ``*89`` and ``*99`` modes:
2333
2334- The ``*99`` modes default to implementing "inline" as specified in C99,
2335 while the ``*89`` modes implement the GNU version. This can be
2336 overridden for individual functions with the ``__gnu_inline__``
2337 attribute.
2338- Digraphs are not recognized in c89 mode.
2339- The scope of names defined inside a "for", "if", "switch", "while",
2340 or "do" statement is different. (example: "``if ((struct x {int
2341 x;}*)0) {}``".)
2342- ``__STDC_VERSION__`` is not defined in ``*89`` modes.
2343- "inline" is not recognized as a keyword in c89 mode.
2344- "restrict" is not recognized as a keyword in ``*89`` modes.
2345- Commas are allowed in integer constant expressions in ``*99`` modes.
2346- Arrays which are not lvalues are not implicitly promoted to pointers
2347 in ``*89`` modes.
2348- Some warnings are different.
2349
Richard Smithab506ad2014-10-20 23:26:58 +00002350Differences between ``*99`` and ``*11`` modes:
2351
2352- Warnings for use of C11 features are disabled.
2353- ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
2354
Aaron Ballman567d9a32018-03-12 13:09:13 +00002355Differences between ``*11`` and ``*17`` modes:
2356
2357- ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002358
2359GCC extensions not implemented yet
2360----------------------------------
2361
2362clang tries to be compatible with gcc as much as possible, but some gcc
2363extensions are not implemented yet:
2364
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002365- clang does not support decimal floating point types (``_Decimal32`` and
2366 friends) or fixed-point types (``_Fract`` and friends); nobody has
2367 expressed interest in these features yet, so it's hard to say when
2368 they will be implemented.
2369- clang does not support nested functions; this is a complex feature
2370 which is infrequently used, so it is unlikely to be implemented
2371 anytime soon. In C++11 it can be emulated by assigning lambda
2372 functions to local variables, e.g:
2373
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002374 .. code-block:: cpp
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002375
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002376 auto const local_function = [&](int parameter) {
2377 // Do something
2378 };
2379 ...
2380 local_function(1);
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002381
Michael Kuperstein94b25ec2016-12-12 19:11:39 +00002382- clang only supports global register variables when the register specified
2383 is non-allocatable (e.g. the stack pointer). Support for general global
2384 register variables is unlikely to be implemented soon because it requires
2385 additional LLVM backend support.
Andrey Bokhanko5dfd5b62016-02-11 13:27:02 +00002386- clang does not support static initialization of flexible array
2387 members. This appears to be a rarely used extension, but could be
2388 implemented pending user demand.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002389- clang does not support
2390 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
2391 used rarely, but in some potentially interesting places, like the
2392 glibc headers, so it may be implemented pending user demand. Note
2393 that because clang pretends to be like GCC 4.2, and this extension
2394 was introduced in 4.3, the glibc headers will not try to use this
2395 extension with clang at the moment.
2396- clang does not support the gcc extension for forward-declaring
2397 function parameters; this has not shown up in any real-world code
2398 yet, though, so it might never be implemented.
2399
2400This is not a complete list; if you find an unsupported extension
2401missing from this list, please send an e-mail to cfe-dev. This list
2402currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
2403list does not include bugs in mostly-implemented features; please see
2404the `bug
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00002405tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002406for known existing bugs (FIXME: Is there a section for bug-reporting
2407guidelines somewhere?).
2408
2409Intentionally unsupported GCC extensions
2410----------------------------------------
2411
2412- clang does not support the gcc extension that allows variable-length
2413 arrays in structures. This is for a few reasons: one, it is tricky to
2414 implement, two, the extension is completely undocumented, and three,
2415 the extension appears to be rarely used. Note that clang *does*
2416 support flexible array members (arrays with a zero or unspecified
2417 size at the end of a structure).
2418- clang does not have an equivalent to gcc's "fold"; this means that
2419 clang doesn't accept some constructs gcc might accept in contexts
2420 where a constant expression is required, like "x-x" where x is a
2421 variable.
2422- clang does not support ``__builtin_apply`` and friends; this extension
2423 is extremely obscure and difficult to implement reliably.
2424
2425.. _c_ms:
2426
2427Microsoft extensions
2428--------------------
2429
Reid Kleckner2a5d34b2016-03-28 20:42:41 +00002430clang has support for many extensions from Microsoft Visual C++. To enable these
2431extensions, use the ``-fms-extensions`` command-line option. This is the default
2432for Windows targets. Clang does not implement every pragma or declspec provided
2433by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
2434comment(lib)`` are well supported.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002435
Richard Smith48d1b652013-12-12 02:42:17 +00002436clang has a ``-fms-compatibility`` flag that makes clang accept enough
Reid Kleckner993e72a2013-09-20 17:04:25 +00002437invalid C++ to be able to parse most Microsoft headers. For example, it
2438allows `unqualified lookup of dependent base class members
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +00002439<https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
Reid Klecknereb248d72013-09-20 17:54:39 +00002440a common compatibility issue with clang. This flag is enabled by default
Reid Kleckner993e72a2013-09-20 17:04:25 +00002441for Windows targets.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002442
Richard Smith48d1b652013-12-12 02:42:17 +00002443``-fdelayed-template-parsing`` lets clang delay parsing of function template
2444definitions until the end of a translation unit. This flag is enabled by
2445default for Windows targets.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002446
Reid Kleckner2a5d34b2016-03-28 20:42:41 +00002447For compatibility with existing code that compiles with MSVC, clang defines the
2448``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
2449and 180000000 respectively, making clang look like an early release of Visual
2450C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It
2451accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
2452compatibility version makes clang behave more like that version of MSVC. For
2453example, ``-fms-compatibility-version=19`` will enable C++14 features and define
2454``char16_t`` and ``char32_t`` as builtin types.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002455
2456.. _cxx:
2457
2458C++ Language Features
2459=====================
2460
2461clang fully implements all of standard C++98 except for exported
Richard Smith48d1b652013-12-12 02:42:17 +00002462templates (which were removed in C++11), and all of standard C++11
2463and the current draft standard for C++1y.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002464
2465Controlling implementation limits
2466---------------------------------
2467
Richard Smithb3a14522013-02-22 01:59:51 +00002468.. option:: -fbracket-depth=N
2469
2470 Sets the limit for nested parentheses, brackets, and braces to N. The
2471 default is 256.
2472
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002473.. option:: -fconstexpr-depth=N
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002474
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002475 Sets the limit for recursive constexpr function invocations to N. The
2476 default is 512.
2477
Richard Smith869038e2018-07-11 00:34:54 +00002478.. option:: -fconstexpr-steps=N
2479
2480 Sets the limit for the number of full-expressions evaluated in a single
2481 constant expression evaluation. The default is 1048576.
2482
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002483.. option:: -ftemplate-depth=N
2484
2485 Sets the limit for recursively nested template instantiations to N. The
Richard Smith869038e2018-07-11 00:34:54 +00002486 default is 1024.
Richard Smith79c927b2013-11-06 19:31:51 +00002487
2488.. option:: -foperator-arrow-depth=N
2489
2490 Sets the limit for iterative calls to 'operator->' functions to N. The
2491 default is 256.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002492
2493.. _objc:
2494
2495Objective-C Language Features
2496=============================
2497
2498.. _objcxx:
2499
2500Objective-C++ Language Features
2501===============================
2502
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002503.. _openmp:
2504
2505OpenMP Features
2506===============
2507
Alexey Bataevcdbe44c2018-07-30 14:44:29 +00002508Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport`
2509for additional details.
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002510
Aaron Ballman51fb0312016-07-15 13:13:45 +00002511Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
2512`-fno-openmp`.
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002513
Alexey Bataevfa4814d2017-12-29 18:27:00 +00002514Use `-fopenmp-simd` to enable OpenMP simd features only, without linking
2515the runtime library; for combined constructs
2516(e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses
2517will be ignored. This can be disabled with `-fno-openmp-simd`.
2518
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002519Controlling implementation limits
2520---------------------------------
2521
2522.. option:: -fopenmp-use-tls
2523
2524 Controls code generation for OpenMP threadprivate variables. In presence of
2525 this option all threadprivate variables are generated the same way as thread
Aaron Ballman51fb0312016-07-15 13:13:45 +00002526 local variables, using TLS support. If `-fno-openmp-use-tls`
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002527 is provided or target does not support TLS, code generation for threadprivate
2528 variables relies on OpenMP runtime library.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002529
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002530.. _opencl:
2531
2532OpenCL Features
2533===============
2534
2535Clang can be used to compile OpenCL kernels for execution on a device
2536(e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMD or
2537Nvidia targets) that can be uploaded to run directly on a device (e.g. using
2538`clCreateProgramWithBinary
2539<https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
2540into generic bitcode files loadable into other toolchains.
2541
2542Compiling to a binary using the default target from the installation can be done
2543as follows:
2544
2545 .. code-block:: console
2546
2547 $ echo "kernel void k(){}" > test.cl
2548 $ clang test.cl
2549
2550Compiling for a specific target can be done by specifying the triple corresponding
2551to the target, for example:
2552
2553 .. code-block:: console
2554
2555 $ clang -target nvptx64-unknown-unknown test.cl
Tony Tye1a3f3a22018-03-23 18:43:15 +00002556 $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002557
2558Compiling to bitcode can be done as follows:
2559
2560 .. code-block:: console
2561
2562 $ clang -c -emit-llvm test.cl
2563
2564This will produce a generic test.bc file that can be used in vendor toolchains
2565to perform machine code generation.
2566
Anastasia Stulova976022e2019-08-23 11:43:49 +00002567Clang currently supports OpenCL C language standards up to v2.0. Starting from
2568clang 9 a C++ mode is available for OpenCL (see :ref:`C++ for OpenCL <opencl_cpp>`).
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002569
2570OpenCL Specific Options
2571-----------------------
2572
2573Most of the OpenCL build options from `the specification v2.0 section 5.8.4
2574<https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
2575
2576Examples:
2577
2578 .. code-block:: console
2579
2580 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
2581
2582Some extra options are available to support special OpenCL features.
2583
2584.. option:: -finclude-default-header
2585
2586Loads standard includes during compilations. By default OpenCL headers are not
2587loaded and therefore standard library includes are not available. To load them
2588automatically a flag has been added to the frontend (see also :ref:`the section
2589on the OpenCL Header <opencl_header>`):
2590
2591 .. code-block:: console
2592
2593 $ clang -Xclang -finclude-default-header test.cl
2594
2595Alternatively ``-include`` or ``-I`` followed by the path to the header location
2596can be given manually.
2597
2598 .. code-block:: console
2599
2600 $ clang -I<path to clang>/lib/Headers/opencl-c.h test.cl
2601
2602In this case the kernel code should contain ``#include <opencl-c.h>`` just as a
2603regular C include.
2604
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002605.. _opencl_cl_ext:
2606
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002607.. option:: -cl-ext
2608
2609Disables support of OpenCL extensions. All OpenCL targets provide a list
2610of extensions that they support. Clang allows to amend this using the ``-cl-ext``
2611flag with a comma-separated list of extensions prefixed with ``'+'`` or ``'-'``.
2612The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where extensions
2613can be either one of `the OpenCL specification extensions
2614<https://www.khronos.org/registry/cl/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
2615or any known vendor extension. Alternatively, ``'all'`` can be used to enable
2616or disable all known extensions.
2617Example disabling double support for the 64-bit SPIR target:
2618
2619 .. code-block:: console
2620
2621 $ clang -cc1 -triple spir64-unknown-unknown -cl-ext=-cl_khr_fp64 test.cl
2622
2623Enabling all extensions except double support in R600 AMD GPU can be done using:
2624
2625 .. code-block:: console
2626
2627 $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl
2628
2629.. _opencl_fake_address_space_map:
2630
2631.. option:: -ffake-address-space-map
2632
2633Overrides the target address space map with a fake map.
2634This allows adding explicit address space IDs to the bitcode for non-segmented
2635memory architectures that don't have separate IDs for each of the OpenCL
2636logical address spaces by default. Passing ``-ffake-address-space-map`` will
2637add/override address spaces of the target compiled for with the following values:
2638``1-global``, ``2-constant``, ``3-local``, ``4-generic``. The private address
2639space is represented by the absence of an address space attribute in the IR (see
2640also :ref:`the section on the address space attribute <opencl_addrsp>`).
2641
2642 .. code-block:: console
2643
2644 $ clang -ffake-address-space-map test.cl
2645
2646Some other flags used for the compilation for C can also be passed while
2647compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
2648
2649OpenCL Targets
2650--------------
2651
2652OpenCL targets are derived from the regular Clang target classes. The OpenCL
2653specific parts of the target representation provide address space mapping as
2654well as a set of supported extensions.
2655
2656Specific Targets
2657^^^^^^^^^^^^^^^^
2658
2659There is a set of concrete HW architectures that OpenCL can be compiled for.
2660
2661- For AMD target:
2662
2663 .. code-block:: console
2664
Tony Tye1a3f3a22018-03-23 18:43:15 +00002665 $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002666
2667- For Nvidia architectures:
2668
2669 .. code-block:: console
2670
2671 $ clang -target nvptx64-unknown-unknown test.cl
2672
2673
2674Generic Targets
2675^^^^^^^^^^^^^^^
2676
2677- SPIR is available as a generic target to allow portable bitcode to be produced
2678 that can be used across GPU toolchains. The implementation follows `the SPIR
2679 specification <https://www.khronos.org/spir>`_. There are two flavors
2680 available for 32 and 64 bits.
2681
2682 .. code-block:: console
2683
2684 $ clang -target spir-unknown-unknown test.cl
2685 $ clang -target spir64-unknown-unknown test.cl
2686
2687 All known OpenCL extensions are supported in the SPIR targets. Clang will
2688 generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and SPIR v2.0
2689 for OpenCL v2.0.
2690
2691- x86 is used by some implementations that are x86 compatible and currently
2692 remains for backwards compatibility (with older implementations prior to
2693 SPIR target support). For "non-SPMD" targets which cannot spawn multiple
2694 work-items on the fly using hardware, which covers practically all non-GPU
2695 devices such as CPUs and DSPs, additional processing is needed for the kernels
2696 to support multiple work-item execution. For this, a 3rd party toolchain,
2697 such as for example `POCL <http://portablecl.org/>`_, can be used.
2698
2699 This target does not support multiple memory segments and, therefore, the fake
2700 address space map can be added using the :ref:`-ffake-address-space-map
2701 <opencl_fake_address_space_map>` flag.
2702
2703.. _opencl_header:
2704
2705OpenCL Header
2706-------------
2707
2708By default Clang will not include standard headers and therefore OpenCL builtin
2709functions and some types (i.e. vectors) are unknown. The default CL header is,
2710however, provided in the Clang installation and can be enabled by passing the
2711``-finclude-default-header`` flag to the Clang frontend.
2712
2713 .. code-block:: console
2714
2715 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
2716 $ clang -Xclang -finclude-default-header -cl-std=CL2.0 test.cl
2717
2718Because the header is very large and long to parse, PCH (:doc:`PCHInternals`)
2719and modules (:doc:`Modules`) are used internally to improve the compilation
2720speed.
2721
2722To enable modules for OpenCL:
2723
2724 .. code-block:: console
2725
2726 $ 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
2727
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002728OpenCL Extensions
2729-----------------
2730
2731All of the ``cl_khr_*`` extensions from `the official OpenCL specification
2732<https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
2733up to and including version 2.0 are available and set per target depending on the
2734support available in the specific architecture.
2735
2736It is possible to alter the default extensions setting per target using
2737``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
2738
2739Vendor extensions can be added flexibly by declaring the list of types and
2740functions associated with each extensions enclosed within the following
2741compiler pragma directives:
2742
2743 .. code-block:: c
2744
2745 #pragma OPENCL EXTENSION the_new_extension_name : begin
2746 // declare types and functions associated with the extension here
2747 #pragma OPENCL EXTENSION the_new_extension_name : end
2748
2749For example, parsing the following code adds ``my_t`` type and ``my_func``
2750function to the custom ``my_ext`` extension.
2751
2752 .. code-block:: c
2753
2754 #pragma OPENCL EXTENSION my_ext : begin
2755 typedef struct{
2756 int a;
2757 }my_t;
2758 void my_func(my_t);
2759 #pragma OPENCL EXTENSION my_ext : end
2760
2761Declaring the same types in different vendor extensions is disallowed.
2762
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002763OpenCL Metadata
2764---------------
2765
2766Clang uses metadata to provide additional OpenCL semantics in IR needed for
2767backends and OpenCL runtime.
2768
2769Each kernel will have function metadata attached to it, specifying the arguments.
2770Kernel argument metadata is used to provide source level information for querying
2771at runtime, for example using the `clGetKernelArgInfo
2772<https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf#167>`_
2773call.
2774
2775Note that ``-cl-kernel-arg-info`` enables more information about the original CL
2776code to be added e.g. kernel parameter names will appear in the OpenCL metadata
2777along with other information.
2778
2779The IDs used to encode the OpenCL's logical address spaces in the argument info
2780metadata follows the SPIR address space mapping as defined in the SPIR
2781specification `section 2.2
2782<https://www.khronos.org/registry/spir/specs/spir_spec-2.0.pdf#18>`_
2783
2784OpenCL-Specific Attributes
2785--------------------------
2786
2787OpenCL support in Clang contains a set of attribute taken directly from the
2788specification as well as additional attributes.
2789
2790See also :doc:`AttributeReference`.
2791
2792nosvm
2793^^^^^
2794
2795Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
2796does not have any effect on the IR. For more details reffer to the specification
2797`section 6.7.2
2798<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
2799
2800
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002801opencl_unroll_hint
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002802^^^^^^^^^^^^^^^^^^
2803
2804The implementation of this feature mirrors the unroll hint for C.
2805More details on the syntax can be found in the specification
2806`section 6.11.5
2807<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
2808
2809convergent
2810^^^^^^^^^^
2811
2812To make sure no invalid optimizations occur for single program multiple data
2813(SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
2814can be used for special functions that have cross work item semantics.
2815An example is the subgroup operations such as `intel_sub_group_shuffle
2816<https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
2817
2818 .. code-block:: c
2819
2820 // Define custom my_sub_group_shuffle(data, c)
2821 // that makes use of intel_sub_group_shuffle
Aaron Ballman37ff16f2017-01-16 13:42:21 +00002822 r1 = ...
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002823 if (r0) r1 = computeA();
2824 // Shuffle data from r1 into r3
2825 // of threads id r2.
2826 r3 = my_sub_group_shuffle(r1, r2);
2827 if (r0) r3 = computeB();
2828
2829with non-SPMD semantics this is optimized to the following equivalent code:
2830
2831 .. code-block:: c
2832
Aaron Ballman37ff16f2017-01-16 13:42:21 +00002833 r1 = ...
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002834 if (!r0)
2835 // Incorrect functionality! The data in r1
2836 // have not been computed by all threads yet.
2837 r3 = my_sub_group_shuffle(r1, r2);
2838 else {
2839 r1 = computeA();
2840 r3 = my_sub_group_shuffle(r1, r2);
2841 r3 = computeB();
2842 }
2843
2844Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
2845would prevent this:
2846
2847 .. code-block:: c
2848
2849 my_sub_group_shuffle() __attribute__((convergent));
2850
2851Using ``convergent`` guarantees correct execution by keeping CFG equivalence
2852wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
2853node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
2854respect to ``Ni`` remain the same in both ``G`` and ``G´``.
2855
2856noduplicate
2857^^^^^^^^^^^
2858
2859``noduplicate`` is more restrictive with respect to optimizations than
2860``convergent`` because a convergent function only preserves CFG equivalence.
2861This allows some optimizations to happen as long as the control flow remains
2862unmodified.
2863
2864 .. code-block:: c
2865
2866 for (int i=0; i<4; i++)
2867 my_sub_group_shuffle()
2868
2869can be modified to:
2870
2871 .. code-block:: c
2872
2873 my_sub_group_shuffle();
2874 my_sub_group_shuffle();
2875 my_sub_group_shuffle();
2876 my_sub_group_shuffle();
2877
2878while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
2879have the same safe semantics of CFG as ``convergent`` and can cause changes in
2880CFG that modify semantics of the original program.
2881
2882``noduplicate`` is kept for backwards compatibility only and it considered to be
2883deprecated for future uses.
2884
2885.. _opencl_addrsp:
2886
2887address_space
2888^^^^^^^^^^^^^
2889
2890Clang has arbitrary address space support using the ``address_space(N)``
2891attribute, where ``N`` is an integer number in the range ``0`` to ``16777215``
2892(``0xffffffu``).
2893
2894An OpenCL implementation provides a list of standard address spaces using
2895keywords: ``private``, ``local``, ``global``, and ``generic``. In the AST and
2896in the IR local, global, or generic will be represented by the address space
2897attribute with the corresponding unique number. Note that private does not have
2898any corresponding attribute added and, therefore, is represented by the absence
2899of an address space number. The specific IDs for an address space do not have to
2900match between the AST and the IR. Typically in the AST address space numbers
2901represent logical segments while in the IR they represent physical segments.
2902Therefore, machines with flat memory segments can map all AST address space
2903numbers to the same physical segment ID or skip address space attribute
2904completely while generating the IR. However, if the address space information
2905is needed by the IR passes e.g. to improve alias analysis, it is recommended
2906to keep it and only lower to reflect physical memory segments in the late
2907machine passes.
2908
2909OpenCL builtins
2910---------------
2911
2912There are some standard OpenCL functions that are implemented as Clang builtins:
2913
2914- All pipe functions from `section 6.13.16.2/6.13.16.3
2915 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#160>`_ of
2916 the OpenCL v2.0 kernel language specification. `
2917
2918- Address space qualifier conversion functions ``to_global``/``to_local``/``to_private``
2919 from `section 6.13.9
2920 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#101>`_.
2921
2922- All the ``enqueue_kernel`` functions from `section 6.13.17.1
2923 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#164>`_ and
2924 enqueue query functions from `section 6.13.17.5
2925 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#171>`_.
2926
Anastasia Stulova79f4e472019-07-17 17:21:31 +00002927.. _opencl_cpp:
2928
2929C++ for OpenCL
2930--------------
2931
Anastasia Stulova976022e2019-08-23 11:43:49 +00002932Starting from clang 9 kernel code can contain C++17 features: classes, templates,
Anastasia Stulova79f4e472019-07-17 17:21:31 +00002933function overloading, type deduction, etc. Please note that this is not an
2934implementation of `OpenCL C++
2935<https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and
2936there is no plan to support it in clang in any new releases in the near future.
2937
Anastasia Stulova976022e2019-08-23 11:43:49 +00002938For detailed information about restrictions to allowed C++ features please
2939refer to :doc:`LanguageExtensions`.
Anastasia Stulova79f4e472019-07-17 17:21:31 +00002940
2941Since C++ features are to be used on top of OpenCL C functionality, all existing
2942restrictions from OpenCL C v2.0 will inherently apply. All OpenCL C builtin types
Anastasia Stulova976022e2019-08-23 11:43:49 +00002943and function libraries are supported and can be used in this mode.
Anastasia Stulova79f4e472019-07-17 17:21:31 +00002944
Anastasia Stulova976022e2019-08-23 11:43:49 +00002945To enable the C++ for OpenCL mode, pass one of following command line options when
2946compiling ``.cl`` file ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-std=clc++`` or
2947``-std=CLC++``.
Anastasia Stulova79f4e472019-07-17 17:21:31 +00002948
2949 .. code-block:: c++
2950
2951 template<class T> T add( T x, T y )
2952 {
2953 return x + y;
2954 }
2955
2956 __kernel void test( __global float* a, __global float* b)
2957 {
2958 auto index = get_global_id(0);
2959 a[index] = add(b[index], b[index+1]);
2960 }
2961
2962
2963 .. code-block:: console
2964
Anastasia Stulova88ed70e2019-07-25 11:04:29 +00002965 clang -cl-std=clc++ test.cl
Anastasia Stulova79f4e472019-07-17 17:21:31 +00002966
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002967.. _target_features:
2968
2969Target-Specific Features and Limitations
2970========================================
2971
2972CPU Architectures Features and Limitations
2973------------------------------------------
2974
2975X86
2976^^^
2977
2978The support for X86 (both 32-bit and 64-bit) is considered stable on
J. Ryan Stinnettd45eaf92019-05-30 16:46:22 +00002979Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002980to correctly compile many large C, C++, Objective-C, and Objective-C++
2981codebases.
2982
Richard Smith48d1b652013-12-12 02:42:17 +00002983On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
David Woodhouseddf89852014-01-23 14:32:46 +00002984Microsoft x64 calling convention. You might need to tweak
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002985``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
2986
Aaron Ballman51fb0312016-07-15 13:13:45 +00002987For the X86 target, clang supports the `-m16` command line
David Woodhouseddf89852014-01-23 14:32:46 +00002988argument which enables 16-bit code output. This is broadly similar to
2989using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
2990and the ABI remains 32-bit but the assembler emits instructions
2991appropriate for a CPU running in 16-bit mode, with address-size and
2992operand-size prefixes to enable 32-bit addressing and operations.
2993
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002994ARM
2995^^^
2996
2997The support for ARM (specifically ARMv6 and ARMv7) is considered stable
2998on Darwin (iOS): it has been tested to correctly compile many large C,
2999C++, Objective-C, and Objective-C++ codebases. Clang only supports a
3000limited number of ARM architectures. It does not yet fully support
3001ARMv5, for example.
3002
Roman Divacky786d32e2013-09-11 17:12:49 +00003003PowerPC
3004^^^^^^^
3005
3006The support for PowerPC (especially PowerPC64) is considered stable
3007on Linux and FreeBSD: it has been tested to correctly compile many
3008large C and C++ codebases. PowerPC (32bit) is still missing certain
3009features (e.g. PIC code on ELF platforms).
3010
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003011Other platforms
3012^^^^^^^^^^^^^^^
3013
Roman Divacky786d32e2013-09-11 17:12:49 +00003014clang currently contains some support for other architectures (e.g. Sparc);
3015however, significant pieces of code generation are still missing, and they
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003016haven't undergone significant testing.
3017
3018clang contains limited support for the MSP430 embedded processor, but
3019both the clang support and the LLVM backend support are highly
3020experimental.
3021
3022Other platforms are completely unsupported at the moment. Adding the
3023minimal support needed for parsing and semantic analysis on a new
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00003024platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003025tree. This level of support is also sufficient for conversion to LLVM IR
3026for simple programs. Proper support for conversion to LLVM IR requires
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00003027adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003028change soon, though. Generating assembly requires a suitable LLVM
3029backend.
3030
3031Operating System Features and Limitations
3032-----------------------------------------
3033
J. Ryan Stinnettd45eaf92019-05-30 16:46:22 +00003034Darwin (macOS)
3035^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003036
Nico Weberc7cb9402014-03-07 18:11:40 +00003037Thread Sanitizer is not supported.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003038
3039Windows
3040^^^^^^^
3041
Richard Smith48d1b652013-12-12 02:42:17 +00003042Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
3043platforms.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003044
Reid Kleckner725b7b32013-09-05 21:29:35 +00003045See also :ref:`Microsoft Extensions <c_ms>`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003046
3047Cygwin
3048""""""
3049
3050Clang works on Cygwin-1.7.
3051
3052MinGW32
3053"""""""
3054
3055Clang works on some mingw32 distributions. Clang assumes directories as
3056below;
3057
3058- ``C:/mingw/include``
3059- ``C:/mingw/lib``
3060- ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
3061
3062On MSYS, a few tests might fail.
3063
3064MinGW-w64
3065"""""""""
3066
3067For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
3068assumes as below;
3069
3070- ``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)``
3071- ``some_directory/bin/gcc.exe``
3072- ``some_directory/bin/clang.exe``
3073- ``some_directory/bin/clang++.exe``
3074- ``some_directory/bin/../include/c++/GCC_version``
3075- ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
3076- ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
3077- ``some_directory/bin/../include/c++/GCC_version/backward``
3078- ``some_directory/bin/../x86_64-w64-mingw32/include``
3079- ``some_directory/bin/../i686-w64-mingw32/include``
3080- ``some_directory/bin/../include``
3081
3082This directory layout is standard for any toolchain you will find on the
3083official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
3084
3085Clang expects the GCC executable "gcc.exe" compiled for
3086``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
3087
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00003088`Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
Sean Silvabf9b4cd2012-12-13 01:10:46 +00003089``x86_64-w64-mingw32``.
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003090
3091.. _clang-cl:
3092
3093clang-cl
3094========
3095
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003096clang-cl is an alternative command-line interface to Clang, designed for
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003097compatibility with the Visual C++ compiler, cl.exe.
3098
3099To enable clang-cl to find system headers, libraries, and the linker when run
3100from the command-line, it should be executed inside a Visual Studio Native Tools
3101Command Prompt or a regular Command Prompt where the environment has been set
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +00003102up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003103
Hans Wennborg69d6d7a2018-03-01 14:00:19 +00003104clang-cl can also be used from inside Visual Studio by selecting the LLVM
Stephen Kelly8a89bb62018-08-22 01:11:18 +00003105Platform Toolset. The toolset is not part of the installer, but may be installed
3106separately from the
3107`Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_.
3108To use the toolset, select a project in Solution Explorer, open its Property
3109Page (Alt+F7), and in the "General" section of "Configuration Properties"
3110change "Platform Toolset" to LLVM. Doing so enables an additional Property
3111Page for selecting the clang-cl executable to use for builds.
Hans Wennborg69d6d7a2018-03-01 14:00:19 +00003112
3113To use the toolset with MSBuild directly, invoke it with e.g.
Stephen Kelly8a89bb62018-08-22 01:11:18 +00003114``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain
3115without modifying your project files.
Hans Wennborg69d6d7a2018-03-01 14:00:19 +00003116
Hans Wennborg1bab7012018-03-01 14:48:19 +00003117It's also possible to point MSBuild at clang-cl without changing toolset by
3118passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.
3119
3120When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:
3121
3122 ::
3123
Stephen Kelly8a89bb62018-08-22 01:11:18 +00003124 cmake -G"Visual Studio 15 2017" -T LLVM ..
Hans Wennborg1bab7012018-03-01 14:48:19 +00003125
3126When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and
3127``CMAKE_CXX_COMPILER`` variables to clang-cl:
3128
3129 ::
3130
3131 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"
3132 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..
3133
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003134
3135Command-Line Options
3136--------------------
3137
3138To be compatible with cl.exe, clang-cl supports most of the same command-line
3139options. Those options can start with either ``/`` or ``-``. It also supports
3140some of Clang's core options, such as the ``-W`` options.
3141
3142Options that are known to clang-cl, but not currently supported, are ignored
3143with a warning. For example:
3144
3145 ::
3146
Hans Wennborg0d080622015-08-12 19:35:01 +00003147 clang-cl.exe: warning: argument unused during compilation: '/AI'
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003148
3149To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
3150
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003151Options that are not known to clang-cl will be ignored by default. Use the
3152``-Werror=unknown-argument`` option in order to treat them as errors. If these
3153options are spelled with a leading ``/``, they will be mistaken for a filename:
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003154
3155 ::
3156
3157 clang-cl.exe: error: no such file or directory: '/foobar'
3158
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00003159Please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=clang&component=Driver>`_
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003160for any valid cl.exe flags that clang-cl does not understand.
3161
3162Execute ``clang-cl /?`` to see a list of supported options:
3163
3164 ::
3165
Hans Wennborg35487d82014-08-04 21:07:58 +00003166 CL.EXE COMPATIBILITY OPTIONS:
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003167 /? Display available options
3168 /arch:<value> Set architecture for code generation
3169 /Brepro- Emit an object file which cannot be reproduced over time
3170 /Brepro Emit an object file which can be reproduced over time
Hans Wennborg797004d2018-11-08 11:27:04 +00003171 /clang:<arg> Pass <arg> to the clang driver
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003172 /C Don't discard comments when preprocessing
3173 /c Compile only
Hans Wennborgaade1202018-08-01 12:58:57 +00003174 /d1PP Retain macro definitions in /E mode
Hans Wennborg7f36a952017-07-19 09:52:24 +00003175 /d1reportAllClassLayout Dump record layout information
3176 /diagnostics:caret Enable caret and column diagnostics (on by default)
3177 /diagnostics:classic Disable column and caret diagnostics
3178 /diagnostics:column Disable caret diagnostics but keep column info
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003179 /D <macro[=value]> Define macro
3180 /EH<value> Exception handling model
3181 /EP Disable linemarker output and preprocess to stdout
3182 /execution-charset:<value>
3183 Runtime encoding, supports only UTF-8
3184 /E Preprocess to stdout
3185 /fallback Fall back to cl.exe if clang-cl fails to compile
3186 /FA Output assembly code file during compilation
3187 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
3188 /Fe<file or directory> Set output executable file or directory (ends in / or \)
3189 /FI <value> Include file before parsing
3190 /Fi<file> Set preprocess output file name (with /P)
3191 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
Hans Wennborg0d080622015-08-12 19:35:01 +00003192 /fp:except-
3193 /fp:except
3194 /fp:fast
3195 /fp:precise
3196 /fp:strict
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003197 /Fp<filename> Set pch filename (with /Yc and /Yu)
3198 /GA Assume thread-local variables are defined in the executable
3199 /Gd Set __cdecl as a default calling convention
3200 /GF- Disable string pooling
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003201 /GF Enable string pooling (default)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003202 /GR- Disable emission of RTTI data
Hans Wennborgcb766532018-01-03 13:20:25 +00003203 /Gregcall Set __regcall as a default calling convention
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003204 /GR Enable emission of RTTI data
3205 /Gr Set __fastcall as a default calling convention
3206 /GS- Disable buffer security check
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003207 /GS Enable buffer security check (default)
3208 /Gs Use stack probes (default)
3209 /Gs<value> Set stack probe size (default 4096)
3210 /guard:<value> Enable Control Flow Guard with /guard:cf,
3211 or only the table with /guard:cf,nochecks
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003212 /Gv Set __vectorcall as a default calling convention
3213 /Gw- Don't put each data item in its own section
3214 /Gw Put each data item in its own section
Hans Wennborg729eb0b2018-04-03 09:28:21 +00003215 /GX- Disable exception handling
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003216 /GX Enable exception handling
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003217 /Gy- Don't put each function in its own section (default)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003218 /Gy Put each function in its own section
3219 /Gz Set __stdcall as a default calling convention
3220 /help Display available options
3221 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
3222 /I <dir> Add directory to include search path
3223 /J Make char type unsigned
3224 /LDd Create debug DLL
3225 /LD Create DLL
3226 /link <options> Forward options to the linker
3227 /MDd Use DLL debug run-time
3228 /MD Use DLL run-time
3229 /MTd Use static debug run-time
3230 /MT Use static run-time
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003231 /O0 Disable optimization
3232 /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy)
3233 /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy)
3234 /Ob0 Disable function inlining
3235 /Ob1 Only inline functions which are (explicitly or implicitly) marked inline
3236 /Ob2 Inline functions as deemed beneficial by the compiler
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003237 /Od Disable optimization
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003238 /Og No effect
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003239 /Oi- Disable use of builtin functions
3240 /Oi Enable use of builtin functions
3241 /Os Optimize for size
3242 /Ot Optimize for speed
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003243 /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead
3244 /Oy- Disable frame pointer omission (x86 only, default)
3245 /Oy Enable frame pointer omission (x86 only)
3246 /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-'
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003247 /o <file or directory> Set output file or directory (ends in / or \)
3248 /P Preprocess to file
3249 /Qvec- Disable the loop vectorization passes
3250 /Qvec Enable the loop vectorization passes
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003251 /showFilenames- Don't print the name of each compiled file (default)
3252 /showFilenames Print the name of each compiled file
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003253 /showIncludes Print info about included files to stderr
3254 /source-charset:<value> Source encoding, supports only UTF-8
3255 /std:<value> Language standard to compile for
3256 /TC Treat all source files as C
3257 /Tc <filename> Specify a C source file
3258 /TP Treat all source files as C++
3259 /Tp <filename> Specify a C++ source file
Hans Wennborg9d1ed002017-01-12 19:26:54 +00003260 /utf-8 Set source and runtime encoding to UTF-8 (default)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003261 /U <macro> Undefine macro
3262 /vd<value> Control vtordisp placement
3263 /vmb Use a best-case representation method for member pointers
3264 /vmg Use a most-general representation for member pointers
3265 /vmm Set the default most-general representation to multiple inheritance
3266 /vms Set the default most-general representation to single inheritance
3267 /vmv Set the default most-general representation to virtual inheritance
3268 /volatile:iso Volatile loads and stores have standard semantics
3269 /volatile:ms Volatile loads and stores have acquire and release semantics
3270 /W0 Disable all warnings
3271 /W1 Enable -Wall
3272 /W2 Enable -Wall
3273 /W3 Enable -Wall
3274 /W4 Enable -Wall and -Wextra
Hans Wennborgcb766532018-01-03 13:20:25 +00003275 /Wall Enable -Weverything
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003276 /WX- Do not treat warnings as errors
3277 /WX Treat warnings as errors
3278 /w Disable all warnings
Hans Wennborgaade1202018-08-01 12:58:57 +00003279 /X Don't add %INCLUDE% to the include search path
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003280 /Y- Disable precompiled headers, overrides /Yc and /Yu
3281 /Yc<filename> Generate a pch file for all code up to and including <filename>
3282 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
3283 /Z7 Enable CodeView debug information in object files
Saleem Abdulrasool09c26252019-05-28 18:26:00 +00003284 /Zc:char8_t Enable C++2a char8_t type
3285 /Zc:char8_t- Disable C++2a char8_t type
Hans Wennborg7717a5c2018-11-13 09:05:12 +00003286 /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes
3287 /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003288 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
3289 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
3290 /Zc:strictStrings Treat string literals as const
3291 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
3292 /Zc:threadSafeInit Enable thread-safe initialization of static variables
3293 /Zc:trigraphs- Disable trigraphs (default)
3294 /Zc:trigraphs Enable trigraphs
Hans Wennborg7f36a952017-07-19 09:52:24 +00003295 /Zc:twoPhase- Disable two-phase name lookup in templates
3296 /Zc:twoPhase Enable two-phase name lookup in templates
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003297 /Zd Emit debug line number tables only
3298 /Zi Alias for /Z7. Does not produce PDBs.
3299 /Zl Don't mention any default libraries in the object file
3300 /Zp Set the default maximum struct packing alignment to 1
3301 /Zp<value> Specify the default maximum struct packing alignment
3302 /Zs Syntax-check only
Hans Wennborg35487d82014-08-04 21:07:58 +00003303
3304 OPTIONS:
Hans Wennborg0d080622015-08-12 19:35:01 +00003305 -### Print (but do not run) the commands to run for this compilation
3306 --analyze Run the static analyzer
Hans Wennborgaade1202018-08-01 12:58:57 +00003307 -faddrsig Emit an address-significance table
Hans Wennborg0d080622015-08-12 19:35:01 +00003308 -fansi-escape-codes Use ANSI escape codes for diagnostics
Hans Wennborgaade1202018-08-01 12:58:57 +00003309 -fblocks Enable the 'blocks' language feature
3310 -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none.
3311 -fcf-protection Enable cf-protection in 'full' mode
Hans Wennborg0d080622015-08-12 19:35:01 +00003312 -fcolor-diagnostics Use colors in diagnostics
Hans Wennborgaade1202018-08-01 12:58:57 +00003313 -fcomplete-member-pointers
3314 Require member pointer base types to be complete if they would be significant under the Microsoft ABI
3315 -fcoverage-mapping Generate coverage mapping to enable code coverage analysis
Hans Wennborg7f36a952017-07-19 09:52:24 +00003316 -fdebug-macro Emit macro debug information
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003317 -fdelayed-template-parsing
3318 Parse templated function definitions at the end of the translation unit
3319 -fdiagnostics-absolute-paths
3320 Print absolute paths in diagnostics
Hans Wennborg0d080622015-08-12 19:35:01 +00003321 -fdiagnostics-parseable-fixits
3322 Print fix-its in machine parseable form
Hans Wennborg7f36a952017-07-19 09:52:24 +00003323 -flto=<value> Set LTO mode to either 'full' or 'thin'
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003324 -flto Enable LTO in 'full' mode
Hans Wennborgaade1202018-08-01 12:58:57 +00003325 -fmerge-all-constants Allow merging of constants
Hans Wennborg35487d82014-08-04 21:07:58 +00003326 -fms-compatibility-version=<value>
Hans Wennborg0d080622015-08-12 19:35:01 +00003327 Dot-separated value representing the Microsoft compiler version
3328 number to report in _MSC_VER (0 = don't define it (default))
Hans Wennborge8178e82016-02-12 01:01:37 +00003329 -fms-compatibility Enable full Microsoft Visual C++ compatibility
3330 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
3331 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
3332 (0 = don't define it (default))
Hans Wennborgaade1202018-08-01 12:58:57 +00003333 -fno-addrsig Don't emit an address-significance table
3334 -fno-builtin-<value> Disable implicit builtin knowledge of a specific function
3335 -fno-builtin Disable implicit builtin knowledge of functions
3336 -fno-complete-member-pointers
3337 Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI
3338 -fno-coverage-mapping Disable code coverage analysis
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003339 -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash
Hans Wennborg7f36a952017-07-19 09:52:24 +00003340 -fno-debug-macro Do not emit macro debug information
Hans Wennborg9d1ed002017-01-12 19:26:54 +00003341 -fno-delayed-template-parsing
3342 Disable delayed template parsing
Filipe Cabecinhas0eb50082018-11-02 17:29:04 +00003343 -fno-sanitize-address-poison-custom-array-cookie
3344 Disable poisoning array cookies when using custom operator new[] in AddressSanitizer
Hans Wennborg7f36a952017-07-19 09:52:24 +00003345 -fno-sanitize-address-use-after-scope
3346 Disable use-after-scope detection in AddressSanitizer
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003347 -fno-sanitize-address-use-odr-indicator
3348 Disable ODR indicator globals
Hans Wennborg7f36a952017-07-19 09:52:24 +00003349 -fno-sanitize-blacklist Don't use blacklist file for sanitizers
3350 -fno-sanitize-cfi-cross-dso
3351 Disable control flow integrity (CFI) checks for cross-DSO calls.
Hans Wennborg0d080622015-08-12 19:35:01 +00003352 -fno-sanitize-coverage=<value>
3353 Disable specified features of coverage instrumentation for Sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00003354 -fno-sanitize-memory-track-origins
3355 Disable origins tracking in MemorySanitizer
Hans Wennborgcb766532018-01-03 13:20:25 +00003356 -fno-sanitize-memory-use-after-dtor
3357 Disable use-after-destroy detection in MemorySanitizer
Hans Wennborg0d080622015-08-12 19:35:01 +00003358 -fno-sanitize-recover=<value>
3359 Disable recovery for specified sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00003360 -fno-sanitize-stats Disable sanitizer statistics gathering.
3361 -fno-sanitize-thread-atomics
3362 Disable atomic operations instrumentation in ThreadSanitizer
3363 -fno-sanitize-thread-func-entry-exit
3364 Disable function entry/exit instrumentation in ThreadSanitizer
3365 -fno-sanitize-thread-memory-access
3366 Disable memory access instrumentation in ThreadSanitizer
Hans Wennborg0d080622015-08-12 19:35:01 +00003367 -fno-sanitize-trap=<value>
3368 Disable trapping for specified sanitizers
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003369 -fno-standalone-debug Limit debug information produced to reduce size of debug binary
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003370 -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version
3371 -fprofile-exclude-files=<value>
3372 Instrument only functions from files where names don't match all the regexes separated by a semi-colon
3373 -fprofile-filter-files=<value>
3374 Instrument only functions from files where names match any regex separated by a semi-colon
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003375 -fprofile-instr-generate=<file>
3376 Generate instrumented code to collect execution counts into <file>
3377 (overridden by LLVM_PROFILE_FILE env var)
3378 -fprofile-instr-generate
3379 Generate instrumented code to collect execution counts into default.profraw file
Sylvestre Ledrue86ee6b2017-01-14 11:41:45 +00003380 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003381 -fprofile-instr-use=<value>
3382 Use instrumentation data for profile-guided optimization
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003383 -fprofile-remapping-file=<file>
3384 Use the remappings described in <file> to match the profile data against names in the program
Hans Wennborg7f36a952017-07-19 09:52:24 +00003385 -fsanitize-address-field-padding=<value>
3386 Level of field padding for AddressSanitizer
3387 -fsanitize-address-globals-dead-stripping
3388 Enable linker dead stripping of globals in AddressSanitizer
Filipe Cabecinhas0eb50082018-11-02 17:29:04 +00003389 -fsanitize-address-poison-custom-array-cookie
3390 Enable poisoning array cookies when using custom operator new[] in AddressSanitizer
Hans Wennborg7f36a952017-07-19 09:52:24 +00003391 -fsanitize-address-use-after-scope
3392 Enable use-after-scope detection in AddressSanitizer
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003393 -fsanitize-address-use-odr-indicator
3394 Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size
Hans Wennborg35487d82014-08-04 21:07:58 +00003395 -fsanitize-blacklist=<value>
Hans Wennborg0d080622015-08-12 19:35:01 +00003396 Path to blacklist file for sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00003397 -fsanitize-cfi-cross-dso
3398 Enable control flow integrity (CFI) checks for cross-DSO calls.
Hans Wennborgcb766532018-01-03 13:20:25 +00003399 -fsanitize-cfi-icall-generalize-pointers
3400 Generalize pointers in CFI indirect call type signature checks
Hans Wennborg0d080622015-08-12 19:35:01 +00003401 -fsanitize-coverage=<value>
3402 Specify the type of coverage instrumentation for Sanitizers
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003403 -fsanitize-hwaddress-abi=<value>
3404 Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor)
Hans Wennborg7f36a952017-07-19 09:52:24 +00003405 -fsanitize-memory-track-origins=<value>
3406 Enable origins tracking in MemorySanitizer
3407 -fsanitize-memory-track-origins
3408 Enable origins tracking in MemorySanitizer
3409 -fsanitize-memory-use-after-dtor
3410 Enable use-after-destroy detection in MemorySanitizer
Hans Wennborg0d080622015-08-12 19:35:01 +00003411 -fsanitize-recover=<value>
3412 Enable recovery for specified sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00003413 -fsanitize-stats Enable sanitizer statistics gathering.
3414 -fsanitize-thread-atomics
3415 Enable atomic operations instrumentation in ThreadSanitizer (default)
3416 -fsanitize-thread-func-entry-exit
3417 Enable function entry/exit instrumentation in ThreadSanitizer (default)
3418 -fsanitize-thread-memory-access
3419 Enable memory access instrumentation in ThreadSanitizer (default)
Hans Wennborg0d080622015-08-12 19:35:01 +00003420 -fsanitize-trap=<value> Enable trapping for specified sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00003421 -fsanitize-undefined-strip-path-components=<number>
3422 Strip (or keep only, if negative) a given number of path components when emitting check metadata.
Hans Wennborg0d080622015-08-12 19:35:01 +00003423 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
3424 behavior. See user manual for available checks
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003425 -fsplit-lto-unit Enables splitting of the LTO unit.
Hans Wennborg715dd7f2017-01-12 18:15:06 +00003426 -fstandalone-debug Emit full debug info for all types used by the program
Hans Wennborgcb766532018-01-03 13:20:25 +00003427 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003428 -gcodeview-ghash Emit type record hashes in a .debug$H section
Hans Wennborg0d080622015-08-12 19:35:01 +00003429 -gcodeview Generate CodeView debug information
Hans Wennborg5168ddf2019-01-16 09:13:47 +00003430 -gline-directives-only Emit debug line info directives only
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00003431 -gline-tables-only Emit debug line number tables only
3432 -miamcu Use Intel MCU ABI
Hans Wennborg0d080622015-08-12 19:35:01 +00003433 -mllvm <value> Additional arguments to forward to LLVM's option processing
Hans Wennborg7f36a952017-07-19 09:52:24 +00003434 -nobuiltininc Disable builtin #include directories
Hans Wennborg0d080622015-08-12 19:35:01 +00003435 -Qunused-arguments Don't emit warning for unused driver arguments
3436 -R<remark> Enable the specified remark
3437 --target=<value> Generate code for the given target
Hans Wennborgcb766532018-01-03 13:20:25 +00003438 --version Print version information
Hans Wennborg0d080622015-08-12 19:35:01 +00003439 -v Show commands to run and use verbose output
3440 -W<warning> Enable the specified warning
3441 -Xclang <arg> Pass <arg> to the clang compiler
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003442
Hans Wennborg797004d2018-11-08 11:27:04 +00003443The /clang: Option
3444^^^^^^^^^^^^^^^^^^
3445
3446When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all
3447of the ``<arg>`` arguments and process them as if they were passed to the clang
3448driver. This mechanism allows you to pass flags that are not exposed in the
3449clang-cl options or flags that have a different meaning when passed to the clang
3450driver. Regardless of where they appear in the command line, the ``/clang:``
3451arguments are treated as if they were passed at the end of the clang-cl command
3452line.
3453
Hans Wennborg96a78602018-11-12 08:38:10 +00003454The /Zc:dllexportInlines- Option
3455^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3456
Hans Wennborg7717a5c2018-11-13 09:05:12 +00003457This causes the class-level `dllexport` and `dllimport` attributes to not apply
3458to inline member functions, as they otherwise would. For example, in the code
3459below `S::foo()` would normally be defined and exported by the DLL, but when
3460using the ``/Zc:dllexportInlines-`` flag it is not:
Hans Wennborg96a78602018-11-12 08:38:10 +00003461
3462.. code-block:: c
3463
3464 struct __declspec(dllexport) S {
3465 void foo() {}
3466 }
3467
3468This has the benefit that the compiler doesn't need to emit a definition of
3469`S::foo()` in every translation unit where the declaration is included, as it
3470would otherwise do to ensure there's a definition in the DLL even if it's not
3471used there. If the declaration occurs in a header file that's widely used, this
3472can save significant compilation time and output size. It also reduces the
3473number of functions exported by the DLL similarly to what
3474``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.
3475Since the function declaration comes with an inline definition, users of the
3476library can use that definition directly instead of importing it from the DLL.
3477
3478Note that the Microsoft Visual C++ compiler does not support this option, and
3479if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the
3480DLL must be compiled in the same way so that it doesn't attempt to dllimport
3481the inline member functions. The reverse scenario should generally work though:
3482a DLL compiled without this flag (such as a system library compiled with Visual
3483C++) can be referenced from code compiled using the flag, meaning that the
3484referencing code will use the inline definitions instead of importing them from
3485the DLL.
3486
3487Also note that like when using ``-fvisibility-inlines-hidden``, the address of
3488`S::foo()` will be different inside and outside the DLL, breaking the C/C++
3489standard requirement that functions have a unique address.
3490
3491The flag does not apply to explicit class template instantiation definitions or
3492declarations, as those are typically used to explicitly provide a single
3493definition in a DLL, (dllexported instantiation definition) or to signal that
3494the definition is available elsewhere (dllimport instantiation declaration). It
3495also doesn't apply to inline members with static local variables, to ensure
3496that the same instance of the variable is used inside and outside the DLL.
3497
3498Using this flag can cause problems when inline functions that would otherwise
3499be dllexported refer to internal symbols of a DLL. For example:
3500
3501.. code-block:: c
3502
3503 void internal();
3504
3505 struct __declspec(dllimport) S {
3506 void foo() { internal(); }
3507 }
3508
3509Normally, references to `S::foo()` would use the definition in the DLL from
3510which it was exported, and which presumably also has the definition of
3511`internal()`. However, when using ``/Zc:dllexportInlines-``, the inline
3512definition of `S::foo()` is used directly, resulting in a link error since
3513`internal()` is not available. Even worse, if there is an inline definition of
3514`internal()` containing a static local variable, we will now refer to a
3515different instance of that variable than in the DLL:
3516
3517.. code-block:: c
3518
3519 inline int internal() { static int x; return x++; }
3520
3521 struct __declspec(dllimport) S {
3522 int foo() { return internal(); }
3523 }
3524
3525This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can
Hans Wennborg7717a5c2018-11-13 09:05:12 +00003526lead to the same issue. To avoid it in this case, make `S::foo()` or
3527`internal()` non-inline, or mark them `dllimport/dllexport` explicitly.
Hans Wennborg96a78602018-11-12 08:38:10 +00003528
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00003529The /fallback Option
3530^^^^^^^^^^^^^^^^^^^^
3531
3532When clang-cl is run with the ``/fallback`` option, it will first try to
3533compile files itself. For any file that it fails to compile, it will fall back
3534and try to compile the file by invoking cl.exe.
3535
3536This option is intended to be used as a temporary means to build projects where
3537clang-cl cannot successfully compile all the files. clang-cl may fail to compile
3538a file either because it cannot generate code for some C++ feature, or because
3539it cannot parse some Microsoft language extension.