UsersManual.rst 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539
  1. ============================
  2. Clang Compiler User's Manual
  3. ============================
  4. .. include:: <isonum.txt>
  5. .. contents::
  6. :local:
  7. Introduction
  8. ============
  9. The Clang Compiler is an open-source compiler for the C family of
  10. programming languages, aiming to be the best in class implementation of
  11. these languages. Clang builds on the LLVM optimizer and code generator,
  12. allowing it to provide high-quality optimization and code generation
  13. support for many targets. For more general information, please see the
  14. `Clang Web Site <https://clang.llvm.org>`_ or the `LLVM Web
  15. Site <https://llvm.org>`_.
  16. This document describes important notes about using Clang as a compiler
  17. for an end-user, documenting the supported features, command line
  18. options, etc. If you are interested in using Clang to build a tool that
  19. processes code, please see :doc:`InternalsManual`. If you are interested in the
  20. `Clang Static Analyzer <https://clang-analyzer.llvm.org>`_, please see its web
  21. page.
  22. Clang is one component in a complete toolchain for C family languages.
  23. A separate document describes the other pieces necessary to
  24. :doc:`assemble a complete toolchain <Toolchain>`.
  25. Clang is designed to support the C family of programming languages,
  26. which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
  27. :ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
  28. language-specific information, please see the corresponding language
  29. specific section:
  30. - :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
  31. C99 (+TC1, TC2, TC3).
  32. - :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
  33. variants depending on base language.
  34. - :ref:`C++ Language <cxx>`
  35. - :ref:`Objective C++ Language <objcxx>`
  36. - :ref:`OpenCL C Language <opencl>`: v1.0, v1.1, v1.2, v2.0.
  37. In addition to these base languages and their dialects, Clang supports a
  38. broad variety of language extensions, which are documented in the
  39. corresponding language section. These extensions are provided to be
  40. compatible with the GCC, Microsoft, and other popular compilers as well
  41. as to improve functionality through Clang-specific features. The Clang
  42. driver and language features are intentionally designed to be as
  43. compatible with the GNU GCC compiler as reasonably possible, easing
  44. migration from GCC to Clang. In most cases, code "just works".
  45. Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
  46. to be compatible with the Visual C++ compiler, cl.exe.
  47. In addition to language specific features, Clang has a variety of
  48. features that depend on what CPU architecture or operating system is
  49. being compiled for. Please see the :ref:`Target-Specific Features and
  50. Limitations <target_features>` section for more details.
  51. The rest of the introduction introduces some basic :ref:`compiler
  52. terminology <terminology>` that is used throughout this manual and
  53. contains a basic :ref:`introduction to using Clang <basicusage>` as a
  54. command line compiler.
  55. .. _terminology:
  56. Terminology
  57. -----------
  58. Front end, parser, backend, preprocessor, undefined behavior,
  59. diagnostic, optimizer
  60. .. _basicusage:
  61. Basic Usage
  62. -----------
  63. Intro to how to use a C compiler for newbies.
  64. compile + link compile then link debug info enabling optimizations
  65. picking a language to use, defaults to C11 by default. Autosenses based
  66. on extension. using a makefile
  67. Command Line Options
  68. ====================
  69. This section is generally an index into other sections. It does not go
  70. into depth on the ones that are covered by other sections. However, the
  71. first part introduces the language selection and other high level
  72. options like :option:`-c`, :option:`-g`, etc.
  73. Options to Control Error and Warning Messages
  74. ---------------------------------------------
  75. .. option:: -Werror
  76. Turn warnings into errors.
  77. .. This is in plain monospaced font because it generates the same label as
  78. .. -Werror, and Sphinx complains.
  79. ``-Werror=foo``
  80. Turn warning "foo" into an error.
  81. .. option:: -Wno-error=foo
  82. Turn warning "foo" into a warning even if :option:`-Werror` is specified.
  83. .. option:: -Wfoo
  84. Enable warning "foo".
  85. See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
  86. list of the warning flags that can be specified in this way.
  87. .. option:: -Wno-foo
  88. Disable warning "foo".
  89. .. option:: -w
  90. Disable all diagnostics.
  91. .. option:: -Weverything
  92. :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
  93. .. option:: -pedantic
  94. Warn on language extensions.
  95. .. option:: -pedantic-errors
  96. Error on language extensions.
  97. .. option:: -Wsystem-headers
  98. Enable warnings from system headers.
  99. .. option:: -ferror-limit=123
  100. Stop emitting diagnostics after 123 errors have been produced. The default is
  101. 20, and the error limit can be disabled with `-ferror-limit=0`.
  102. .. option:: -ftemplate-backtrace-limit=123
  103. Only emit up to 123 template instantiation notes within the template
  104. instantiation backtrace for a single warning or error. The default is 10, and
  105. the limit can be disabled with `-ftemplate-backtrace-limit=0`.
  106. .. _cl_diag_formatting:
  107. Formatting of Diagnostics
  108. ^^^^^^^^^^^^^^^^^^^^^^^^^
  109. Clang aims to produce beautiful diagnostics by default, particularly for
  110. new users that first come to Clang. However, different people have
  111. different preferences, and sometimes Clang is driven not by a human,
  112. but by a program that wants consistent and easily parsable output. For
  113. these cases, Clang provides a wide range of options to control the exact
  114. output format of the diagnostics that it generates.
  115. .. _opt_fshow-column:
  116. **-f[no-]show-column**
  117. Print column number in diagnostic.
  118. This option, which defaults to on, controls whether or not Clang
  119. prints the column number of a diagnostic. For example, when this is
  120. enabled, Clang will print something like:
  121. ::
  122. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  123. #endif bad
  124. ^
  125. //
  126. When this is disabled, Clang will print "test.c:28: warning..." with
  127. no column number.
  128. The printed column numbers count bytes from the beginning of the
  129. line; take care if your source contains multibyte characters.
  130. .. _opt_fshow-source-location:
  131. **-f[no-]show-source-location**
  132. Print source file/line/column information in diagnostic.
  133. This option, which defaults to on, controls whether or not Clang
  134. prints the filename, line number and column number of a diagnostic.
  135. For example, when this is enabled, Clang will print something like:
  136. ::
  137. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  138. #endif bad
  139. ^
  140. //
  141. When this is disabled, Clang will not print the "test.c:28:8: "
  142. part.
  143. .. _opt_fcaret-diagnostics:
  144. **-f[no-]caret-diagnostics**
  145. Print source line and ranges from source code in diagnostic.
  146. This option, which defaults to on, controls whether or not Clang
  147. prints the source line, source ranges, and caret when emitting a
  148. diagnostic. For example, when this is enabled, Clang will print
  149. something like:
  150. ::
  151. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  152. #endif bad
  153. ^
  154. //
  155. **-f[no-]color-diagnostics**
  156. This option, which defaults to on when a color-capable terminal is
  157. detected, controls whether or not Clang prints diagnostics in color.
  158. When this option is enabled, Clang will use colors to highlight
  159. specific parts of the diagnostic, e.g.,
  160. .. nasty hack to not lose our dignity
  161. .. raw:: html
  162. <pre>
  163. <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>
  164. #endif bad
  165. <span style="color:green">^</span>
  166. <span style="color:green">//</span>
  167. </pre>
  168. When this is disabled, Clang will just print:
  169. ::
  170. test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  171. #endif bad
  172. ^
  173. //
  174. **-fansi-escape-codes**
  175. Controls whether ANSI escape codes are used instead of the Windows Console
  176. API to output colored diagnostics. This option is only used on Windows and
  177. defaults to off.
  178. .. option:: -fdiagnostics-format=clang/msvc/vi
  179. Changes diagnostic output format to better match IDEs and command line tools.
  180. This option controls the output format of the filename, line number,
  181. and column printed in diagnostic messages. The options, and their
  182. affect on formatting a simple conversion diagnostic, follow:
  183. **clang** (default)
  184. ::
  185. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
  186. **msvc**
  187. ::
  188. t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
  189. **vi**
  190. ::
  191. t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
  192. .. _opt_fdiagnostics-show-option:
  193. **-f[no-]diagnostics-show-option**
  194. Enable ``[-Woption]`` information in diagnostic line.
  195. This option, which defaults to on, controls whether or not Clang
  196. prints the associated :ref:`warning group <cl_diag_warning_groups>`
  197. option name when outputting a warning diagnostic. For example, in
  198. this output:
  199. ::
  200. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  201. #endif bad
  202. ^
  203. //
  204. Passing **-fno-diagnostics-show-option** will prevent Clang from
  205. printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
  206. the diagnostic. This information tells you the flag needed to enable
  207. or disable the diagnostic, either from the command line or through
  208. :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
  209. .. _opt_fdiagnostics-show-category:
  210. .. option:: -fdiagnostics-show-category=none/id/name
  211. Enable printing category information in diagnostic line.
  212. This option, which defaults to "none", controls whether or not Clang
  213. prints the category associated with a diagnostic when emitting it.
  214. Each diagnostic may or many not have an associated category, if it
  215. has one, it is listed in the diagnostic categorization field of the
  216. diagnostic line (in the []'s).
  217. For example, a format string warning will produce these three
  218. renditions based on the setting of this option:
  219. ::
  220. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
  221. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
  222. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
  223. This category can be used by clients that want to group diagnostics
  224. by category, so it should be a high level category. We want dozens
  225. of these, not hundreds or thousands of them.
  226. .. _opt_fsave-optimization-record:
  227. .. option:: -fsave-optimization-record[=<format>]
  228. Write optimization remarks to a separate file.
  229. This option, which defaults to off, controls whether Clang writes
  230. optimization reports to a separate file. By recording diagnostics in a file,
  231. users can parse or sort the remarks in a convenient way.
  232. By default, the serialization format is YAML.
  233. The supported serialization formats are:
  234. - .. _opt_fsave_optimization_record_yaml:
  235. ``-fsave-optimization-record=yaml``: A structured YAML format.
  236. .. _opt_foptimization-record-file:
  237. **-foptimization-record-file**
  238. Control the file to which optimization reports are written.
  239. When optimization reports are being output (see
  240. :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
  241. option controls the file to which those reports are written.
  242. If this option is not used, optimization records are output to a file named
  243. after the primary file being compiled. If that's "foo.c", for example,
  244. optimization records are output to "foo.opt.yaml". If a specific
  245. serialization format is specified, the file will be named
  246. "foo.opt.<format>".
  247. .. _opt_foptimization-record-passes:
  248. **-foptimization-record-passes**
  249. Only include passes which match a specified regular expression.
  250. When optimization reports are being output (see
  251. :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
  252. option controls the passes that will be included in the final report.
  253. If this option is not used, all the passes are included in the optimization
  254. record.
  255. .. _opt_fdiagnostics-show-hotness:
  256. **-f[no-]diagnostics-show-hotness**
  257. Enable profile hotness information in diagnostic line.
  258. This option controls whether Clang prints the profile hotness associated
  259. with diagnostics in the presence of profile-guided optimization information.
  260. This is currently supported with optimization remarks (see
  261. :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
  262. allows users to focus on the hot optimization remarks that are likely to be
  263. more relevant for run-time performance.
  264. For example, in this output, the block containing the callsite of `foo` was
  265. executed 3000 times according to the profile data:
  266. ::
  267. s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
  268. sum += foo(x, x - 2);
  269. ^
  270. This option is implied when
  271. :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
  272. Otherwise, it defaults to off.
  273. .. _opt_fdiagnostics-hotness-threshold:
  274. **-fdiagnostics-hotness-threshold**
  275. Prevent optimization remarks from being output if they do not have at least
  276. this hotness value.
  277. This option, which defaults to zero, controls the minimum hotness an
  278. optimization remark would need in order to be output by Clang. This is
  279. currently supported with optimization remarks (see :ref:`Options to Emit
  280. Optimization Reports <rpass>`) when profile hotness information in
  281. diagnostics is enabled (see
  282. :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
  283. .. _opt_fdiagnostics-fixit-info:
  284. **-f[no-]diagnostics-fixit-info**
  285. Enable "FixIt" information in the diagnostics output.
  286. This option, which defaults to on, controls whether or not Clang
  287. prints the information on how to fix a specific diagnostic
  288. underneath it when it knows. For example, in this output:
  289. ::
  290. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  291. #endif bad
  292. ^
  293. //
  294. Passing **-fno-diagnostics-fixit-info** will prevent Clang from
  295. printing the "//" line at the end of the message. This information
  296. is useful for users who may not understand what is wrong, but can be
  297. confusing for machine parsing.
  298. .. _opt_fdiagnostics-print-source-range-info:
  299. **-fdiagnostics-print-source-range-info**
  300. Print machine parsable information about source ranges.
  301. This option makes Clang print information about source ranges in a machine
  302. parsable format after the file/line/column number information. The
  303. information is a simple sequence of brace enclosed ranges, where each range
  304. lists the start and end line/column locations. For example, in this output:
  305. ::
  306. exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
  307. P = (P-42) + Gamma*4;
  308. ~~~~~~ ^ ~~~~~~~
  309. The {}'s are generated by -fdiagnostics-print-source-range-info.
  310. The printed column numbers count bytes from the beginning of the
  311. line; take care if your source contains multibyte characters.
  312. .. option:: -fdiagnostics-parseable-fixits
  313. Print Fix-Its in a machine parseable form.
  314. This option makes Clang print available Fix-Its in a machine
  315. parseable format at the end of diagnostics. The following example
  316. illustrates the format:
  317. ::
  318. fix-it:"t.cpp":{7:25-7:29}:"Gamma"
  319. The range printed is a half-open range, so in this example the
  320. characters at column 25 up to but not including column 29 on line 7
  321. in t.cpp should be replaced with the string "Gamma". Either the
  322. range or the replacement string may be empty (representing strict
  323. insertions and strict erasures, respectively). Both the file name
  324. and the insertion string escape backslash (as "\\\\"), tabs (as
  325. "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
  326. non-printable characters (as octal "\\xxx").
  327. The printed column numbers count bytes from the beginning of the
  328. line; take care if your source contains multibyte characters.
  329. .. option:: -fno-elide-type
  330. Turns off elision in template type printing.
  331. The default for template type printing is to elide as many template
  332. arguments as possible, removing those which are the same in both
  333. template types, leaving only the differences. Adding this flag will
  334. print all the template arguments. If supported by the terminal,
  335. highlighting will still appear on differing arguments.
  336. Default:
  337. ::
  338. 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;
  339. -fno-elide-type:
  340. ::
  341. 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;
  342. .. option:: -fdiagnostics-show-template-tree
  343. Template type diffing prints a text tree.
  344. For diffing large templated types, this option will cause Clang to
  345. display the templates as an indented text tree, one argument per
  346. line, with differences marked inline. This is compatible with
  347. -fno-elide-type.
  348. Default:
  349. ::
  350. 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;
  351. With :option:`-fdiagnostics-show-template-tree`:
  352. ::
  353. t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
  354. vector<
  355. map<
  356. [...],
  357. map<
  358. [float != double],
  359. [...]>>>
  360. .. _cl_diag_warning_groups:
  361. Individual Warning Groups
  362. ^^^^^^^^^^^^^^^^^^^^^^^^^
  363. TODO: Generate this from tblgen. Define one anchor per warning group.
  364. .. _opt_wextra-tokens:
  365. .. option:: -Wextra-tokens
  366. Warn about excess tokens at the end of a preprocessor directive.
  367. This option, which defaults to on, enables warnings about extra
  368. tokens at the end of preprocessor directives. For example:
  369. ::
  370. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  371. #endif bad
  372. ^
  373. These extra tokens are not strictly conforming, and are usually best
  374. handled by commenting them out.
  375. .. option:: -Wambiguous-member-template
  376. Warn about unqualified uses of a member template whose name resolves to
  377. another template at the location of the use.
  378. This option, which defaults to on, enables a warning in the
  379. following code:
  380. ::
  381. template<typename T> struct set{};
  382. template<typename T> struct trait { typedef const T& type; };
  383. struct Value {
  384. template<typename T> void set(typename trait<T>::type value) {}
  385. };
  386. void foo() {
  387. Value v;
  388. v.set<double>(3.2);
  389. }
  390. C++ [basic.lookup.classref] requires this to be an error, but,
  391. because it's hard to work around, Clang downgrades it to a warning
  392. as an extension.
  393. .. option:: -Wbind-to-temporary-copy
  394. Warn about an unusable copy constructor when binding a reference to a
  395. temporary.
  396. This option enables warnings about binding a
  397. reference to a temporary when the temporary doesn't have a usable
  398. copy constructor. For example:
  399. ::
  400. struct NonCopyable {
  401. NonCopyable();
  402. private:
  403. NonCopyable(const NonCopyable&);
  404. };
  405. void foo(const NonCopyable&);
  406. void bar() {
  407. foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
  408. }
  409. ::
  410. struct NonCopyable2 {
  411. NonCopyable2();
  412. NonCopyable2(NonCopyable2&);
  413. };
  414. void foo(const NonCopyable2&);
  415. void bar() {
  416. foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
  417. }
  418. Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
  419. whose instantiation produces a compile error, that error will still
  420. be a hard error in C++98 mode even if this warning is turned off.
  421. Options to Control Clang Crash Diagnostics
  422. ------------------------------------------
  423. As unbelievable as it may sound, Clang does crash from time to time.
  424. Generally, this only occurs to those living on the `bleeding
  425. edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great
  426. lengths to assist you in filing a bug report. Specifically, Clang
  427. generates preprocessed source file(s) and associated run script(s) upon
  428. a crash. These files should be attached to a bug report to ease
  429. reproducibility of the failure. Below are the command line options to
  430. control the crash diagnostics.
  431. .. option:: -fno-crash-diagnostics
  432. Disable auto-generation of preprocessed source files during a clang crash.
  433. The -fno-crash-diagnostics flag can be helpful for speeding the process
  434. of generating a delta reduced test case.
  435. Clang is also capable of generating preprocessed source file(s) and associated
  436. run script(s) even without a crash. This is specially useful when trying to
  437. generate a reproducer for warnings or errors while using modules.
  438. .. option:: -gen-reproducer
  439. Generates preprocessed source files, a reproducer script and if relevant, a
  440. cache containing: built module pcm's and all headers needed to rebuilt the
  441. same modules.
  442. .. _rpass:
  443. Options to Emit Optimization Reports
  444. ------------------------------------
  445. Optimization reports trace, at a high-level, all the major decisions
  446. done by compiler transformations. For instance, when the inliner
  447. decides to inline function ``foo()`` into ``bar()``, or the loop unroller
  448. decides to unroll a loop N times, or the vectorizer decides to
  449. vectorize a loop body.
  450. Clang offers a family of flags which the optimizers can use to emit
  451. a diagnostic in three cases:
  452. 1. When the pass makes a transformation (`-Rpass`).
  453. 2. When the pass fails to make a transformation (`-Rpass-missed`).
  454. 3. When the pass determines whether or not to make a transformation
  455. (`-Rpass-analysis`).
  456. NOTE: Although the discussion below focuses on `-Rpass`, the exact
  457. same options apply to `-Rpass-missed` and `-Rpass-analysis`.
  458. Since there are dozens of passes inside the compiler, each of these flags
  459. take a regular expression that identifies the name of the pass which should
  460. emit the associated diagnostic. For example, to get a report from the inliner,
  461. compile the code with:
  462. .. code-block:: console
  463. $ clang -O2 -Rpass=inline code.cc -o code
  464. code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
  465. int bar(int j) { return foo(j, j - 2); }
  466. ^
  467. Note that remarks from the inliner are identified with `[-Rpass=inline]`.
  468. To request a report from every optimization pass, you should use
  469. `-Rpass=.*` (in fact, you can use any valid POSIX regular
  470. expression). However, do not expect a report from every transformation
  471. made by the compiler. Optimization remarks do not really make sense
  472. outside of the major transformations (e.g., inlining, vectorization,
  473. loop optimizations) and not every optimization pass supports this
  474. feature.
  475. Note that when using profile-guided optimization information, profile hotness
  476. information can be included in the remarks (see
  477. :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
  478. Current limitations
  479. ^^^^^^^^^^^^^^^^^^^
  480. 1. Optimization remarks that refer to function names will display the
  481. mangled name of the function. Since these remarks are emitted by the
  482. back end of the compiler, it does not know anything about the input
  483. language, nor its mangling rules.
  484. 2. Some source locations are not displayed correctly. The front end has
  485. a more detailed source location tracking than the locations included
  486. in the debug info (e.g., the front end can locate code inside macro
  487. expansions). However, the locations used by `-Rpass` are
  488. translated from debug annotations. That translation can be lossy,
  489. which results in some remarks having no location information.
  490. Other Options
  491. -------------
  492. Clang options that don't fit neatly into other categories.
  493. .. option:: -fgnuc-version=
  494. This flag controls the value of ``__GNUC__`` and related macros. This flag
  495. does not enable or disable any GCC extensions implemented in Clang. Setting
  496. the version to zero causes Clang to leave ``__GNUC__`` and other
  497. GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined.
  498. .. option:: -MV
  499. When emitting a dependency file, use formatting conventions appropriate
  500. for NMake or Jom. Ignored unless another option causes Clang to emit a
  501. dependency file.
  502. When Clang emits a dependency file (e.g., you supplied the -M option)
  503. most filenames can be written to the file without any special formatting.
  504. Different Make tools will treat different sets of characters as "special"
  505. and use different conventions for telling the Make tool that the character
  506. is actually part of the filename. Normally Clang uses backslash to "escape"
  507. a special character, which is the convention used by GNU Make. The -MV
  508. option tells Clang to put double-quotes around the entire filename, which
  509. is the convention used by NMake and Jom.
  510. Configuration files
  511. -------------------
  512. Configuration files group command-line options and allow all of them to be
  513. specified just by referencing the configuration file. They may be used, for
  514. example, to collect options required to tune compilation for particular
  515. target, such as -L, -I, -l, --sysroot, codegen options, etc.
  516. The command line option `--config` can be used to specify configuration
  517. file in a Clang invocation. For example:
  518. ::
  519. clang --config /home/user/cfgs/testing.txt
  520. clang --config debug.cfg
  521. If the provided argument contains a directory separator, it is considered as
  522. a file path, and options are read from that file. Otherwise the argument is
  523. treated as a file name and is searched for sequentially in the directories:
  524. - user directory,
  525. - system directory,
  526. - the directory where Clang executable resides.
  527. Both user and system directories for configuration files are specified during
  528. clang build using CMake parameters, CLANG_CONFIG_FILE_USER_DIR and
  529. CLANG_CONFIG_FILE_SYSTEM_DIR respectively. The first file found is used. It is
  530. an error if the required file cannot be found.
  531. Another way to specify a configuration file is to encode it in executable name.
  532. For example, if the Clang executable is named `armv7l-clang` (it may be a
  533. symbolic link to `clang`), then Clang will search for file `armv7l.cfg` in the
  534. directory where Clang resides.
  535. If a driver mode is specified in invocation, Clang tries to find a file specific
  536. for the specified mode. For example, if the executable file is named
  537. `x86_64-clang-cl`, Clang first looks for `x86_64-cl.cfg` and if it is not found,
  538. looks for `x86_64.cfg`.
  539. If the command line contains options that effectively change target architecture
  540. (these are -m32, -EL, and some others) and the configuration file starts with an
  541. architecture name, Clang tries to load the configuration file for the effective
  542. architecture. For example, invocation:
  543. ::
  544. x86_64-clang -m32 abc.c
  545. causes Clang search for a file `i368.cfg` first, and if no such file is found,
  546. Clang looks for the file `x86_64.cfg`.
  547. The configuration file consists of command-line options specified on one or
  548. more lines. Lines composed of whitespace characters only are ignored as well as
  549. lines in which the first non-blank character is `#`. Long options may be split
  550. between several lines by a trailing backslash. Here is example of a
  551. configuration file:
  552. ::
  553. # Several options on line
  554. -c --target=x86_64-unknown-linux-gnu
  555. # Long option split between lines
  556. -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\
  557. include/c++/5.4.0
  558. # other config files may be included
  559. @linux.options
  560. Files included by `@file` directives in configuration files are resolved
  561. relative to the including file. For example, if a configuration file
  562. `~/.llvm/target.cfg` contains the directive `@os/linux.opts`, the file
  563. `linux.opts` is searched for in the directory `~/.llvm/os`.
  564. Language and Target-Independent Features
  565. ========================================
  566. Controlling Errors and Warnings
  567. -------------------------------
  568. Clang provides a number of ways to control which code constructs cause
  569. it to emit errors and warning messages, and how they are displayed to
  570. the console.
  571. Controlling How Clang Displays Diagnostics
  572. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  573. When Clang emits a diagnostic, it includes rich information in the
  574. output, and gives you fine-grain control over which information is
  575. printed. Clang has the ability to print this information, and these are
  576. the options that control it:
  577. #. A file/line/column indicator that shows exactly where the diagnostic
  578. occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
  579. :ref:`-fshow-source-location <opt_fshow-source-location>`].
  580. #. A categorization of the diagnostic as a note, warning, error, or
  581. fatal error.
  582. #. A text string that describes what the problem is.
  583. #. An option that indicates how to control the diagnostic (for
  584. diagnostics that support it)
  585. [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
  586. #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
  587. for clients that want to group diagnostics by class (for diagnostics
  588. that support it)
  589. [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
  590. #. The line of source code that the issue occurs on, along with a caret
  591. and ranges that indicate the important locations
  592. [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
  593. #. "FixIt" information, which is a concise explanation of how to fix the
  594. problem (when Clang is certain it knows)
  595. [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
  596. #. A machine-parsable representation of the ranges involved (off by
  597. default)
  598. [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
  599. For more information please see :ref:`Formatting of
  600. Diagnostics <cl_diag_formatting>`.
  601. Diagnostic Mappings
  602. ^^^^^^^^^^^^^^^^^^^
  603. All diagnostics are mapped into one of these 6 classes:
  604. - Ignored
  605. - Note
  606. - Remark
  607. - Warning
  608. - Error
  609. - Fatal
  610. .. _diagnostics_categories:
  611. Diagnostic Categories
  612. ^^^^^^^^^^^^^^^^^^^^^
  613. Though not shown by default, diagnostics may each be associated with a
  614. high-level category. This category is intended to make it possible to
  615. triage builds that produce a large number of errors or warnings in a
  616. grouped way.
  617. Categories are not shown by default, but they can be turned on with the
  618. :ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
  619. When set to "``name``", the category is printed textually in the
  620. diagnostic output. When it is set to "``id``", a category number is
  621. printed. The mapping of category names to category id's can be obtained
  622. by running '``clang --print-diagnostic-categories``'.
  623. Controlling Diagnostics via Command Line Flags
  624. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  625. TODO: -W flags, -pedantic, etc
  626. .. _pragma_gcc_diagnostic:
  627. Controlling Diagnostics via Pragmas
  628. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  629. Clang can also control what diagnostics are enabled through the use of
  630. pragmas in the source code. This is useful for turning off specific
  631. warnings in a section of source code. Clang supports GCC's pragma for
  632. compatibility with existing source code, as well as several extensions.
  633. The pragma may control any warning that can be used from the command
  634. line. Warnings may be set to ignored, warning, error, or fatal. The
  635. following example code will tell Clang or GCC to ignore the -Wall
  636. warnings:
  637. .. code-block:: c
  638. #pragma GCC diagnostic ignored "-Wall"
  639. In addition to all of the functionality provided by GCC's pragma, Clang
  640. also allows you to push and pop the current warning state. This is
  641. particularly useful when writing a header file that will be compiled by
  642. other people, because you don't know what warning flags they build with.
  643. In the below example :option:`-Wextra-tokens` is ignored for only a single line
  644. of code, after which the diagnostics return to whatever state had previously
  645. existed.
  646. .. code-block:: c
  647. #if foo
  648. #endif foo // warning: extra tokens at end of #endif directive
  649. #pragma clang diagnostic push
  650. #pragma clang diagnostic ignored "-Wextra-tokens"
  651. #if foo
  652. #endif foo // no warning
  653. #pragma clang diagnostic pop
  654. The push and pop pragmas will save and restore the full diagnostic state
  655. of the compiler, regardless of how it was set. That means that it is
  656. possible to use push and pop around GCC compatible diagnostics and Clang
  657. will push and pop them appropriately, while GCC will ignore the pushes
  658. and pops as unknown pragmas. It should be noted that while Clang
  659. supports the GCC pragma, Clang and GCC do not support the exact same set
  660. of warnings, so even when using GCC compatible #pragmas there is no
  661. guarantee that they will have identical behaviour on both compilers.
  662. In addition to controlling warnings and errors generated by the compiler, it is
  663. possible to generate custom warning and error messages through the following
  664. pragmas:
  665. .. code-block:: c
  666. // The following will produce warning messages
  667. #pragma message "some diagnostic message"
  668. #pragma GCC warning "TODO: replace deprecated feature"
  669. // The following will produce an error message
  670. #pragma GCC error "Not supported"
  671. These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
  672. directives, except that they may also be embedded into preprocessor macros via
  673. the C99 ``_Pragma`` operator, for example:
  674. .. code-block:: c
  675. #define STR(X) #X
  676. #define DEFER(M,...) M(__VA_ARGS__)
  677. #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
  678. CUSTOM_ERROR("Feature not available");
  679. Controlling Diagnostics in System Headers
  680. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  681. Warnings are suppressed when they occur in system headers. By default,
  682. an included file is treated as a system header if it is found in an
  683. include path specified by ``-isystem``, but this can be overridden in
  684. several ways.
  685. The ``system_header`` pragma can be used to mark the current file as
  686. being a system header. No warnings will be produced from the location of
  687. the pragma onwards within the same file.
  688. .. code-block:: c
  689. #if foo
  690. #endif foo // warning: extra tokens at end of #endif directive
  691. #pragma clang system_header
  692. #if foo
  693. #endif foo // no warning
  694. The `--system-header-prefix=` and `--no-system-header-prefix=`
  695. command-line arguments can be used to override whether subsets of an include
  696. path are treated as system headers. When the name in a ``#include`` directive
  697. is found within a header search path and starts with a system prefix, the
  698. header is treated as a system header. The last prefix on the
  699. command-line which matches the specified header name takes precedence.
  700. For instance:
  701. .. code-block:: console
  702. $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
  703. --no-system-header-prefix=x/y/
  704. Here, ``#include "x/a.h"`` is treated as including a system header, even
  705. if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
  706. as not including a system header, even if the header is found in
  707. ``bar``.
  708. A ``#include`` directive which finds a file relative to the current
  709. directory is treated as including a system header if the including file
  710. is treated as a system header.
  711. .. _diagnostics_enable_everything:
  712. Enabling All Diagnostics
  713. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  714. In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
  715. by passing :option:`-Weverything`. This works as expected with
  716. :option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some
  717. diagnostics contradict each other, therefore, users of :option:`-Weverything`
  718. often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat`
  719. because they contradict recent C++ standards.
  720. Since :option:`-Weverything` enables every diagnostic, we generally don't
  721. recommend using it. `-Wall` `-Wextra` are a better choice for most projects.
  722. Using :option:`-Weverything` means that updating your compiler is more difficult
  723. because you're exposed to experimental diagnostics which might be of lower
  724. quality than the default ones. If you do use :option:`-Weverything` then we
  725. advise that you address all new compiler diagnostics as they get added to Clang,
  726. either by fixing everything they find or explicitly disabling that diagnostic
  727. with its corresponding `Wno-` option.
  728. Note that when combined with :option:`-w` (which disables all warnings),
  729. disabling all warnings wins.
  730. Controlling Static Analyzer Diagnostics
  731. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  732. While not strictly part of the compiler, the diagnostics from Clang's
  733. `static analyzer <https://clang-analyzer.llvm.org>`_ can also be
  734. influenced by the user via changes to the source code. See the available
  735. `annotations <https://clang-analyzer.llvm.org/annotations.html>`_ and the
  736. analyzer's `FAQ
  737. page <https://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
  738. information.
  739. .. _usersmanual-precompiled-headers:
  740. Precompiled Headers
  741. -------------------
  742. `Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_
  743. are a general approach employed by many compilers to reduce compilation
  744. time. The underlying motivation of the approach is that it is common for
  745. the same (and often large) header files to be included by multiple
  746. source files. Consequently, compile times can often be greatly improved
  747. by caching some of the (redundant) work done by a compiler to process
  748. headers. Precompiled header files, which represent one of many ways to
  749. implement this optimization, are literally files that represent an
  750. on-disk cache that contains the vital information necessary to reduce
  751. some of the work needed to process a corresponding header file. While
  752. details of precompiled headers vary between compilers, precompiled
  753. headers have been shown to be highly effective at speeding up program
  754. compilation on systems with very large system headers (e.g., macOS).
  755. Generating a PCH File
  756. ^^^^^^^^^^^^^^^^^^^^^
  757. To generate a PCH file using Clang, one invokes Clang with the
  758. `-x <language>-header` option. This mirrors the interface in GCC
  759. for generating PCH files:
  760. .. code-block:: console
  761. $ gcc -x c-header test.h -o test.h.gch
  762. $ clang -x c-header test.h -o test.h.pch
  763. Using a PCH File
  764. ^^^^^^^^^^^^^^^^
  765. A PCH file can then be used as a prefix header when a :option:`-include`
  766. option is passed to ``clang``:
  767. .. code-block:: console
  768. $ clang -include test.h test.c -o test
  769. The ``clang`` driver will first check if a PCH file for ``test.h`` is
  770. available; if so, the contents of ``test.h`` (and the files it includes)
  771. will be processed from the PCH file. Otherwise, Clang falls back to
  772. directly processing the content of ``test.h``. This mirrors the behavior
  773. of GCC.
  774. .. note::
  775. Clang does *not* automatically use PCH files for headers that are directly
  776. included within a source file. For example:
  777. .. code-block:: console
  778. $ clang -x c-header test.h -o test.h.pch
  779. $ cat test.c
  780. #include "test.h"
  781. $ clang test.c -o test
  782. In this example, ``clang`` will not automatically use the PCH file for
  783. ``test.h`` since ``test.h`` was included directly in the source file and not
  784. specified on the command line using :option:`-include`.
  785. Relocatable PCH Files
  786. ^^^^^^^^^^^^^^^^^^^^^
  787. It is sometimes necessary to build a precompiled header from headers
  788. that are not yet in their final, installed locations. For example, one
  789. might build a precompiled header within the build tree that is then
  790. meant to be installed alongside the headers. Clang permits the creation
  791. of "relocatable" precompiled headers, which are built with a given path
  792. (into the build directory) and can later be used from an installed
  793. location.
  794. To build a relocatable precompiled header, place your headers into a
  795. subdirectory whose structure mimics the installed location. For example,
  796. if you want to build a precompiled header for the header ``mylib.h``
  797. that will be installed into ``/usr/include``, create a subdirectory
  798. ``build/usr/include`` and place the header ``mylib.h`` into that
  799. subdirectory. If ``mylib.h`` depends on other headers, then they can be
  800. stored within ``build/usr/include`` in a way that mimics the installed
  801. location.
  802. Building a relocatable precompiled header requires two additional
  803. arguments. First, pass the ``--relocatable-pch`` flag to indicate that
  804. the resulting PCH file should be relocatable. Second, pass
  805. ``-isysroot /path/to/build``, which makes all includes for your library
  806. relative to the build directory. For example:
  807. .. code-block:: console
  808. # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
  809. When loading the relocatable PCH file, the various headers used in the
  810. PCH file are found from the system header root. For example, ``mylib.h``
  811. can be found in ``/usr/include/mylib.h``. If the headers are installed
  812. in some other system root, the ``-isysroot`` option can be used provide
  813. a different system root from which the headers will be based. For
  814. example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
  815. ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
  816. Relocatable precompiled headers are intended to be used in a limited
  817. number of cases where the compilation environment is tightly controlled
  818. and the precompiled header cannot be generated after headers have been
  819. installed.
  820. .. _controlling-fp-behavior:
  821. Controlling Floating Point Behavior
  822. -----------------------------------
  823. Clang provides a number of ways to control floating point behavior. The options
  824. are listed below.
  825. .. option:: -ffast-math
  826. Enable fast-math mode. This option lets the
  827. compiler make aggressive, potentially-lossy assumptions about
  828. floating-point math. These include:
  829. * Floating-point math obeys regular algebraic rules for real numbers (e.g.
  830. ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
  831. ``(a + b) * c == a * c + b * c``),
  832. * Operands to floating-point operations are not equal to ``NaN`` and
  833. ``Inf``, and
  834. * ``+0`` and ``-0`` are interchangeable.
  835. ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor
  836. macro. Some math libraries recognize this macro and change their behavior.
  837. With the exception of ``-ffp-contract=fast``, using any of the options
  838. below to disable any of the individual optimizations in ``-ffast-math``
  839. will cause ``__FAST_MATH__`` to no longer be set.
  840. This option implies:
  841. * ``-fno-honor-infinities``
  842. * ``-fno-honor-nans``
  843. * ``-fno-math-errno``
  844. * ``-ffinite-math``
  845. * ``-fassociative-math``
  846. * ``-freciprocal-math``
  847. * ``-fno-signed-zeros``
  848. * ``-fno-trapping-math``
  849. * ``-ffp-contract=fast``
  850. .. option:: -fdenormal-fp-math=<value>
  851. Select which denormal numbers the code is permitted to require.
  852. Valid values are:
  853. * ``ieee`` - IEEE 754 denormal numbers
  854. * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 0
  855. * ``positive-zero`` - denormals are flushed to positive zero
  856. Defaults to ``ieee``.
  857. .. _opt_fstrict-float-cast-overflow:
  858. **-f[no-]strict-float-cast-overflow**
  859. When a floating-point value is not representable in a destination integer
  860. type, the code has undefined behavior according to the language standard.
  861. By default, Clang will not guarantee any particular result in that case.
  862. With the 'no-strict' option, Clang attempts to match the overflowing behavior
  863. of the target's native float-to-int conversion instructions.
  864. .. _opt_fmath-errno:
  865. **-f[no-]math-errno**
  866. Require math functions to indicate errors by setting errno.
  867. The default varies by ToolChain. ``-fno-math-errno`` allows optimizations
  868. that might cause standard C math functions to not set ``errno``.
  869. For example, on some systems, the math function ``sqrt`` is specified
  870. as setting ``errno`` to ``EDOM`` when the input is negative. On these
  871. systems, the compiler cannot normally optimize a call to ``sqrt`` to use
  872. inline code (e.g. the x86 ``sqrtsd`` instruction) without additional
  873. checking to ensure that ``errno`` is set appropriately.
  874. ``-fno-math-errno`` permits these transformations.
  875. On some targets, math library functions never set ``errno``, and so
  876. ``-fno-math-errno`` is the default. This includes most BSD-derived
  877. systems, including Darwin.
  878. .. _opt_ftrapping-math:
  879. **-f[no-]trapping-math**
  880. ``-fno-trapping-math`` allows optimizations that assume that
  881. floating point operations cannot generate traps such as divide-by-zero,
  882. overflow and underflow. Defaults to ``-ftrapping-math``.
  883. Currently this option has no effect.
  884. .. option:: -ffp-contract=<value>
  885. Specify when the compiler is permitted to form fused floating-point
  886. operations, such as fused multiply-add (FMA). Fused operations are
  887. permitted to produce more precise results than performing the same
  888. operations separately.
  889. The C standard permits intermediate floating-point results within an
  890. expression to be computed with more precision than their type would
  891. normally allow. This permits operation fusing, and Clang takes advantage
  892. of this by default. This behavior can be controlled with the
  893. ``FP_CONTRACT`` pragma. Please refer to the pragma documentation for a
  894. description of how the pragma interacts with this option.
  895. Valid values are:
  896. * ``fast`` (everywhere)
  897. * ``on`` (according to FP_CONTRACT pragma, default)
  898. * ``off`` (never fuse)
  899. .. _opt_fhonor-infinities:
  900. **-f[no-]honor-infinities**
  901. If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
  902. has the same effect as specifying ``-ffinite-math``.
  903. .. _opt_fhonor-nans:
  904. **-f[no-]honor-nans**
  905. If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
  906. has the same effect as specifying ``-ffinite-math``.
  907. .. _opt_fsigned-zeros:
  908. **-f[no-]signed-zeros**
  909. Allow optimizations that ignore the sign of floating point zeros.
  910. Defaults to ``-fno-signed-zeros``.
  911. .. _opt_fassociative-math:
  912. **-f[no-]associative-math**
  913. Allow floating point operations to be reassociated.
  914. Defaults to ``-fno-associative-math``.
  915. .. _opt_freciprocal-math:
  916. **-f[no-]reciprocal-math**
  917. Allow division operations to be transformed into multiplication by a
  918. reciprocal. This can be significantly faster than an ordinary division
  919. but can also have significantly less precision. Defaults to
  920. ``-fno-reciprocal-math``.
  921. .. _opt_funsafe-math-optimizations:
  922. **-f[no-]unsafe-math-optimizations**
  923. Allow unsafe floating-point optimizations. Also implies:
  924. * ``-fassociative-math``
  925. * ``-freciprocal-math``
  926. * ``-fno-signed-zeroes``
  927. * ``-fno-trapping-math``.
  928. Defaults to ``-fno-unsafe-math-optimizations``.
  929. .. _opt_ffinite-math:
  930. **-f[no-]finite-math**
  931. Allow floating-point optimizations that assume arguments and results are
  932. not NaNs or +-Inf. This defines the ``__FINITE_MATH_ONLY__`` preprocessor macro.
  933. Also implies:
  934. * ``-fno-honor-infinities``
  935. * ``-fno-honor-nans``
  936. Defaults to ``-fno-finite-math``.
  937. .. _controlling-code-generation:
  938. Controlling Code Generation
  939. ---------------------------
  940. Clang provides a number of ways to control code generation. The options
  941. are listed below.
  942. **-f[no-]sanitize=check1,check2,...**
  943. Turn on runtime checks for various forms of undefined or suspicious
  944. behavior.
  945. This option controls whether Clang adds runtime checks for various
  946. forms of undefined or suspicious behavior, and is disabled by
  947. default. If a check fails, a diagnostic message is produced at
  948. runtime explaining the problem. The main checks are:
  949. - .. _opt_fsanitize_address:
  950. ``-fsanitize=address``:
  951. :doc:`AddressSanitizer`, a memory error
  952. detector.
  953. - .. _opt_fsanitize_thread:
  954. ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
  955. - .. _opt_fsanitize_memory:
  956. ``-fsanitize=memory``: :doc:`MemorySanitizer`,
  957. a detector of uninitialized reads. Requires instrumentation of all
  958. program code.
  959. - .. _opt_fsanitize_undefined:
  960. ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
  961. a fast and compatible undefined behavior checker.
  962. - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
  963. flow analysis.
  964. - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
  965. checks. Requires ``-flto``.
  966. - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
  967. protection against stack-based memory corruption errors.
  968. There are more fine-grained checks available: see
  969. the :ref:`list <ubsan-checks>` of specific kinds of
  970. undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
  971. of control flow integrity schemes.
  972. The ``-fsanitize=`` argument must also be provided when linking, in
  973. order to link to the appropriate runtime library.
  974. It is not possible to combine more than one of the ``-fsanitize=address``,
  975. ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
  976. program.
  977. **-f[no-]sanitize-recover=check1,check2,...**
  978. **-f[no-]sanitize-recover=all**
  979. Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
  980. If the check is fatal, program will halt after the first error
  981. of this kind is detected and error report is printed.
  982. By default, non-fatal checks are those enabled by
  983. :doc:`UndefinedBehaviorSanitizer`,
  984. except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
  985. sanitizers may not support recovery (or not support it by default
  986. e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
  987. is detected.
  988. Note that the ``-fsanitize-trap`` flag has precedence over this flag.
  989. This means that if a check has been configured to trap elsewhere on the
  990. command line, or if the check traps by default, this flag will not have
  991. any effect unless that sanitizer's trapping behavior is disabled with
  992. ``-fno-sanitize-trap``.
  993. For example, if a command line contains the flags ``-fsanitize=undefined
  994. -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
  995. will have no effect on its own; it will need to be accompanied by
  996. ``-fno-sanitize-trap=alignment``.
  997. **-f[no-]sanitize-trap=check1,check2,...**
  998. Controls which checks enabled by the ``-fsanitize=`` flag trap. This
  999. option is intended for use in cases where the sanitizer runtime cannot
  1000. be used (for instance, when building libc or a kernel module), or where
  1001. the binary size increase caused by the sanitizer runtime is a concern.
  1002. This flag is only compatible with :doc:`control flow integrity
  1003. <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
  1004. checks other than ``vptr``. If this flag
  1005. is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
  1006. will be implicitly disabled.
  1007. This flag is enabled by default for sanitizers in the ``cfi`` group.
  1008. .. option:: -fsanitize-blacklist=/path/to/blacklist/file
  1009. Disable or modify sanitizer checks for objects (source files, functions,
  1010. variables, types) listed in the file. See
  1011. :doc:`SanitizerSpecialCaseList` for file format description.
  1012. .. option:: -fno-sanitize-blacklist
  1013. Don't use blacklist file, if it was specified earlier in the command line.
  1014. **-f[no-]sanitize-coverage=[type,features,...]**
  1015. Enable simple code coverage in addition to certain sanitizers.
  1016. See :doc:`SanitizerCoverage` for more details.
  1017. **-f[no-]sanitize-stats**
  1018. Enable simple statistics gathering for the enabled sanitizers.
  1019. See :doc:`SanitizerStats` for more details.
  1020. .. option:: -fsanitize-undefined-trap-on-error
  1021. Deprecated alias for ``-fsanitize-trap=undefined``.
  1022. .. option:: -fsanitize-cfi-cross-dso
  1023. Enable cross-DSO control flow integrity checks. This flag modifies
  1024. the behavior of sanitizers in the ``cfi`` group to allow checking
  1025. of cross-DSO virtual and indirect calls.
  1026. .. option:: -fsanitize-cfi-icall-generalize-pointers
  1027. Generalize pointers in return and argument types in function type signatures
  1028. checked by Control Flow Integrity indirect call checking. See
  1029. :doc:`ControlFlowIntegrity` for more details.
  1030. .. option:: -fstrict-vtable-pointers
  1031. Enable optimizations based on the strict rules for overwriting polymorphic
  1032. C++ objects, i.e. the vptr is invariant during an object's lifetime.
  1033. This enables better devirtualization. Turned off by default, because it is
  1034. still experimental.
  1035. .. option:: -fwhole-program-vtables
  1036. Enable whole-program vtable optimizations, such as single-implementation
  1037. devirtualization and virtual constant propagation, for classes with
  1038. :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
  1039. .. option:: -fforce-emit-vtables
  1040. In order to improve devirtualization, forces emitting of vtables even in
  1041. modules where it isn't necessary. It causes more inline virtual functions
  1042. to be emitted.
  1043. .. option:: -fno-assume-sane-operator-new
  1044. Don't assume that the C++'s new operator is sane.
  1045. This option tells the compiler to do not assume that C++'s global
  1046. new operator will always return a pointer that does not alias any
  1047. other pointer when the function returns.
  1048. .. option:: -ftrap-function=[name]
  1049. Instruct code generator to emit a function call to the specified
  1050. function name for ``__builtin_trap()``.
  1051. LLVM code generator translates ``__builtin_trap()`` to a trap
  1052. instruction if it is supported by the target ISA. Otherwise, the
  1053. builtin is translated into a call to ``abort``. If this option is
  1054. set, then the code generator will always lower the builtin to a call
  1055. to the specified function regardless of whether the target ISA has a
  1056. trap instruction. This option is useful for environments (e.g.
  1057. deeply embedded) where a trap cannot be properly handled, or when
  1058. some custom behavior is desired.
  1059. .. option:: -ftls-model=[model]
  1060. Select which TLS model to use.
  1061. Valid values are: ``global-dynamic``, ``local-dynamic``,
  1062. ``initial-exec`` and ``local-exec``. The default value is
  1063. ``global-dynamic``. The compiler may use a different model if the
  1064. selected model is not supported by the target, or if a more
  1065. efficient model can be used. The TLS model can be overridden per
  1066. variable using the ``tls_model`` attribute.
  1067. .. option:: -femulated-tls
  1068. Select emulated TLS model, which overrides all -ftls-model choices.
  1069. In emulated TLS mode, all access to TLS variables are converted to
  1070. calls to __emutls_get_address in the runtime library.
  1071. .. option:: -mhwdiv=[values]
  1072. Select the ARM modes (arm or thumb) that support hardware division
  1073. instructions.
  1074. Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
  1075. This option is used to indicate which mode (arm or thumb) supports
  1076. hardware division instructions. This only applies to the ARM
  1077. architecture.
  1078. .. option:: -m[no-]crc
  1079. Enable or disable CRC instructions.
  1080. This option is used to indicate whether CRC instructions are to
  1081. be generated. This only applies to the ARM architecture.
  1082. CRC instructions are enabled by default on ARMv8.
  1083. .. option:: -mgeneral-regs-only
  1084. Generate code which only uses the general purpose registers.
  1085. This option restricts the generated code to use general registers
  1086. only. This only applies to the AArch64 architecture.
  1087. .. option:: -mcompact-branches=[values]
  1088. Control the usage of compact branches for MIPSR6.
  1089. Valid values are: ``never``, ``optimal`` and ``always``.
  1090. The default value is ``optimal`` which generates compact branches
  1091. when a delay slot cannot be filled. ``never`` disables the usage of
  1092. compact branches and ``always`` generates compact branches whenever
  1093. possible.
  1094. **-f[no-]max-type-align=[number]**
  1095. Instruct the code generator to not enforce a higher alignment than the given
  1096. number (of bytes) when accessing memory via an opaque pointer or reference.
  1097. This cap is ignored when directly accessing a variable or when the pointee
  1098. type has an explicit “aligned” attribute.
  1099. The value should usually be determined by the properties of the system allocator.
  1100. Some builtin types, especially vector types, have very high natural alignments;
  1101. when working with values of those types, Clang usually wants to use instructions
  1102. that take advantage of that alignment. However, many system allocators do
  1103. not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
  1104. this option to limit the alignment that the compiler can assume for an arbitrary
  1105. pointer, which may point onto the heap.
  1106. This option does not affect the ABI alignment of types; the layout of structs and
  1107. unions and the value returned by the alignof operator remain the same.
  1108. This option can be overridden on a case-by-case basis by putting an explicit
  1109. “aligned” alignment on a struct, union, or typedef. For example:
  1110. .. code-block:: console
  1111. #include <immintrin.h>
  1112. // Make an aligned typedef of the AVX-512 16-int vector type.
  1113. typedef __v16si __aligned_v16si __attribute__((aligned(64)));
  1114. void initialize_vector(__aligned_v16si *v) {
  1115. // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
  1116. // value of -fmax-type-align.
  1117. }
  1118. .. option:: -faddrsig, -fno-addrsig
  1119. Controls whether Clang emits an address-significance table into the object
  1120. file. Address-significance tables allow linkers to implement `safe ICF
  1121. <https://research.google.com/pubs/archive/36912.pdf>`_ without the false
  1122. positives that can result from other implementation techniques such as
  1123. relocation scanning. Address-significance tables are enabled by default
  1124. on ELF targets when using the integrated assembler. This flag currently
  1125. only has an effect on ELF targets.
  1126. Profile Guided Optimization
  1127. ---------------------------
  1128. Profile information enables better optimization. For example, knowing that a
  1129. branch is taken very frequently helps the compiler make better decisions when
  1130. ordering basic blocks. Knowing that a function ``foo`` is called more
  1131. frequently than another function ``bar`` helps the inliner. Optimization
  1132. levels ``-O2`` and above are recommended for use of profile guided optimization.
  1133. Clang supports profile guided optimization with two different kinds of
  1134. profiling. A sampling profiler can generate a profile with very low runtime
  1135. overhead, or you can build an instrumented version of the code that collects
  1136. more detailed profile information. Both kinds of profiles can provide execution
  1137. counts for instructions in the code and information on branches taken and
  1138. function invocation.
  1139. Regardless of which kind of profiling you use, be careful to collect profiles
  1140. by running your code with inputs that are representative of the typical
  1141. behavior. Code that is not exercised in the profile will be optimized as if it
  1142. is unimportant, and the compiler may make poor optimization choices for code
  1143. that is disproportionately used while profiling.
  1144. Differences Between Sampling and Instrumentation
  1145. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1146. Although both techniques are used for similar purposes, there are important
  1147. differences between the two:
  1148. 1. Profile data generated with one cannot be used by the other, and there is no
  1149. conversion tool that can convert one to the other. So, a profile generated
  1150. via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
  1151. Similarly, sampling profiles generated by external profilers must be
  1152. converted and used with ``-fprofile-sample-use``.
  1153. 2. Instrumentation profile data can be used for code coverage analysis and
  1154. optimization.
  1155. 3. Sampling profiles can only be used for optimization. They cannot be used for
  1156. code coverage analysis. Although it would be technically possible to use
  1157. sampling profiles for code coverage, sample-based profiles are too
  1158. coarse-grained for code coverage purposes; it would yield poor results.
  1159. 4. Sampling profiles must be generated by an external tool. The profile
  1160. generated by that tool must then be converted into a format that can be read
  1161. by LLVM. The section on sampling profilers describes one of the supported
  1162. sampling profile formats.
  1163. Using Sampling Profilers
  1164. ^^^^^^^^^^^^^^^^^^^^^^^^
  1165. Sampling profilers are used to collect runtime information, such as
  1166. hardware counters, while your application executes. They are typically
  1167. very efficient and do not incur a large runtime overhead. The
  1168. sample data collected by the profiler can be used during compilation
  1169. to determine what the most executed areas of the code are.
  1170. Using the data from a sample profiler requires some changes in the way
  1171. a program is built. Before the compiler can use profiling information,
  1172. the code needs to execute under the profiler. The following is the
  1173. usual build cycle when using sample profilers for optimization:
  1174. 1. Build the code with source line table information. You can use all the
  1175. usual build flags that you always build your application with. The only
  1176. requirement is that you add ``-gline-tables-only`` or ``-g`` to the
  1177. command line. This is important for the profiler to be able to map
  1178. instructions back to source line locations.
  1179. .. code-block:: console
  1180. $ clang++ -O2 -gline-tables-only code.cc -o code
  1181. 2. Run the executable under a sampling profiler. The specific profiler
  1182. you use does not really matter, as long as its output can be converted
  1183. into the format that the LLVM optimizer understands. Currently, there
  1184. exists a conversion tool for the Linux Perf profiler
  1185. (https://perf.wiki.kernel.org/), so these examples assume that you
  1186. are using Linux Perf to profile your code.
  1187. .. code-block:: console
  1188. $ perf record -b ./code
  1189. Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
  1190. Record (LBR) to record call chains. While this is not strictly required,
  1191. it provides better call information, which improves the accuracy of
  1192. the profile data.
  1193. 3. Convert the collected profile data to LLVM's sample profile format.
  1194. This is currently supported via the AutoFDO converter ``create_llvm_prof``.
  1195. It is available at https://github.com/google/autofdo. Once built and
  1196. installed, you can convert the ``perf.data`` file to LLVM using
  1197. the command:
  1198. .. code-block:: console
  1199. $ create_llvm_prof --binary=./code --out=code.prof
  1200. This will read ``perf.data`` and the binary file ``./code`` and emit
  1201. the profile data in ``code.prof``. Note that if you ran ``perf``
  1202. without the ``-b`` flag, you need to use ``--use_lbr=false`` when
  1203. calling ``create_llvm_prof``.
  1204. 4. Build the code again using the collected profile. This step feeds
  1205. the profile back to the optimizers. This should result in a binary
  1206. that executes faster than the original one. Note that you are not
  1207. required to build the code with the exact same arguments that you
  1208. used in the first step. The only requirement is that you build the code
  1209. with ``-gline-tables-only`` and ``-fprofile-sample-use``.
  1210. .. code-block:: console
  1211. $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
  1212. Sample Profile Formats
  1213. """"""""""""""""""""""
  1214. Since external profilers generate profile data in a variety of custom formats,
  1215. the data generated by the profiler must be converted into a format that can be
  1216. read by the backend. LLVM supports three different sample profile formats:
  1217. 1. ASCII text. This is the easiest one to generate. The file is divided into
  1218. sections, which correspond to each of the functions with profile
  1219. information. The format is described below. It can also be generated from
  1220. the binary or gcov formats using the ``llvm-profdata`` tool.
  1221. 2. Binary encoding. This uses a more efficient encoding that yields smaller
  1222. profile files. This is the format generated by the ``create_llvm_prof`` tool
  1223. in https://github.com/google/autofdo.
  1224. 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
  1225. is only interesting in environments where GCC and Clang co-exist. This
  1226. encoding is only generated by the ``create_gcov`` tool in
  1227. https://github.com/google/autofdo. It can be read by LLVM and
  1228. ``llvm-profdata``, but it cannot be generated by either.
  1229. If you are using Linux Perf to generate sampling profiles, you can use the
  1230. conversion tool ``create_llvm_prof`` described in the previous section.
  1231. Otherwise, you will need to write a conversion tool that converts your
  1232. profiler's native format into one of these three.
  1233. Sample Profile Text Format
  1234. """"""""""""""""""""""""""
  1235. This section describes the ASCII text format for sampling profiles. It is,
  1236. arguably, the easiest one to generate. If you are interested in generating any
  1237. of the other two, consult the ``ProfileData`` library in LLVM's source tree
  1238. (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
  1239. .. code-block:: console
  1240. function1:total_samples:total_head_samples
  1241. offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
  1242. offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
  1243. ...
  1244. offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
  1245. offsetA[.discriminator]: fnA:num_of_total_samples
  1246. offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
  1247. offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
  1248. offsetB[.discriminator]: fnB:num_of_total_samples
  1249. offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
  1250. This is a nested tree in which the indentation represents the nesting level
  1251. of the inline stack. There are no blank lines in the file. And the spacing
  1252. within a single line is fixed. Additional spaces will result in an error
  1253. while reading the file.
  1254. Any line starting with the '#' character is completely ignored.
  1255. Inlined calls are represented with indentation. The Inline stack is a
  1256. stack of source locations in which the top of the stack represents the
  1257. leaf function, and the bottom of the stack represents the actual
  1258. symbol to which the instruction belongs.
  1259. Function names must be mangled in order for the profile loader to
  1260. match them in the current translation unit. The two numbers in the
  1261. function header specify how many total samples were accumulated in the
  1262. function (first number), and the total number of samples accumulated
  1263. in the prologue of the function (second number). This head sample
  1264. count provides an indicator of how frequently the function is invoked.
  1265. There are two types of lines in the function body.
  1266. - Sampled line represents the profile information of a source location.
  1267. ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
  1268. - Callsite line represents the profile information of an inlined callsite.
  1269. ``offsetA[.discriminator]: fnA:num_of_total_samples``
  1270. Each sampled line may contain several items. Some are optional (marked
  1271. below):
  1272. a. Source line offset. This number represents the line number
  1273. in the function where the sample was collected. The line number is
  1274. always relative to the line where symbol of the function is
  1275. defined. So, if the function has its header at line 280, the offset
  1276. 13 is at line 293 in the file.
  1277. Note that this offset should never be a negative number. This could
  1278. happen in cases like macros. The debug machinery will register the
  1279. line number at the point of macro expansion. So, if the macro was
  1280. expanded in a line before the start of the function, the profile
  1281. converter should emit a 0 as the offset (this means that the optimizers
  1282. will not be able to associate a meaningful weight to the instructions
  1283. in the macro).
  1284. b. [OPTIONAL] Discriminator. This is used if the sampled program
  1285. was compiled with DWARF discriminator support
  1286. (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
  1287. DWARF discriminators are unsigned integer values that allow the
  1288. compiler to distinguish between multiple execution paths on the
  1289. same source line location.
  1290. For example, consider the line of code ``if (cond) foo(); else bar();``.
  1291. If the predicate ``cond`` is true 80% of the time, then the edge
  1292. into function ``foo`` should be considered to be taken most of the
  1293. time. But both calls to ``foo`` and ``bar`` are at the same source
  1294. line, so a sample count at that line is not sufficient. The
  1295. compiler needs to know which part of that line is taken more
  1296. frequently.
  1297. This is what discriminators provide. In this case, the calls to
  1298. ``foo`` and ``bar`` will be at the same line, but will have
  1299. different discriminator values. This allows the compiler to correctly
  1300. set edge weights into ``foo`` and ``bar``.
  1301. c. Number of samples. This is an integer quantity representing the
  1302. number of samples collected by the profiler at this source
  1303. location.
  1304. d. [OPTIONAL] Potential call targets and samples. If present, this
  1305. line contains a call instruction. This models both direct and
  1306. number of samples. For example,
  1307. .. code-block:: console
  1308. 130: 7 foo:3 bar:2 baz:7
  1309. The above means that at relative line offset 130 there is a call
  1310. instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
  1311. with ``baz()`` being the relatively more frequently called target.
  1312. As an example, consider a program with the call chain ``main -> foo -> bar``.
  1313. When built with optimizations enabled, the compiler may inline the
  1314. calls to ``bar`` and ``foo`` inside ``main``. The generated profile
  1315. could then be something like this:
  1316. .. code-block:: console
  1317. main:35504:0
  1318. 1: _Z3foov:35504
  1319. 2: _Z32bari:31977
  1320. 1.1: 31977
  1321. 2: 0
  1322. This profile indicates that there were a total of 35,504 samples
  1323. collected in main. All of those were at line 1 (the call to ``foo``).
  1324. Of those, 31,977 were spent inside the body of ``bar``. The last line
  1325. of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
  1326. samples were collected there.
  1327. Profiling with Instrumentation
  1328. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1329. Clang also supports profiling via instrumentation. This requires building a
  1330. special instrumented version of the code and has some runtime
  1331. overhead during the profiling, but it provides more detailed results than a
  1332. sampling profiler. It also provides reproducible results, at least to the
  1333. extent that the code behaves consistently across runs.
  1334. Here are the steps for using profile guided optimization with
  1335. instrumentation:
  1336. 1. Build an instrumented version of the code by compiling and linking with the
  1337. ``-fprofile-instr-generate`` option.
  1338. .. code-block:: console
  1339. $ clang++ -O2 -fprofile-instr-generate code.cc -o code
  1340. 2. Run the instrumented executable with inputs that reflect the typical usage.
  1341. By default, the profile data will be written to a ``default.profraw`` file
  1342. in the current directory. You can override that default by using option
  1343. ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
  1344. environment variable to specify an alternate file. If non-default file name
  1345. is specified by both the environment variable and the command line option,
  1346. the environment variable takes precedence. The file name pattern specified
  1347. can include different modifiers: ``%p``, ``%h``, and ``%m``.
  1348. Any instance of ``%p`` in that file name will be replaced by the process
  1349. ID, so that you can easily distinguish the profile output from multiple
  1350. runs.
  1351. .. code-block:: console
  1352. $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
  1353. The modifier ``%h`` can be used in scenarios where the same instrumented
  1354. binary is run in multiple different host machines dumping profile data
  1355. to a shared network based storage. The ``%h`` specifier will be substituted
  1356. with the hostname so that profiles collected from different hosts do not
  1357. clobber each other.
  1358. While the use of ``%p`` specifier can reduce the likelihood for the profiles
  1359. dumped from different processes to clobber each other, such clobbering can still
  1360. happen because of the ``pid`` re-use by the OS. Another side-effect of using
  1361. ``%p`` is that the storage requirement for raw profile data files is greatly
  1362. increased. To avoid issues like this, the ``%m`` specifier can used in the profile
  1363. name. When this specifier is used, the profiler runtime will substitute ``%m``
  1364. with a unique integer identifier associated with the instrumented binary. Additionally,
  1365. multiple raw profiles dumped from different processes that share a file system (can be
  1366. on different hosts) will be automatically merged by the profiler runtime during the
  1367. dumping. If the program links in multiple instrumented shared libraries, each library
  1368. will dump the profile data into its own profile data file (with its unique integer
  1369. id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
  1370. profile data generated by profiler runtime. The resulting merged "raw" profile data
  1371. file still needs to be converted to a different format expected by the compiler (
  1372. see step 3 below).
  1373. .. code-block:: console
  1374. $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
  1375. 3. Combine profiles from multiple runs and convert the "raw" profile format to
  1376. the input expected by clang. Use the ``merge`` command of the
  1377. ``llvm-profdata`` tool to do this.
  1378. .. code-block:: console
  1379. $ llvm-profdata merge -output=code.profdata code-*.profraw
  1380. Note that this step is necessary even when there is only one "raw" profile,
  1381. since the merge operation also changes the file format.
  1382. 4. Build the code again using the ``-fprofile-instr-use`` option to specify the
  1383. collected profile data.
  1384. .. code-block:: console
  1385. $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
  1386. You can repeat step 4 as often as you like without regenerating the
  1387. profile. As you make changes to your code, clang may no longer be able to
  1388. use the profile data. It will warn you when this happens.
  1389. Profile generation using an alternative instrumentation method can be
  1390. controlled by the GCC-compatible flags ``-fprofile-generate`` and
  1391. ``-fprofile-use``. Although these flags are semantically equivalent to
  1392. their GCC counterparts, they *do not* handle GCC-compatible profiles.
  1393. They are only meant to implement GCC's semantics with respect to
  1394. profile creation and use. Flag ``-fcs-profile-generate`` also instruments
  1395. programs using the same instrumentation method as ``-fprofile-generate``.
  1396. .. option:: -fprofile-generate[=<dirname>]
  1397. The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
  1398. an alternative instrumentation method for profile generation. When
  1399. given a directory name, it generates the profile file
  1400. ``default_%m.profraw`` in the directory named ``dirname`` if specified.
  1401. If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
  1402. will be substituted with a unique id documented in step 2 above. In other words,
  1403. with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
  1404. merging is turned on by default, so there will no longer any risk of profile
  1405. clobbering from different running processes. For example,
  1406. .. code-block:: console
  1407. $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
  1408. When ``code`` is executed, the profile will be written to the file
  1409. ``yyy/zzz/default_xxxx.profraw``.
  1410. To generate the profile data file with the compiler readable format, the
  1411. ``llvm-profdata`` tool can be used with the profile directory as the input:
  1412. .. code-block:: console
  1413. $ llvm-profdata merge -output=code.profdata yyy/zzz/
  1414. If the user wants to turn off the auto-merging feature, or simply override the
  1415. the profile dumping path specified at command line, the environment variable
  1416. ``LLVM_PROFILE_FILE`` can still be used to override
  1417. the directory and filename for the profile file at runtime.
  1418. .. option:: -fcs-profile-generate[=<dirname>]
  1419. The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use
  1420. the same instrumentation method, and generate the same profile as in the
  1421. ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is
  1422. that the instrumentation is performed after inlining so that the resulted
  1423. profile has a better context sensitive information. They cannot be used
  1424. together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags.
  1425. They are typically used in conjunction with ``-fprofile-use`` flag.
  1426. The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate``
  1427. can be merged by llvm-profdata. A use example:
  1428. .. code-block:: console
  1429. $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
  1430. $ ./code
  1431. $ llvm-profdata merge -output=code.profdata yyy/zzz/
  1432. The first few steps are the same as that in ``-fprofile-generate``
  1433. compilation. Then perform a second round of instrumentation.
  1434. .. code-block:: console
  1435. $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \
  1436. -o cs_code
  1437. $ ./cs_code
  1438. $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata
  1439. The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile
  1440. generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by
  1441. ``-fprofile-use`` compilaton.
  1442. .. code-block:: console
  1443. $ clang++ -O2 -fprofile-use=cs_code.profdata
  1444. The above command will read both profiles to the compiler at the identical
  1445. point of instrumenations.
  1446. .. option:: -fprofile-use[=<pathname>]
  1447. Without any other arguments, ``-fprofile-use`` behaves identically to
  1448. ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
  1449. profile file, it reads from that file. If ``pathname`` is a directory name,
  1450. it reads from ``pathname/default.profdata``.
  1451. Disabling Instrumentation
  1452. ^^^^^^^^^^^^^^^^^^^^^^^^^
  1453. In certain situations, it may be useful to disable profile generation or use
  1454. for specific files in a build, without affecting the main compilation flags
  1455. used for the other files in the project.
  1456. In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
  1457. ``-fno-profile-generate``) to disable profile generation, and
  1458. ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
  1459. Note that these flags should appear after the corresponding profile
  1460. flags to have an effect.
  1461. Profile remapping
  1462. ^^^^^^^^^^^^^^^^^
  1463. When the program is compiled after a change that affects many symbol names,
  1464. pre-existing profile data may no longer match the program. For example:
  1465. * switching from libstdc++ to libc++ will result in the mangled names of all
  1466. functions taking standard library types to change
  1467. * renaming a widely-used type in C++ will result in the mangled names of all
  1468. functions that have parameters involving that type to change
  1469. * moving from a 32-bit compilation to a 64-bit compilation may change the
  1470. underlying type of ``size_t`` and similar types, resulting in changes to
  1471. manglings
  1472. Clang allows use of a profile remapping file to specify that such differences
  1473. in mangled names should be ignored when matching the profile data against the
  1474. program.
  1475. .. option:: -fprofile-remapping-file=<file>
  1476. Specifies a file containing profile remapping information, that will be
  1477. used to match mangled names in the profile data to mangled names in the
  1478. program.
  1479. The profile remapping file is a text file containing lines of the form
  1480. .. code-block:: text
  1481. fragmentkind fragment1 fragment2
  1482. where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``,
  1483. indicating whether the following mangled name fragments are
  1484. <`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s,
  1485. <`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or
  1486. <`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s,
  1487. respectively.
  1488. Blank lines and lines starting with ``#`` are ignored.
  1489. For convenience, built-in <substitution>s such as ``St`` and ``Ss``
  1490. are accepted as <name>s (even though they technically are not <name>s).
  1491. For example, to specify that ``absl::string_view`` and ``std::string_view``
  1492. should be treated as equivalent when matching profile data, the following
  1493. remapping file could be used:
  1494. .. code-block:: text
  1495. # absl::string_view is considered equivalent to std::string_view
  1496. type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE
  1497. # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++
  1498. name 3std St3__1
  1499. name 3std St7__cxx11
  1500. Matching profile data using a profile remapping file is supported on a
  1501. best-effort basis. For example, information regarding indirect call targets is
  1502. currently not remapped. For best results, you are encouraged to generate new
  1503. profile data matching the updated program, or to remap the profile data
  1504. using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools.
  1505. .. note::
  1506. Profile data remapping support is currently only implemented for LLVM's
  1507. new pass manager, which can be enabled with
  1508. ``-fexperimental-new-pass-manager``.
  1509. .. note::
  1510. Profile data remapping is currently only supported for C++ mangled names
  1511. following the Itanium C++ ABI mangling scheme. This covers all C++ targets
  1512. supported by Clang other than Windows.
  1513. GCOV-based Profiling
  1514. --------------------
  1515. GCOV is a test coverage program, it helps to know how often a line of code
  1516. is executed. When instrumenting the code with ``--coverage`` option, some
  1517. counters are added for each edge linking basic blocks.
  1518. At compile time, gcno files are generated containing information about
  1519. blocks and edges between them. At runtime the counters are incremented and at
  1520. exit the counters are dumped in gcda files.
  1521. The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate
  1522. a report ``.c.gcov``.
  1523. .. option:: -fprofile-filter-files=[regexes]
  1524. Define a list of regexes separated by a semi-colon.
  1525. If a file name matches any of the regexes then the file is instrumented.
  1526. .. code-block:: console
  1527. $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c
  1528. For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files.
  1529. .. option:: -fprofile-exclude-files=[regexes]
  1530. Define a list of regexes separated by a semi-colon.
  1531. If a file name doesn't match all the regexes then the file is instrumented.
  1532. .. code-block:: console
  1533. $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c
  1534. For example, this will instrument all the files except the ones in ``/usr/include``.
  1535. If both options are used then a file is instrumented if its name matches any
  1536. of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes
  1537. from ``-fprofile-exclude-list``.
  1538. .. code-block:: console
  1539. $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \
  1540. -fprofile-filter-files="^/usr/.*$"
  1541. In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and
  1542. doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches
  1543. the exclude regex.
  1544. Controlling Debug Information
  1545. -----------------------------
  1546. Controlling Size of Debug Information
  1547. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1548. Debug info kind generated by Clang can be set by one of the flags listed
  1549. below. If multiple flags are present, the last one is used.
  1550. .. option:: -g0
  1551. Don't generate any debug info (default).
  1552. .. option:: -gline-tables-only
  1553. Generate line number tables only.
  1554. This kind of debug info allows to obtain stack traces with function names,
  1555. file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
  1556. doesn't contain any other data (e.g. description of local variables or
  1557. function parameters).
  1558. .. option:: -fstandalone-debug
  1559. Clang supports a number of optimizations to reduce the size of debug
  1560. information in the binary. They work based on the assumption that
  1561. the debug type information can be spread out over multiple
  1562. compilation units. For instance, Clang will not emit type
  1563. definitions for types that are not needed by a module and could be
  1564. replaced with a forward declaration. Further, Clang will only emit
  1565. type info for a dynamic C++ class in the module that contains the
  1566. vtable for the class.
  1567. The **-fstandalone-debug** option turns off these optimizations.
  1568. This is useful when working with 3rd-party libraries that don't come
  1569. with debug information. Note that Clang will never emit type
  1570. information for types that are not referenced at all by the program.
  1571. .. option:: -fno-standalone-debug
  1572. On Darwin **-fstandalone-debug** is enabled by default. The
  1573. **-fno-standalone-debug** option can be used to get to turn on the
  1574. vtable-based optimization described above.
  1575. .. option:: -g
  1576. Generate complete debug info.
  1577. Controlling Macro Debug Info Generation
  1578. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1579. Debug info for C preprocessor macros increases the size of debug information in
  1580. the binary. Macro debug info generated by Clang can be controlled by the flags
  1581. listed below.
  1582. .. option:: -fdebug-macro
  1583. Generate debug info for preprocessor macros. This flag is discarded when
  1584. **-g0** is enabled.
  1585. .. option:: -fno-debug-macro
  1586. Do not generate debug info for preprocessor macros (default).
  1587. Controlling Debugger "Tuning"
  1588. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1589. While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
  1590. different debuggers may know how to take advantage of different specific DWARF
  1591. features. You can "tune" the debug info for one of several different debuggers.
  1592. .. option:: -ggdb, -glldb, -gsce
  1593. Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg|
  1594. debugger, respectively. Each of these options implies **-g**. (Therefore, if
  1595. you want both **-gline-tables-only** and debugger tuning, the tuning option
  1596. must come first.)
  1597. Controlling LLVM IR Output
  1598. --------------------------
  1599. Controlling Value Names in LLVM IR
  1600. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1601. Emitting value names in LLVM IR increases the size and verbosity of the IR.
  1602. By default, value names are only emitted in assertion-enabled builds of Clang.
  1603. However, when reading IR it can be useful to re-enable the emission of value
  1604. names to improve readability.
  1605. .. option:: -fdiscard-value-names
  1606. Discard value names when generating LLVM IR.
  1607. .. option:: -fno-discard-value-names
  1608. Do not discard value names when generating LLVM IR. This option can be used
  1609. to re-enable names for release builds of Clang.
  1610. Comment Parsing Options
  1611. -----------------------
  1612. Clang parses Doxygen and non-Doxygen style documentation comments and attaches
  1613. them to the appropriate declaration nodes. By default, it only parses
  1614. Doxygen-style comments and ignores ordinary comments starting with ``//`` and
  1615. ``/*``.
  1616. .. option:: -Wdocumentation
  1617. Emit warnings about use of documentation comments. This warning group is off
  1618. by default.
  1619. This includes checking that ``\param`` commands name parameters that actually
  1620. present in the function signature, checking that ``\returns`` is used only on
  1621. functions that actually return a value etc.
  1622. .. option:: -Wno-documentation-unknown-command
  1623. Don't warn when encountering an unknown Doxygen command.
  1624. .. option:: -fparse-all-comments
  1625. Parse all comments as documentation comments (including ordinary comments
  1626. starting with ``//`` and ``/*``).
  1627. .. option:: -fcomment-block-commands=[commands]
  1628. Define custom documentation commands as block commands. This allows Clang to
  1629. construct the correct AST for these custom commands, and silences warnings
  1630. about unknown commands. Several commands must be separated by a comma
  1631. *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
  1632. custom commands ``\foo`` and ``\bar``.
  1633. It is also possible to use ``-fcomment-block-commands`` several times; e.g.
  1634. ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
  1635. as above.
  1636. .. _c:
  1637. C Language Features
  1638. ===================
  1639. The support for standard C in clang is feature-complete except for the
  1640. C99 floating-point pragmas.
  1641. Extensions supported by clang
  1642. -----------------------------
  1643. See :doc:`LanguageExtensions`.
  1644. Differences between various standard modes
  1645. ------------------------------------------
  1646. clang supports the -std option, which changes what language mode clang
  1647. uses. The supported modes for C are c89, gnu89, c99, gnu99, c11, gnu11,
  1648. c17, gnu17, and various aliases for those modes. If no -std option is
  1649. specified, clang defaults to gnu11 mode. Many C99 and C11 features are
  1650. supported in earlier modes as a conforming extension, with a warning. Use
  1651. ``-pedantic-errors`` to request an error if a feature from a later standard
  1652. revision is used in an earlier mode.
  1653. Differences between all ``c*`` and ``gnu*`` modes:
  1654. - ``c*`` modes define "``__STRICT_ANSI__``".
  1655. - Target-specific defines not prefixed by underscores, like "linux",
  1656. are defined in ``gnu*`` modes.
  1657. - Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
  1658. the -trigraphs option.
  1659. - The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
  1660. the variants "``__asm__``" and "``__typeof__``" are recognized in all
  1661. modes.
  1662. - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
  1663. on some platforms; it can be enabled in any mode with the "-fblocks"
  1664. option.
  1665. - Arrays that are VLA's according to the standard, but which can be
  1666. constant folded by the frontend are treated as fixed size arrays.
  1667. This occurs for things like "int X[(1, 2)];", which is technically a
  1668. VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
  1669. Differences between ``*89`` and ``*99`` modes:
  1670. - The ``*99`` modes default to implementing "inline" as specified in C99,
  1671. while the ``*89`` modes implement the GNU version. This can be
  1672. overridden for individual functions with the ``__gnu_inline__``
  1673. attribute.
  1674. - Digraphs are not recognized in c89 mode.
  1675. - The scope of names defined inside a "for", "if", "switch", "while",
  1676. or "do" statement is different. (example: "``if ((struct x {int
  1677. x;}*)0) {}``".)
  1678. - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
  1679. - "inline" is not recognized as a keyword in c89 mode.
  1680. - "restrict" is not recognized as a keyword in ``*89`` modes.
  1681. - Commas are allowed in integer constant expressions in ``*99`` modes.
  1682. - Arrays which are not lvalues are not implicitly promoted to pointers
  1683. in ``*89`` modes.
  1684. - Some warnings are different.
  1685. Differences between ``*99`` and ``*11`` modes:
  1686. - Warnings for use of C11 features are disabled.
  1687. - ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
  1688. Differences between ``*11`` and ``*17`` modes:
  1689. - ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.
  1690. GCC extensions not implemented yet
  1691. ----------------------------------
  1692. clang tries to be compatible with gcc as much as possible, but some gcc
  1693. extensions are not implemented yet:
  1694. - clang does not support decimal floating point types (``_Decimal32`` and
  1695. friends) or fixed-point types (``_Fract`` and friends); nobody has
  1696. expressed interest in these features yet, so it's hard to say when
  1697. they will be implemented.
  1698. - clang does not support nested functions; this is a complex feature
  1699. which is infrequently used, so it is unlikely to be implemented
  1700. anytime soon. In C++11 it can be emulated by assigning lambda
  1701. functions to local variables, e.g:
  1702. .. code-block:: cpp
  1703. auto const local_function = [&](int parameter) {
  1704. // Do something
  1705. };
  1706. ...
  1707. local_function(1);
  1708. - clang only supports global register variables when the register specified
  1709. is non-allocatable (e.g. the stack pointer). Support for general global
  1710. register variables is unlikely to be implemented soon because it requires
  1711. additional LLVM backend support.
  1712. - clang does not support static initialization of flexible array
  1713. members. This appears to be a rarely used extension, but could be
  1714. implemented pending user demand.
  1715. - clang does not support
  1716. ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
  1717. used rarely, but in some potentially interesting places, like the
  1718. glibc headers, so it may be implemented pending user demand. Note
  1719. that because clang pretends to be like GCC 4.2, and this extension
  1720. was introduced in 4.3, the glibc headers will not try to use this
  1721. extension with clang at the moment.
  1722. - clang does not support the gcc extension for forward-declaring
  1723. function parameters; this has not shown up in any real-world code
  1724. yet, though, so it might never be implemented.
  1725. This is not a complete list; if you find an unsupported extension
  1726. missing from this list, please send an e-mail to cfe-dev. This list
  1727. currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
  1728. list does not include bugs in mostly-implemented features; please see
  1729. the `bug
  1730. tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
  1731. for known existing bugs (FIXME: Is there a section for bug-reporting
  1732. guidelines somewhere?).
  1733. Intentionally unsupported GCC extensions
  1734. ----------------------------------------
  1735. - clang does not support the gcc extension that allows variable-length
  1736. arrays in structures. This is for a few reasons: one, it is tricky to
  1737. implement, two, the extension is completely undocumented, and three,
  1738. the extension appears to be rarely used. Note that clang *does*
  1739. support flexible array members (arrays with a zero or unspecified
  1740. size at the end of a structure).
  1741. - clang does not have an equivalent to gcc's "fold"; this means that
  1742. clang doesn't accept some constructs gcc might accept in contexts
  1743. where a constant expression is required, like "x-x" where x is a
  1744. variable.
  1745. - clang does not support ``__builtin_apply`` and friends; this extension
  1746. is extremely obscure and difficult to implement reliably.
  1747. .. _c_ms:
  1748. Microsoft extensions
  1749. --------------------
  1750. clang has support for many extensions from Microsoft Visual C++. To enable these
  1751. extensions, use the ``-fms-extensions`` command-line option. This is the default
  1752. for Windows targets. Clang does not implement every pragma or declspec provided
  1753. by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
  1754. comment(lib)`` are well supported.
  1755. clang has a ``-fms-compatibility`` flag that makes clang accept enough
  1756. invalid C++ to be able to parse most Microsoft headers. For example, it
  1757. allows `unqualified lookup of dependent base class members
  1758. <https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
  1759. a common compatibility issue with clang. This flag is enabled by default
  1760. for Windows targets.
  1761. ``-fdelayed-template-parsing`` lets clang delay parsing of function template
  1762. definitions until the end of a translation unit. This flag is enabled by
  1763. default for Windows targets.
  1764. For compatibility with existing code that compiles with MSVC, clang defines the
  1765. ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
  1766. and 180000000 respectively, making clang look like an early release of Visual
  1767. C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It
  1768. accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
  1769. compatibility version makes clang behave more like that version of MSVC. For
  1770. example, ``-fms-compatibility-version=19`` will enable C++14 features and define
  1771. ``char16_t`` and ``char32_t`` as builtin types.
  1772. .. _cxx:
  1773. C++ Language Features
  1774. =====================
  1775. clang fully implements all of standard C++98 except for exported
  1776. templates (which were removed in C++11), and all of standard C++11
  1777. and the current draft standard for C++1y.
  1778. Controlling implementation limits
  1779. ---------------------------------
  1780. .. option:: -fbracket-depth=N
  1781. Sets the limit for nested parentheses, brackets, and braces to N. The
  1782. default is 256.
  1783. .. option:: -fconstexpr-depth=N
  1784. Sets the limit for recursive constexpr function invocations to N. The
  1785. default is 512.
  1786. .. option:: -fconstexpr-steps=N
  1787. Sets the limit for the number of full-expressions evaluated in a single
  1788. constant expression evaluation. The default is 1048576.
  1789. .. option:: -ftemplate-depth=N
  1790. Sets the limit for recursively nested template instantiations to N. The
  1791. default is 1024.
  1792. .. option:: -foperator-arrow-depth=N
  1793. Sets the limit for iterative calls to 'operator->' functions to N. The
  1794. default is 256.
  1795. .. _objc:
  1796. Objective-C Language Features
  1797. =============================
  1798. .. _objcxx:
  1799. Objective-C++ Language Features
  1800. ===============================
  1801. .. _openmp:
  1802. OpenMP Features
  1803. ===============
  1804. Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport`
  1805. for additional details.
  1806. Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
  1807. `-fno-openmp`.
  1808. Use `-fopenmp-simd` to enable OpenMP simd features only, without linking
  1809. the runtime library; for combined constructs
  1810. (e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses
  1811. will be ignored. This can be disabled with `-fno-openmp-simd`.
  1812. Controlling implementation limits
  1813. ---------------------------------
  1814. .. option:: -fopenmp-use-tls
  1815. Controls code generation for OpenMP threadprivate variables. In presence of
  1816. this option all threadprivate variables are generated the same way as thread
  1817. local variables, using TLS support. If `-fno-openmp-use-tls`
  1818. is provided or target does not support TLS, code generation for threadprivate
  1819. variables relies on OpenMP runtime library.
  1820. .. _opencl:
  1821. OpenCL Features
  1822. ===============
  1823. Clang can be used to compile OpenCL kernels for execution on a device
  1824. (e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMD or
  1825. Nvidia targets) that can be uploaded to run directly on a device (e.g. using
  1826. `clCreateProgramWithBinary
  1827. <https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
  1828. into generic bitcode files loadable into other toolchains.
  1829. Compiling to a binary using the default target from the installation can be done
  1830. as follows:
  1831. .. code-block:: console
  1832. $ echo "kernel void k(){}" > test.cl
  1833. $ clang test.cl
  1834. Compiling for a specific target can be done by specifying the triple corresponding
  1835. to the target, for example:
  1836. .. code-block:: console
  1837. $ clang -target nvptx64-unknown-unknown test.cl
  1838. $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
  1839. Compiling to bitcode can be done as follows:
  1840. .. code-block:: console
  1841. $ clang -c -emit-llvm test.cl
  1842. This will produce a generic test.bc file that can be used in vendor toolchains
  1843. to perform machine code generation.
  1844. Clang currently supports OpenCL C language standards up to v2.0. Starting from
  1845. clang 9 a C++ mode is available for OpenCL (see :ref:`C++ for OpenCL <opencl_cpp>`).
  1846. OpenCL Specific Options
  1847. -----------------------
  1848. Most of the OpenCL build options from `the specification v2.0 section 5.8.4
  1849. <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
  1850. Examples:
  1851. .. code-block:: console
  1852. $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
  1853. Some extra options are available to support special OpenCL features.
  1854. .. option:: -finclude-default-header
  1855. Loads standard includes during compilations. By default OpenCL headers are not
  1856. loaded and therefore standard library includes are not available. To load them
  1857. automatically a flag has been added to the frontend (see also :ref:`the section
  1858. on the OpenCL Header <opencl_header>`):
  1859. .. code-block:: console
  1860. $ clang -Xclang -finclude-default-header test.cl
  1861. Alternatively ``-include`` or ``-I`` followed by the path to the header location
  1862. can be given manually.
  1863. .. code-block:: console
  1864. $ clang -I<path to clang>/lib/Headers/opencl-c.h test.cl
  1865. In this case the kernel code should contain ``#include <opencl-c.h>`` just as a
  1866. regular C include.
  1867. .. _opencl_cl_ext:
  1868. .. option:: -cl-ext
  1869. Disables support of OpenCL extensions. All OpenCL targets provide a list
  1870. of extensions that they support. Clang allows to amend this using the ``-cl-ext``
  1871. flag with a comma-separated list of extensions prefixed with ``'+'`` or ``'-'``.
  1872. The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where extensions
  1873. can be either one of `the OpenCL specification extensions
  1874. <https://www.khronos.org/registry/cl/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
  1875. or any known vendor extension. Alternatively, ``'all'`` can be used to enable
  1876. or disable all known extensions.
  1877. Example disabling double support for the 64-bit SPIR target:
  1878. .. code-block:: console
  1879. $ clang -cc1 -triple spir64-unknown-unknown -cl-ext=-cl_khr_fp64 test.cl
  1880. Enabling all extensions except double support in R600 AMD GPU can be done using:
  1881. .. code-block:: console
  1882. $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl
  1883. .. _opencl_fake_address_space_map:
  1884. .. option:: -ffake-address-space-map
  1885. Overrides the target address space map with a fake map.
  1886. This allows adding explicit address space IDs to the bitcode for non-segmented
  1887. memory architectures that don't have separate IDs for each of the OpenCL
  1888. logical address spaces by default. Passing ``-ffake-address-space-map`` will
  1889. add/override address spaces of the target compiled for with the following values:
  1890. ``1-global``, ``2-constant``, ``3-local``, ``4-generic``. The private address
  1891. space is represented by the absence of an address space attribute in the IR (see
  1892. also :ref:`the section on the address space attribute <opencl_addrsp>`).
  1893. .. code-block:: console
  1894. $ clang -ffake-address-space-map test.cl
  1895. Some other flags used for the compilation for C can also be passed while
  1896. compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
  1897. OpenCL Targets
  1898. --------------
  1899. OpenCL targets are derived from the regular Clang target classes. The OpenCL
  1900. specific parts of the target representation provide address space mapping as
  1901. well as a set of supported extensions.
  1902. Specific Targets
  1903. ^^^^^^^^^^^^^^^^
  1904. There is a set of concrete HW architectures that OpenCL can be compiled for.
  1905. - For AMD target:
  1906. .. code-block:: console
  1907. $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
  1908. - For Nvidia architectures:
  1909. .. code-block:: console
  1910. $ clang -target nvptx64-unknown-unknown test.cl
  1911. Generic Targets
  1912. ^^^^^^^^^^^^^^^
  1913. - SPIR is available as a generic target to allow portable bitcode to be produced
  1914. that can be used across GPU toolchains. The implementation follows `the SPIR
  1915. specification <https://www.khronos.org/spir>`_. There are two flavors
  1916. available for 32 and 64 bits.
  1917. .. code-block:: console
  1918. $ clang -target spir-unknown-unknown test.cl
  1919. $ clang -target spir64-unknown-unknown test.cl
  1920. All known OpenCL extensions are supported in the SPIR targets. Clang will
  1921. generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and SPIR v2.0
  1922. for OpenCL v2.0.
  1923. - x86 is used by some implementations that are x86 compatible and currently
  1924. remains for backwards compatibility (with older implementations prior to
  1925. SPIR target support). For "non-SPMD" targets which cannot spawn multiple
  1926. work-items on the fly using hardware, which covers practically all non-GPU
  1927. devices such as CPUs and DSPs, additional processing is needed for the kernels
  1928. to support multiple work-item execution. For this, a 3rd party toolchain,
  1929. such as for example `POCL <http://portablecl.org/>`_, can be used.
  1930. This target does not support multiple memory segments and, therefore, the fake
  1931. address space map can be added using the :ref:`-ffake-address-space-map
  1932. <opencl_fake_address_space_map>` flag.
  1933. .. _opencl_header:
  1934. OpenCL Header
  1935. -------------
  1936. By default Clang will not include standard headers and therefore OpenCL builtin
  1937. functions and some types (i.e. vectors) are unknown. The default CL header is,
  1938. however, provided in the Clang installation and can be enabled by passing the
  1939. ``-finclude-default-header`` flag to the Clang frontend.
  1940. .. code-block:: console
  1941. $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
  1942. $ clang -Xclang -finclude-default-header -cl-std=CL2.0 test.cl
  1943. Because the header is very large and long to parse, PCH (:doc:`PCHInternals`)
  1944. and modules (:doc:`Modules`) are used internally to improve the compilation
  1945. speed.
  1946. To enable modules for OpenCL:
  1947. .. code-block:: console
  1948. $ clang -target spir-unknown-unknown -c -emit-llvm -Xclang -finclude-default-header -fmodules -fimplicit-module-maps -fmodules-cache-path=<path to the generated module> test.cl
  1949. OpenCL Extensions
  1950. -----------------
  1951. All of the ``cl_khr_*`` extensions from `the official OpenCL specification
  1952. <https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
  1953. up to and including version 2.0 are available and set per target depending on the
  1954. support available in the specific architecture.
  1955. It is possible to alter the default extensions setting per target using
  1956. ``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
  1957. Vendor extensions can be added flexibly by declaring the list of types and
  1958. functions associated with each extensions enclosed within the following
  1959. compiler pragma directives:
  1960. .. code-block:: c
  1961. #pragma OPENCL EXTENSION the_new_extension_name : begin
  1962. // declare types and functions associated with the extension here
  1963. #pragma OPENCL EXTENSION the_new_extension_name : end
  1964. For example, parsing the following code adds ``my_t`` type and ``my_func``
  1965. function to the custom ``my_ext`` extension.
  1966. .. code-block:: c
  1967. #pragma OPENCL EXTENSION my_ext : begin
  1968. typedef struct{
  1969. int a;
  1970. }my_t;
  1971. void my_func(my_t);
  1972. #pragma OPENCL EXTENSION my_ext : end
  1973. Declaring the same types in different vendor extensions is disallowed.
  1974. OpenCL Metadata
  1975. ---------------
  1976. Clang uses metadata to provide additional OpenCL semantics in IR needed for
  1977. backends and OpenCL runtime.
  1978. Each kernel will have function metadata attached to it, specifying the arguments.
  1979. Kernel argument metadata is used to provide source level information for querying
  1980. at runtime, for example using the `clGetKernelArgInfo
  1981. <https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf#167>`_
  1982. call.
  1983. Note that ``-cl-kernel-arg-info`` enables more information about the original CL
  1984. code to be added e.g. kernel parameter names will appear in the OpenCL metadata
  1985. along with other information.
  1986. The IDs used to encode the OpenCL's logical address spaces in the argument info
  1987. metadata follows the SPIR address space mapping as defined in the SPIR
  1988. specification `section 2.2
  1989. <https://www.khronos.org/registry/spir/specs/spir_spec-2.0.pdf#18>`_
  1990. OpenCL-Specific Attributes
  1991. --------------------------
  1992. OpenCL support in Clang contains a set of attribute taken directly from the
  1993. specification as well as additional attributes.
  1994. See also :doc:`AttributeReference`.
  1995. nosvm
  1996. ^^^^^
  1997. Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
  1998. does not have any effect on the IR. For more details reffer to the specification
  1999. `section 6.7.2
  2000. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
  2001. opencl_unroll_hint
  2002. ^^^^^^^^^^^^^^^^^^
  2003. The implementation of this feature mirrors the unroll hint for C.
  2004. More details on the syntax can be found in the specification
  2005. `section 6.11.5
  2006. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
  2007. convergent
  2008. ^^^^^^^^^^
  2009. To make sure no invalid optimizations occur for single program multiple data
  2010. (SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
  2011. can be used for special functions that have cross work item semantics.
  2012. An example is the subgroup operations such as `intel_sub_group_shuffle
  2013. <https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
  2014. .. code-block:: c
  2015. // Define custom my_sub_group_shuffle(data, c)
  2016. // that makes use of intel_sub_group_shuffle
  2017. r1 = ...
  2018. if (r0) r1 = computeA();
  2019. // Shuffle data from r1 into r3
  2020. // of threads id r2.
  2021. r3 = my_sub_group_shuffle(r1, r2);
  2022. if (r0) r3 = computeB();
  2023. with non-SPMD semantics this is optimized to the following equivalent code:
  2024. .. code-block:: c
  2025. r1 = ...
  2026. if (!r0)
  2027. // Incorrect functionality! The data in r1
  2028. // have not been computed by all threads yet.
  2029. r3 = my_sub_group_shuffle(r1, r2);
  2030. else {
  2031. r1 = computeA();
  2032. r3 = my_sub_group_shuffle(r1, r2);
  2033. r3 = computeB();
  2034. }
  2035. Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
  2036. would prevent this:
  2037. .. code-block:: c
  2038. my_sub_group_shuffle() __attribute__((convergent));
  2039. Using ``convergent`` guarantees correct execution by keeping CFG equivalence
  2040. wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
  2041. node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
  2042. respect to ``Ni`` remain the same in both ``G`` and ``G´``.
  2043. noduplicate
  2044. ^^^^^^^^^^^
  2045. ``noduplicate`` is more restrictive with respect to optimizations than
  2046. ``convergent`` because a convergent function only preserves CFG equivalence.
  2047. This allows some optimizations to happen as long as the control flow remains
  2048. unmodified.
  2049. .. code-block:: c
  2050. for (int i=0; i<4; i++)
  2051. my_sub_group_shuffle()
  2052. can be modified to:
  2053. .. code-block:: c
  2054. my_sub_group_shuffle();
  2055. my_sub_group_shuffle();
  2056. my_sub_group_shuffle();
  2057. my_sub_group_shuffle();
  2058. while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
  2059. have the same safe semantics of CFG as ``convergent`` and can cause changes in
  2060. CFG that modify semantics of the original program.
  2061. ``noduplicate`` is kept for backwards compatibility only and it considered to be
  2062. deprecated for future uses.
  2063. .. _opencl_addrsp:
  2064. address_space
  2065. ^^^^^^^^^^^^^
  2066. Clang has arbitrary address space support using the ``address_space(N)``
  2067. attribute, where ``N`` is an integer number in the range ``0`` to ``16777215``
  2068. (``0xffffffu``).
  2069. An OpenCL implementation provides a list of standard address spaces using
  2070. keywords: ``private``, ``local``, ``global``, and ``generic``. In the AST and
  2071. in the IR local, global, or generic will be represented by the address space
  2072. attribute with the corresponding unique number. Note that private does not have
  2073. any corresponding attribute added and, therefore, is represented by the absence
  2074. of an address space number. The specific IDs for an address space do not have to
  2075. match between the AST and the IR. Typically in the AST address space numbers
  2076. represent logical segments while in the IR they represent physical segments.
  2077. Therefore, machines with flat memory segments can map all AST address space
  2078. numbers to the same physical segment ID or skip address space attribute
  2079. completely while generating the IR. However, if the address space information
  2080. is needed by the IR passes e.g. to improve alias analysis, it is recommended
  2081. to keep it and only lower to reflect physical memory segments in the late
  2082. machine passes.
  2083. OpenCL builtins
  2084. ---------------
  2085. There are some standard OpenCL functions that are implemented as Clang builtins:
  2086. - All pipe functions from `section 6.13.16.2/6.13.16.3
  2087. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#160>`_ of
  2088. the OpenCL v2.0 kernel language specification. `
  2089. - Address space qualifier conversion functions ``to_global``/``to_local``/``to_private``
  2090. from `section 6.13.9
  2091. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#101>`_.
  2092. - All the ``enqueue_kernel`` functions from `section 6.13.17.1
  2093. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#164>`_ and
  2094. enqueue query functions from `section 6.13.17.5
  2095. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#171>`_.
  2096. .. _opencl_cpp:
  2097. C++ for OpenCL
  2098. --------------
  2099. Starting from clang 9 kernel code can contain C++17 features: classes, templates,
  2100. function overloading, type deduction, etc. Please note that this is not an
  2101. implementation of `OpenCL C++
  2102. <https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and
  2103. there is no plan to support it in clang in any new releases in the near future.
  2104. For detailed information about restrictions to allowed C++ features please
  2105. refer to :doc:`LanguageExtensions`.
  2106. Since C++ features are to be used on top of OpenCL C functionality, all existing
  2107. restrictions from OpenCL C v2.0 will inherently apply. All OpenCL C builtin types
  2108. and function libraries are supported and can be used in this mode.
  2109. To enable the C++ for OpenCL mode, pass one of following command line options when
  2110. compiling ``.cl`` file ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-std=clc++`` or
  2111. ``-std=CLC++``.
  2112. .. code-block:: c++
  2113. template<class T> T add( T x, T y )
  2114. {
  2115. return x + y;
  2116. }
  2117. __kernel void test( __global float* a, __global float* b)
  2118. {
  2119. auto index = get_global_id(0);
  2120. a[index] = add(b[index], b[index+1]);
  2121. }
  2122. .. code-block:: console
  2123. clang -cl-std=clc++ test.cl
  2124. .. _target_features:
  2125. Target-Specific Features and Limitations
  2126. ========================================
  2127. CPU Architectures Features and Limitations
  2128. ------------------------------------------
  2129. X86
  2130. ^^^
  2131. The support for X86 (both 32-bit and 64-bit) is considered stable on
  2132. Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested
  2133. to correctly compile many large C, C++, Objective-C, and Objective-C++
  2134. codebases.
  2135. On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
  2136. Microsoft x64 calling convention. You might need to tweak
  2137. ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
  2138. For the X86 target, clang supports the `-m16` command line
  2139. argument which enables 16-bit code output. This is broadly similar to
  2140. using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
  2141. and the ABI remains 32-bit but the assembler emits instructions
  2142. appropriate for a CPU running in 16-bit mode, with address-size and
  2143. operand-size prefixes to enable 32-bit addressing and operations.
  2144. ARM
  2145. ^^^
  2146. The support for ARM (specifically ARMv6 and ARMv7) is considered stable
  2147. on Darwin (iOS): it has been tested to correctly compile many large C,
  2148. C++, Objective-C, and Objective-C++ codebases. Clang only supports a
  2149. limited number of ARM architectures. It does not yet fully support
  2150. ARMv5, for example.
  2151. PowerPC
  2152. ^^^^^^^
  2153. The support for PowerPC (especially PowerPC64) is considered stable
  2154. on Linux and FreeBSD: it has been tested to correctly compile many
  2155. large C and C++ codebases. PowerPC (32bit) is still missing certain
  2156. features (e.g. PIC code on ELF platforms).
  2157. Other platforms
  2158. ^^^^^^^^^^^^^^^
  2159. clang currently contains some support for other architectures (e.g. Sparc);
  2160. however, significant pieces of code generation are still missing, and they
  2161. haven't undergone significant testing.
  2162. clang contains limited support for the MSP430 embedded processor, but
  2163. both the clang support and the LLVM backend support are highly
  2164. experimental.
  2165. Other platforms are completely unsupported at the moment. Adding the
  2166. minimal support needed for parsing and semantic analysis on a new
  2167. platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
  2168. tree. This level of support is also sufficient for conversion to LLVM IR
  2169. for simple programs. Proper support for conversion to LLVM IR requires
  2170. adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
  2171. change soon, though. Generating assembly requires a suitable LLVM
  2172. backend.
  2173. Operating System Features and Limitations
  2174. -----------------------------------------
  2175. Darwin (macOS)
  2176. ^^^^^^^^^^^^^^
  2177. Thread Sanitizer is not supported.
  2178. Windows
  2179. ^^^^^^^
  2180. Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
  2181. platforms.
  2182. See also :ref:`Microsoft Extensions <c_ms>`.
  2183. Cygwin
  2184. """"""
  2185. Clang works on Cygwin-1.7.
  2186. MinGW32
  2187. """""""
  2188. Clang works on some mingw32 distributions. Clang assumes directories as
  2189. below;
  2190. - ``C:/mingw/include``
  2191. - ``C:/mingw/lib``
  2192. - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
  2193. On MSYS, a few tests might fail.
  2194. MinGW-w64
  2195. """""""""
  2196. For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
  2197. assumes as below;
  2198. - ``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)``
  2199. - ``some_directory/bin/gcc.exe``
  2200. - ``some_directory/bin/clang.exe``
  2201. - ``some_directory/bin/clang++.exe``
  2202. - ``some_directory/bin/../include/c++/GCC_version``
  2203. - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
  2204. - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
  2205. - ``some_directory/bin/../include/c++/GCC_version/backward``
  2206. - ``some_directory/bin/../x86_64-w64-mingw32/include``
  2207. - ``some_directory/bin/../i686-w64-mingw32/include``
  2208. - ``some_directory/bin/../include``
  2209. This directory layout is standard for any toolchain you will find on the
  2210. official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
  2211. Clang expects the GCC executable "gcc.exe" compiled for
  2212. ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
  2213. `Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
  2214. ``x86_64-w64-mingw32``.
  2215. .. _clang-cl:
  2216. clang-cl
  2217. ========
  2218. clang-cl is an alternative command-line interface to Clang, designed for
  2219. compatibility with the Visual C++ compiler, cl.exe.
  2220. To enable clang-cl to find system headers, libraries, and the linker when run
  2221. from the command-line, it should be executed inside a Visual Studio Native Tools
  2222. Command Prompt or a regular Command Prompt where the environment has been set
  2223. up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
  2224. clang-cl can also be used from inside Visual Studio by selecting the LLVM
  2225. Platform Toolset. The toolset is not part of the installer, but may be installed
  2226. separately from the
  2227. `Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_.
  2228. To use the toolset, select a project in Solution Explorer, open its Property
  2229. Page (Alt+F7), and in the "General" section of "Configuration Properties"
  2230. change "Platform Toolset" to LLVM. Doing so enables an additional Property
  2231. Page for selecting the clang-cl executable to use for builds.
  2232. To use the toolset with MSBuild directly, invoke it with e.g.
  2233. ``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain
  2234. without modifying your project files.
  2235. It's also possible to point MSBuild at clang-cl without changing toolset by
  2236. passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.
  2237. When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:
  2238. ::
  2239. cmake -G"Visual Studio 15 2017" -T LLVM ..
  2240. When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and
  2241. ``CMAKE_CXX_COMPILER`` variables to clang-cl:
  2242. ::
  2243. cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"
  2244. -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..
  2245. Command-Line Options
  2246. --------------------
  2247. To be compatible with cl.exe, clang-cl supports most of the same command-line
  2248. options. Those options can start with either ``/`` or ``-``. It also supports
  2249. some of Clang's core options, such as the ``-W`` options.
  2250. Options that are known to clang-cl, but not currently supported, are ignored
  2251. with a warning. For example:
  2252. ::
  2253. clang-cl.exe: warning: argument unused during compilation: '/AI'
  2254. To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
  2255. Options that are not known to clang-cl will be ignored by default. Use the
  2256. ``-Werror=unknown-argument`` option in order to treat them as errors. If these
  2257. options are spelled with a leading ``/``, they will be mistaken for a filename:
  2258. ::
  2259. clang-cl.exe: error: no such file or directory: '/foobar'
  2260. Please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=clang&component=Driver>`_
  2261. for any valid cl.exe flags that clang-cl does not understand.
  2262. Execute ``clang-cl /?`` to see a list of supported options:
  2263. ::
  2264. CL.EXE COMPATIBILITY OPTIONS:
  2265. /? Display available options
  2266. /arch:<value> Set architecture for code generation
  2267. /Brepro- Emit an object file which cannot be reproduced over time
  2268. /Brepro Emit an object file which can be reproduced over time
  2269. /clang:<arg> Pass <arg> to the clang driver
  2270. /C Don't discard comments when preprocessing
  2271. /c Compile only
  2272. /d1PP Retain macro definitions in /E mode
  2273. /d1reportAllClassLayout Dump record layout information
  2274. /diagnostics:caret Enable caret and column diagnostics (on by default)
  2275. /diagnostics:classic Disable column and caret diagnostics
  2276. /diagnostics:column Disable caret diagnostics but keep column info
  2277. /D <macro[=value]> Define macro
  2278. /EH<value> Exception handling model
  2279. /EP Disable linemarker output and preprocess to stdout
  2280. /execution-charset:<value>
  2281. Runtime encoding, supports only UTF-8
  2282. /E Preprocess to stdout
  2283. /fallback Fall back to cl.exe if clang-cl fails to compile
  2284. /FA Output assembly code file during compilation
  2285. /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
  2286. /Fe<file or directory> Set output executable file or directory (ends in / or \)
  2287. /FI <value> Include file before parsing
  2288. /Fi<file> Set preprocess output file name (with /P)
  2289. /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
  2290. /fp:except-
  2291. /fp:except
  2292. /fp:fast
  2293. /fp:precise
  2294. /fp:strict
  2295. /Fp<filename> Set pch filename (with /Yc and /Yu)
  2296. /GA Assume thread-local variables are defined in the executable
  2297. /Gd Set __cdecl as a default calling convention
  2298. /GF- Disable string pooling
  2299. /GF Enable string pooling (default)
  2300. /GR- Disable emission of RTTI data
  2301. /Gregcall Set __regcall as a default calling convention
  2302. /GR Enable emission of RTTI data
  2303. /Gr Set __fastcall as a default calling convention
  2304. /GS- Disable buffer security check
  2305. /GS Enable buffer security check (default)
  2306. /Gs Use stack probes (default)
  2307. /Gs<value> Set stack probe size (default 4096)
  2308. /guard:<value> Enable Control Flow Guard with /guard:cf,
  2309. or only the table with /guard:cf,nochecks
  2310. /Gv Set __vectorcall as a default calling convention
  2311. /Gw- Don't put each data item in its own section
  2312. /Gw Put each data item in its own section
  2313. /GX- Disable exception handling
  2314. /GX Enable exception handling
  2315. /Gy- Don't put each function in its own section (default)
  2316. /Gy Put each function in its own section
  2317. /Gz Set __stdcall as a default calling convention
  2318. /help Display available options
  2319. /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
  2320. /I <dir> Add directory to include search path
  2321. /J Make char type unsigned
  2322. /LDd Create debug DLL
  2323. /LD Create DLL
  2324. /link <options> Forward options to the linker
  2325. /MDd Use DLL debug run-time
  2326. /MD Use DLL run-time
  2327. /MTd Use static debug run-time
  2328. /MT Use static run-time
  2329. /O0 Disable optimization
  2330. /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy)
  2331. /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy)
  2332. /Ob0 Disable function inlining
  2333. /Ob1 Only inline functions which are (explicitly or implicitly) marked inline
  2334. /Ob2 Inline functions as deemed beneficial by the compiler
  2335. /Od Disable optimization
  2336. /Og No effect
  2337. /Oi- Disable use of builtin functions
  2338. /Oi Enable use of builtin functions
  2339. /Os Optimize for size
  2340. /Ot Optimize for speed
  2341. /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead
  2342. /Oy- Disable frame pointer omission (x86 only, default)
  2343. /Oy Enable frame pointer omission (x86 only)
  2344. /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-'
  2345. /o <file or directory> Set output file or directory (ends in / or \)
  2346. /P Preprocess to file
  2347. /Qvec- Disable the loop vectorization passes
  2348. /Qvec Enable the loop vectorization passes
  2349. /showFilenames- Don't print the name of each compiled file (default)
  2350. /showFilenames Print the name of each compiled file
  2351. /showIncludes Print info about included files to stderr
  2352. /source-charset:<value> Source encoding, supports only UTF-8
  2353. /std:<value> Language standard to compile for
  2354. /TC Treat all source files as C
  2355. /Tc <filename> Specify a C source file
  2356. /TP Treat all source files as C++
  2357. /Tp <filename> Specify a C++ source file
  2358. /utf-8 Set source and runtime encoding to UTF-8 (default)
  2359. /U <macro> Undefine macro
  2360. /vd<value> Control vtordisp placement
  2361. /vmb Use a best-case representation method for member pointers
  2362. /vmg Use a most-general representation for member pointers
  2363. /vmm Set the default most-general representation to multiple inheritance
  2364. /vms Set the default most-general representation to single inheritance
  2365. /vmv Set the default most-general representation to virtual inheritance
  2366. /volatile:iso Volatile loads and stores have standard semantics
  2367. /volatile:ms Volatile loads and stores have acquire and release semantics
  2368. /W0 Disable all warnings
  2369. /W1 Enable -Wall
  2370. /W2 Enable -Wall
  2371. /W3 Enable -Wall
  2372. /W4 Enable -Wall and -Wextra
  2373. /Wall Enable -Weverything
  2374. /WX- Do not treat warnings as errors
  2375. /WX Treat warnings as errors
  2376. /w Disable all warnings
  2377. /X Don't add %INCLUDE% to the include search path
  2378. /Y- Disable precompiled headers, overrides /Yc and /Yu
  2379. /Yc<filename> Generate a pch file for all code up to and including <filename>
  2380. /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
  2381. /Z7 Enable CodeView debug information in object files
  2382. /Zc:char8_t Enable C++2a char8_t type
  2383. /Zc:char8_t- Disable C++2a char8_t type
  2384. /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes
  2385. /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default)
  2386. /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
  2387. /Zc:sizedDealloc Enable C++14 sized global deallocation functions
  2388. /Zc:strictStrings Treat string literals as const
  2389. /Zc:threadSafeInit- Disable thread-safe initialization of static variables
  2390. /Zc:threadSafeInit Enable thread-safe initialization of static variables
  2391. /Zc:trigraphs- Disable trigraphs (default)
  2392. /Zc:trigraphs Enable trigraphs
  2393. /Zc:twoPhase- Disable two-phase name lookup in templates
  2394. /Zc:twoPhase Enable two-phase name lookup in templates
  2395. /Zd Emit debug line number tables only
  2396. /Zi Alias for /Z7. Does not produce PDBs.
  2397. /Zl Don't mention any default libraries in the object file
  2398. /Zp Set the default maximum struct packing alignment to 1
  2399. /Zp<value> Specify the default maximum struct packing alignment
  2400. /Zs Syntax-check only
  2401. OPTIONS:
  2402. -### Print (but do not run) the commands to run for this compilation
  2403. --analyze Run the static analyzer
  2404. -faddrsig Emit an address-significance table
  2405. -fansi-escape-codes Use ANSI escape codes for diagnostics
  2406. -fblocks Enable the 'blocks' language feature
  2407. -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none.
  2408. -fcf-protection Enable cf-protection in 'full' mode
  2409. -fcolor-diagnostics Use colors in diagnostics
  2410. -fcomplete-member-pointers
  2411. Require member pointer base types to be complete if they would be significant under the Microsoft ABI
  2412. -fcoverage-mapping Generate coverage mapping to enable code coverage analysis
  2413. -fdebug-macro Emit macro debug information
  2414. -fdelayed-template-parsing
  2415. Parse templated function definitions at the end of the translation unit
  2416. -fdiagnostics-absolute-paths
  2417. Print absolute paths in diagnostics
  2418. -fdiagnostics-parseable-fixits
  2419. Print fix-its in machine parseable form
  2420. -flto=<value> Set LTO mode to either 'full' or 'thin'
  2421. -flto Enable LTO in 'full' mode
  2422. -fmerge-all-constants Allow merging of constants
  2423. -fms-compatibility-version=<value>
  2424. Dot-separated value representing the Microsoft compiler version
  2425. number to report in _MSC_VER (0 = don't define it (default))
  2426. -fms-compatibility Enable full Microsoft Visual C++ compatibility
  2427. -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
  2428. -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
  2429. (0 = don't define it (default))
  2430. -fno-addrsig Don't emit an address-significance table
  2431. -fno-builtin-<value> Disable implicit builtin knowledge of a specific function
  2432. -fno-builtin Disable implicit builtin knowledge of functions
  2433. -fno-complete-member-pointers
  2434. Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI
  2435. -fno-coverage-mapping Disable code coverage analysis
  2436. -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash
  2437. -fno-debug-macro Do not emit macro debug information
  2438. -fno-delayed-template-parsing
  2439. Disable delayed template parsing
  2440. -fno-sanitize-address-poison-custom-array-cookie
  2441. Disable poisoning array cookies when using custom operator new[] in AddressSanitizer
  2442. -fno-sanitize-address-use-after-scope
  2443. Disable use-after-scope detection in AddressSanitizer
  2444. -fno-sanitize-address-use-odr-indicator
  2445. Disable ODR indicator globals
  2446. -fno-sanitize-blacklist Don't use blacklist file for sanitizers
  2447. -fno-sanitize-cfi-cross-dso
  2448. Disable control flow integrity (CFI) checks for cross-DSO calls.
  2449. -fno-sanitize-coverage=<value>
  2450. Disable specified features of coverage instrumentation for Sanitizers
  2451. -fno-sanitize-memory-track-origins
  2452. Disable origins tracking in MemorySanitizer
  2453. -fno-sanitize-memory-use-after-dtor
  2454. Disable use-after-destroy detection in MemorySanitizer
  2455. -fno-sanitize-recover=<value>
  2456. Disable recovery for specified sanitizers
  2457. -fno-sanitize-stats Disable sanitizer statistics gathering.
  2458. -fno-sanitize-thread-atomics
  2459. Disable atomic operations instrumentation in ThreadSanitizer
  2460. -fno-sanitize-thread-func-entry-exit
  2461. Disable function entry/exit instrumentation in ThreadSanitizer
  2462. -fno-sanitize-thread-memory-access
  2463. Disable memory access instrumentation in ThreadSanitizer
  2464. -fno-sanitize-trap=<value>
  2465. Disable trapping for specified sanitizers
  2466. -fno-standalone-debug Limit debug information produced to reduce size of debug binary
  2467. -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version
  2468. -fprofile-exclude-files=<value>
  2469. Instrument only functions from files where names don't match all the regexes separated by a semi-colon
  2470. -fprofile-filter-files=<value>
  2471. Instrument only functions from files where names match any regex separated by a semi-colon
  2472. -fprofile-instr-generate=<file>
  2473. Generate instrumented code to collect execution counts into <file>
  2474. (overridden by LLVM_PROFILE_FILE env var)
  2475. -fprofile-instr-generate
  2476. Generate instrumented code to collect execution counts into default.profraw file
  2477. (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
  2478. -fprofile-instr-use=<value>
  2479. Use instrumentation data for profile-guided optimization
  2480. -fprofile-remapping-file=<file>
  2481. Use the remappings described in <file> to match the profile data against names in the program
  2482. -fsanitize-address-field-padding=<value>
  2483. Level of field padding for AddressSanitizer
  2484. -fsanitize-address-globals-dead-stripping
  2485. Enable linker dead stripping of globals in AddressSanitizer
  2486. -fsanitize-address-poison-custom-array-cookie
  2487. Enable poisoning array cookies when using custom operator new[] in AddressSanitizer
  2488. -fsanitize-address-use-after-scope
  2489. Enable use-after-scope detection in AddressSanitizer
  2490. -fsanitize-address-use-odr-indicator
  2491. Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size
  2492. -fsanitize-blacklist=<value>
  2493. Path to blacklist file for sanitizers
  2494. -fsanitize-cfi-cross-dso
  2495. Enable control flow integrity (CFI) checks for cross-DSO calls.
  2496. -fsanitize-cfi-icall-generalize-pointers
  2497. Generalize pointers in CFI indirect call type signature checks
  2498. -fsanitize-coverage=<value>
  2499. Specify the type of coverage instrumentation for Sanitizers
  2500. -fsanitize-hwaddress-abi=<value>
  2501. Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor)
  2502. -fsanitize-memory-track-origins=<value>
  2503. Enable origins tracking in MemorySanitizer
  2504. -fsanitize-memory-track-origins
  2505. Enable origins tracking in MemorySanitizer
  2506. -fsanitize-memory-use-after-dtor
  2507. Enable use-after-destroy detection in MemorySanitizer
  2508. -fsanitize-recover=<value>
  2509. Enable recovery for specified sanitizers
  2510. -fsanitize-stats Enable sanitizer statistics gathering.
  2511. -fsanitize-thread-atomics
  2512. Enable atomic operations instrumentation in ThreadSanitizer (default)
  2513. -fsanitize-thread-func-entry-exit
  2514. Enable function entry/exit instrumentation in ThreadSanitizer (default)
  2515. -fsanitize-thread-memory-access
  2516. Enable memory access instrumentation in ThreadSanitizer (default)
  2517. -fsanitize-trap=<value> Enable trapping for specified sanitizers
  2518. -fsanitize-undefined-strip-path-components=<number>
  2519. Strip (or keep only, if negative) a given number of path components when emitting check metadata.
  2520. -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
  2521. behavior. See user manual for available checks
  2522. -fsplit-lto-unit Enables splitting of the LTO unit.
  2523. -fstandalone-debug Emit full debug info for all types used by the program
  2524. -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
  2525. -gcodeview-ghash Emit type record hashes in a .debug$H section
  2526. -gcodeview Generate CodeView debug information
  2527. -gline-directives-only Emit debug line info directives only
  2528. -gline-tables-only Emit debug line number tables only
  2529. -miamcu Use Intel MCU ABI
  2530. -mllvm <value> Additional arguments to forward to LLVM's option processing
  2531. -nobuiltininc Disable builtin #include directories
  2532. -Qunused-arguments Don't emit warning for unused driver arguments
  2533. -R<remark> Enable the specified remark
  2534. --target=<value> Generate code for the given target
  2535. --version Print version information
  2536. -v Show commands to run and use verbose output
  2537. -W<warning> Enable the specified warning
  2538. -Xclang <arg> Pass <arg> to the clang compiler
  2539. The /clang: Option
  2540. ^^^^^^^^^^^^^^^^^^
  2541. When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all
  2542. of the ``<arg>`` arguments and process them as if they were passed to the clang
  2543. driver. This mechanism allows you to pass flags that are not exposed in the
  2544. clang-cl options or flags that have a different meaning when passed to the clang
  2545. driver. Regardless of where they appear in the command line, the ``/clang:``
  2546. arguments are treated as if they were passed at the end of the clang-cl command
  2547. line.
  2548. The /Zc:dllexportInlines- Option
  2549. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  2550. This causes the class-level `dllexport` and `dllimport` attributes to not apply
  2551. to inline member functions, as they otherwise would. For example, in the code
  2552. below `S::foo()` would normally be defined and exported by the DLL, but when
  2553. using the ``/Zc:dllexportInlines-`` flag it is not:
  2554. .. code-block:: c
  2555. struct __declspec(dllexport) S {
  2556. void foo() {}
  2557. }
  2558. This has the benefit that the compiler doesn't need to emit a definition of
  2559. `S::foo()` in every translation unit where the declaration is included, as it
  2560. would otherwise do to ensure there's a definition in the DLL even if it's not
  2561. used there. If the declaration occurs in a header file that's widely used, this
  2562. can save significant compilation time and output size. It also reduces the
  2563. number of functions exported by the DLL similarly to what
  2564. ``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.
  2565. Since the function declaration comes with an inline definition, users of the
  2566. library can use that definition directly instead of importing it from the DLL.
  2567. Note that the Microsoft Visual C++ compiler does not support this option, and
  2568. if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the
  2569. DLL must be compiled in the same way so that it doesn't attempt to dllimport
  2570. the inline member functions. The reverse scenario should generally work though:
  2571. a DLL compiled without this flag (such as a system library compiled with Visual
  2572. C++) can be referenced from code compiled using the flag, meaning that the
  2573. referencing code will use the inline definitions instead of importing them from
  2574. the DLL.
  2575. Also note that like when using ``-fvisibility-inlines-hidden``, the address of
  2576. `S::foo()` will be different inside and outside the DLL, breaking the C/C++
  2577. standard requirement that functions have a unique address.
  2578. The flag does not apply to explicit class template instantiation definitions or
  2579. declarations, as those are typically used to explicitly provide a single
  2580. definition in a DLL, (dllexported instantiation definition) or to signal that
  2581. the definition is available elsewhere (dllimport instantiation declaration). It
  2582. also doesn't apply to inline members with static local variables, to ensure
  2583. that the same instance of the variable is used inside and outside the DLL.
  2584. Using this flag can cause problems when inline functions that would otherwise
  2585. be dllexported refer to internal symbols of a DLL. For example:
  2586. .. code-block:: c
  2587. void internal();
  2588. struct __declspec(dllimport) S {
  2589. void foo() { internal(); }
  2590. }
  2591. Normally, references to `S::foo()` would use the definition in the DLL from
  2592. which it was exported, and which presumably also has the definition of
  2593. `internal()`. However, when using ``/Zc:dllexportInlines-``, the inline
  2594. definition of `S::foo()` is used directly, resulting in a link error since
  2595. `internal()` is not available. Even worse, if there is an inline definition of
  2596. `internal()` containing a static local variable, we will now refer to a
  2597. different instance of that variable than in the DLL:
  2598. .. code-block:: c
  2599. inline int internal() { static int x; return x++; }
  2600. struct __declspec(dllimport) S {
  2601. int foo() { return internal(); }
  2602. }
  2603. This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can
  2604. lead to the same issue. To avoid it in this case, make `S::foo()` or
  2605. `internal()` non-inline, or mark them `dllimport/dllexport` explicitly.
  2606. The /fallback Option
  2607. ^^^^^^^^^^^^^^^^^^^^
  2608. When clang-cl is run with the ``/fallback`` option, it will first try to
  2609. compile files itself. For any file that it fails to compile, it will fall back
  2610. and try to compile the file by invoking cl.exe.
  2611. This option is intended to be used as a temporary means to build projects where
  2612. clang-cl cannot successfully compile all the files. clang-cl may fail to compile
  2613. a file either because it cannot generate code for some C++ feature, or because
  2614. it cannot parse some Microsoft language extension.