UsersManual.rst 85 KB

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