LanguageExtensions.rst 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511
  1. =========================
  2. Clang Language Extensions
  3. =========================
  4. .. contents::
  5. :local:
  6. :depth: 1
  7. .. toctree::
  8. :hidden:
  9. ObjectiveCLiterals
  10. BlockLanguageSpec
  11. Block-ABI-Apple
  12. AutomaticReferenceCounting
  13. Introduction
  14. ============
  15. This document describes the language extensions provided by Clang. In addition
  16. to the language extensions listed here, Clang aims to support a broad range of
  17. GCC extensions. Please see the `GCC manual
  18. <https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
  19. these extensions.
  20. .. _langext-feature_check:
  21. Feature Checking Macros
  22. =======================
  23. Language extensions can be very useful, but only if you know you can depend on
  24. them. In order to allow fine-grain features checks, we support three builtin
  25. function-like macros. This allows you to directly test for a feature in your
  26. code without having to resort to something like autoconf or fragile "compiler
  27. version checks".
  28. ``__has_builtin``
  29. -----------------
  30. This function-like macro takes a single identifier argument that is the name of
  31. a builtin function, a builtin pseudo-function (taking one or more type
  32. arguments), or a builtin template.
  33. It evaluates to 1 if the builtin is supported or 0 if not.
  34. It can be used like this:
  35. .. code-block:: c++
  36. #ifndef __has_builtin // Optional of course.
  37. #define __has_builtin(x) 0 // Compatibility with non-clang compilers.
  38. #endif
  39. ...
  40. #if __has_builtin(__builtin_trap)
  41. __builtin_trap();
  42. #else
  43. abort();
  44. #endif
  45. ...
  46. .. note::
  47. Prior to Clang 10, ``__has_builtin`` could not be used to detect most builtin
  48. pseudo-functions.
  49. ``__has_builtin`` should not be used to detect support for a builtin macro;
  50. use ``#ifdef`` instead.
  51. .. _langext-__has_feature-__has_extension:
  52. ``__has_feature`` and ``__has_extension``
  53. -----------------------------------------
  54. These function-like macros take a single identifier argument that is the name
  55. of a feature. ``__has_feature`` evaluates to 1 if the feature is both
  56. supported by Clang and standardized in the current language standard or 0 if
  57. not (but see :ref:`below <langext-has-feature-back-compat>`), while
  58. ``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
  59. current language (either as a language extension or a standard language
  60. feature) or 0 if not. They can be used like this:
  61. .. code-block:: c++
  62. #ifndef __has_feature // Optional of course.
  63. #define __has_feature(x) 0 // Compatibility with non-clang compilers.
  64. #endif
  65. #ifndef __has_extension
  66. #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
  67. #endif
  68. ...
  69. #if __has_feature(cxx_rvalue_references)
  70. // This code will only be compiled with the -std=c++11 and -std=gnu++11
  71. // options, because rvalue references are only standardized in C++11.
  72. #endif
  73. #if __has_extension(cxx_rvalue_references)
  74. // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
  75. // and -std=gnu++98 options, because rvalue references are supported as a
  76. // language extension in C++98.
  77. #endif
  78. .. _langext-has-feature-back-compat:
  79. For backward compatibility, ``__has_feature`` can also be used to test
  80. for support for non-standardized features, i.e. features not prefixed ``c_``,
  81. ``cxx_`` or ``objc_``.
  82. Another use of ``__has_feature`` is to check for compiler features not related
  83. to the language standard, such as e.g. :doc:`AddressSanitizer
  84. <AddressSanitizer>`.
  85. If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
  86. to ``__has_feature``.
  87. The feature tag is described along with the language feature below.
  88. The feature name or extension name can also be specified with a preceding and
  89. following ``__`` (double underscore) to avoid interference from a macro with
  90. the same name. For instance, ``__cxx_rvalue_references__`` can be used instead
  91. of ``cxx_rvalue_references``.
  92. ``__has_cpp_attribute``
  93. -----------------------
  94. This function-like macro is available in C++2a by default, and is provided as an
  95. extension in earlier language standards. It takes a single argument that is the
  96. name of a double-square-bracket-style attribute. The argument can either be a
  97. single identifier or a scoped identifier. If the attribute is supported, a
  98. nonzero value is returned. If the attribute is a standards-based attribute, this
  99. macro returns a nonzero value based on the year and month in which the attribute
  100. was voted into the working draft. See `WG21 SD-6
  101. <https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_
  102. for the list of values returned for standards-based attributes. If the attribute
  103. is not supported by the current compliation target, this macro evaluates to 0.
  104. It can be used like this:
  105. .. code-block:: c++
  106. #ifndef __has_cpp_attribute // For backwards compatibility
  107. #define __has_cpp_attribute(x) 0
  108. #endif
  109. ...
  110. #if __has_cpp_attribute(clang::fallthrough)
  111. #define FALLTHROUGH [[clang::fallthrough]]
  112. #else
  113. #define FALLTHROUGH
  114. #endif
  115. ...
  116. The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
  117. the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
  118. of these namespaces can be specified with a preceding and following ``__``
  119. (double underscore) to avoid interference from a macro with the same name. For
  120. instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
  121. ``__has_c_attribute``
  122. ---------------------
  123. This function-like macro takes a single argument that is the name of an
  124. attribute exposed with the double square-bracket syntax in C mode. The argument
  125. can either be a single identifier or a scoped identifier. If the attribute is
  126. supported, a nonzero value is returned. If the attribute is not supported by the
  127. current compilation target, this macro evaluates to 0. It can be used like this:
  128. .. code-block:: c
  129. #ifndef __has_c_attribute // Optional of course.
  130. #define __has_c_attribute(x) 0 // Compatibility with non-clang compilers.
  131. #endif
  132. ...
  133. #if __has_c_attribute(fallthrough)
  134. #define FALLTHROUGH [[fallthrough]]
  135. #else
  136. #define FALLTHROUGH
  137. #endif
  138. ...
  139. The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are
  140. the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either
  141. of these namespaces can be specified with a preceding and following ``__``
  142. (double underscore) to avoid interference from a macro with the same name. For
  143. instance, ``gnu::__const__`` can be used instead of ``gnu::const``.
  144. ``__has_attribute``
  145. -------------------
  146. This function-like macro takes a single identifier argument that is the name of
  147. a GNU-style attribute. It evaluates to 1 if the attribute is supported by the
  148. current compilation target, or 0 if not. It can be used like this:
  149. .. code-block:: c++
  150. #ifndef __has_attribute // Optional of course.
  151. #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
  152. #endif
  153. ...
  154. #if __has_attribute(always_inline)
  155. #define ALWAYS_INLINE __attribute__((always_inline))
  156. #else
  157. #define ALWAYS_INLINE
  158. #endif
  159. ...
  160. The attribute name can also be specified with a preceding and following ``__``
  161. (double underscore) to avoid interference from a macro with the same name. For
  162. instance, ``__always_inline__`` can be used instead of ``always_inline``.
  163. ``__has_declspec_attribute``
  164. ----------------------------
  165. This function-like macro takes a single identifier argument that is the name of
  166. an attribute implemented as a Microsoft-style ``__declspec`` attribute. It
  167. evaluates to 1 if the attribute is supported by the current compilation target,
  168. or 0 if not. It can be used like this:
  169. .. code-block:: c++
  170. #ifndef __has_declspec_attribute // Optional of course.
  171. #define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers.
  172. #endif
  173. ...
  174. #if __has_declspec_attribute(dllexport)
  175. #define DLLEXPORT __declspec(dllexport)
  176. #else
  177. #define DLLEXPORT
  178. #endif
  179. ...
  180. The attribute name can also be specified with a preceding and following ``__``
  181. (double underscore) to avoid interference from a macro with the same name. For
  182. instance, ``__dllexport__`` can be used instead of ``dllexport``.
  183. ``__is_identifier``
  184. -------------------
  185. This function-like macro takes a single identifier argument that might be either
  186. a reserved word or a regular identifier. It evaluates to 1 if the argument is just
  187. a regular identifier and not a reserved word, in the sense that it can then be
  188. used as the name of a user-defined function or variable. Otherwise it evaluates
  189. to 0. It can be used like this:
  190. .. code-block:: c++
  191. ...
  192. #ifdef __is_identifier // Compatibility with non-clang compilers.
  193. #if __is_identifier(__wchar_t)
  194. typedef wchar_t __wchar_t;
  195. #endif
  196. #endif
  197. __wchar_t WideCharacter;
  198. ...
  199. Include File Checking Macros
  200. ============================
  201. Not all developments systems have the same include files. The
  202. :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
  203. you to check for the existence of an include file before doing a possibly
  204. failing ``#include`` directive. Include file checking macros must be used
  205. as expressions in ``#if`` or ``#elif`` preprocessing directives.
  206. .. _langext-__has_include:
  207. ``__has_include``
  208. -----------------
  209. This function-like macro takes a single file name string argument that is the
  210. name of an include file. It evaluates to 1 if the file can be found using the
  211. include paths, or 0 otherwise:
  212. .. code-block:: c++
  213. // Note the two possible file name string formats.
  214. #if __has_include("myinclude.h") && __has_include(<stdint.h>)
  215. # include "myinclude.h"
  216. #endif
  217. To test for this feature, use ``#if defined(__has_include)``:
  218. .. code-block:: c++
  219. // To avoid problem with non-clang compilers not having this macro.
  220. #if defined(__has_include)
  221. #if __has_include("myinclude.h")
  222. # include "myinclude.h"
  223. #endif
  224. #endif
  225. .. _langext-__has_include_next:
  226. ``__has_include_next``
  227. ----------------------
  228. This function-like macro takes a single file name string argument that is the
  229. name of an include file. It is like ``__has_include`` except that it looks for
  230. the second instance of the given file found in the include paths. It evaluates
  231. to 1 if the second instance of the file can be found using the include paths,
  232. or 0 otherwise:
  233. .. code-block:: c++
  234. // Note the two possible file name string formats.
  235. #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
  236. # include_next "myinclude.h"
  237. #endif
  238. // To avoid problem with non-clang compilers not having this macro.
  239. #if defined(__has_include_next)
  240. #if __has_include_next("myinclude.h")
  241. # include_next "myinclude.h"
  242. #endif
  243. #endif
  244. Note that ``__has_include_next``, like the GNU extension ``#include_next``
  245. directive, is intended for use in headers only, and will issue a warning if
  246. used in the top-level compilation file. A warning will also be issued if an
  247. absolute path is used in the file argument.
  248. ``__has_warning``
  249. -----------------
  250. This function-like macro takes a string literal that represents a command line
  251. option for a warning and returns true if that is a valid warning option.
  252. .. code-block:: c++
  253. #if __has_warning("-Wformat")
  254. ...
  255. #endif
  256. .. _languageextensions-builtin-macros:
  257. Builtin Macros
  258. ==============
  259. ``__BASE_FILE__``
  260. Defined to a string that contains the name of the main input file passed to
  261. Clang.
  262. ``__FILE_NAME__``
  263. Clang-specific extension that functions similar to ``__FILE__`` but only
  264. renders the last path component (the filename) instead of an invocation
  265. dependent full path to that file.
  266. ``__COUNTER__``
  267. Defined to an integer value that starts at zero and is incremented each time
  268. the ``__COUNTER__`` macro is expanded.
  269. ``__INCLUDE_LEVEL__``
  270. Defined to an integral value that is the include depth of the file currently
  271. being translated. For the main file, this value is zero.
  272. ``__TIMESTAMP__``
  273. Defined to the date and time of the last modification of the current source
  274. file.
  275. ``__clang__``
  276. Defined when compiling with Clang
  277. ``__clang_major__``
  278. Defined to the major marketing version number of Clang (e.g., the 2 in
  279. 2.0.1). Note that marketing version numbers should not be used to check for
  280. language features, as different vendors use different numbering schemes.
  281. Instead, use the :ref:`langext-feature_check`.
  282. ``__clang_minor__``
  283. Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
  284. that marketing version numbers should not be used to check for language
  285. features, as different vendors use different numbering schemes. Instead, use
  286. the :ref:`langext-feature_check`.
  287. ``__clang_patchlevel__``
  288. Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
  289. ``__clang_version__``
  290. Defined to a string that captures the Clang marketing version, including the
  291. Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
  292. .. _langext-vectors:
  293. Vectors and Extended Vectors
  294. ============================
  295. Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
  296. OpenCL vector types are created using the ``ext_vector_type`` attribute. It
  297. supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
  298. is:
  299. .. code-block:: c++
  300. typedef float float4 __attribute__((ext_vector_type(4)));
  301. typedef float float2 __attribute__((ext_vector_type(2)));
  302. float4 foo(float2 a, float2 b) {
  303. float4 c;
  304. c.xz = a;
  305. c.yw = b;
  306. return c;
  307. }
  308. Query for this feature with ``__has_attribute(ext_vector_type)``.
  309. Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax
  310. and functions. For example:
  311. .. code-block:: c++
  312. vector float foo(vector int a) {
  313. vector int b;
  314. b = vec_add(a, a) + a;
  315. return (vector float)b;
  316. }
  317. NEON vector types are created using ``neon_vector_type`` and
  318. ``neon_polyvector_type`` attributes. For example:
  319. .. code-block:: c++
  320. typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
  321. typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
  322. int8x8_t foo(int8x8_t a) {
  323. int8x8_t v;
  324. v = a;
  325. return v;
  326. }
  327. Vector Literals
  328. ---------------
  329. Vector literals can be used to create vectors from a set of scalars, or
  330. vectors. Either parentheses or braces form can be used. In the parentheses
  331. form the number of literal values specified must be one, i.e. referring to a
  332. scalar value, or must match the size of the vector type being created. If a
  333. single scalar literal value is specified, the scalar literal value will be
  334. replicated to all the components of the vector type. In the brackets form any
  335. number of literals can be specified. For example:
  336. .. code-block:: c++
  337. typedef int v4si __attribute__((__vector_size__(16)));
  338. typedef float float4 __attribute__((ext_vector_type(4)));
  339. typedef float float2 __attribute__((ext_vector_type(2)));
  340. v4si vsi = (v4si){1, 2, 3, 4};
  341. float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
  342. vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
  343. vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
  344. vector int vi3 = (vector int)(1, 2); // error
  345. vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
  346. vector int vi5 = (vector int)(1, 2, 3, 4);
  347. float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
  348. Vector Operations
  349. -----------------
  350. The table below shows the support for each operation by vector extension. A
  351. dash indicates that an operation is not accepted according to a corresponding
  352. specification.
  353. ============================== ======= ======= ======= =======
  354. Operator OpenCL AltiVec GCC NEON
  355. ============================== ======= ======= ======= =======
  356. [] yes yes yes --
  357. unary operators +, -- yes yes yes --
  358. ++, -- -- yes yes yes --
  359. +,--,*,/,% yes yes yes --
  360. bitwise operators &,|,^,~ yes yes yes --
  361. >>,<< yes yes yes --
  362. !, &&, || yes -- -- --
  363. ==, !=, >, <, >=, <= yes yes -- --
  364. = yes yes yes yes
  365. :? yes -- -- --
  366. sizeof yes yes yes yes
  367. C-style cast yes yes yes no
  368. reinterpret_cast yes no yes no
  369. static_cast yes no yes no
  370. const_cast no no no no
  371. ============================== ======= ======= ======= =======
  372. See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
  373. Half-Precision Floating Point
  374. =============================
  375. Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and
  376. ``_Float16``. These types are supported in all language modes.
  377. ``__fp16`` is supported on every target, as it is purely a storage format; see below.
  378. ``_Float16`` is currently only supported on the following targets, with further
  379. targets pending ABI standardization:
  380. * 32-bit ARM
  381. * 64-bit ARM (AArch64)
  382. * SPIR
  383. ``_Float16`` will be supported on more targets as they define ABIs for it.
  384. ``__fp16`` is a storage and interchange format only. This means that values of
  385. ``__fp16`` are immediately promoted to (at least) ``float`` when used in arithmetic
  386. operations, so that e.g. the result of adding two ``__fp16`` values has type ``float``.
  387. The behavior of ``__fp16`` is specified by the ARM C Language Extensions (`ACLE <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053d/IHI0053D_acle_2_1.pdf>`_).
  388. Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, not the ARM
  389. alternative format.
  390. ``_Float16`` is an extended floating-point type. This means that, just like arithmetic on
  391. ``float`` or ``double``, arithmetic on ``_Float16`` operands is formally performed in the
  392. ``_Float16`` type, so that e.g. the result of adding two ``_Float16`` values has type
  393. ``_Float16``. The behavior of ``_Float16`` is specified by ISO/IEC TS 18661-3:2015
  394. ("Floating-point extensions for C"). As with ``__fp16``, Clang uses the ``binary16``
  395. format from IEEE 754-2008 for ``_Float16``.
  396. ``_Float16`` arithmetic will be performed using native half-precision support
  397. when available on the target (e.g. on ARMv8.2a); otherwise it will be performed
  398. at a higher precision (currently always ``float``) and then truncated down to
  399. ``_Float16``. Note that C and C++ allow intermediate floating-point operands
  400. of an expression to be computed with greater precision than is expressible in
  401. their type, so Clang may avoid intermediate truncations in certain cases; this may
  402. lead to results that are inconsistent with native arithmetic.
  403. It is recommended that portable code use ``_Float16`` instead of ``__fp16``,
  404. as it has been defined by the C standards committee and has behavior that is
  405. more familiar to most programmers.
  406. Because ``__fp16`` operands are always immediately promoted to ``float``, the
  407. common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual
  408. arithmetic conversions is ``float``.
  409. A literal can be given ``_Float16`` type using the suffix ``f16``. For example,
  410. ``3.14f16``.
  411. Because default argument promotion only applies to the standard floating-point
  412. types, ``_Float16`` values are not promoted to ``double`` when passed as variadic
  413. or untyped arguments. As a consequence, some caution must be taken when using
  414. certain library facilities with ``_Float16``; for example, there is no ``printf`` format
  415. specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to
  416. ``double`` when passed to ``printf``, so the programmer must explicitly cast it to
  417. ``double`` before using it with an ``%f`` or similar specifier.
  418. Messages on ``deprecated`` and ``unavailable`` Attributes
  419. =========================================================
  420. An optional string message can be added to the ``deprecated`` and
  421. ``unavailable`` attributes. For example:
  422. .. code-block:: c++
  423. void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
  424. If the deprecated or unavailable declaration is used, the message will be
  425. incorporated into the appropriate diagnostic:
  426. .. code-block:: none
  427. harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
  428. [-Wdeprecated-declarations]
  429. explode();
  430. ^
  431. Query for this feature with
  432. ``__has_extension(attribute_deprecated_with_message)`` and
  433. ``__has_extension(attribute_unavailable_with_message)``.
  434. Attributes on Enumerators
  435. =========================
  436. Clang allows attributes to be written on individual enumerators. This allows
  437. enumerators to be deprecated, made unavailable, etc. The attribute must appear
  438. after the enumerator name and before any initializer, like so:
  439. .. code-block:: c++
  440. enum OperationMode {
  441. OM_Invalid,
  442. OM_Normal,
  443. OM_Terrified __attribute__((deprecated)),
  444. OM_AbortOnError __attribute__((deprecated)) = 4
  445. };
  446. Attributes on the ``enum`` declaration do not apply to individual enumerators.
  447. Query for this feature with ``__has_extension(enumerator_attributes)``.
  448. 'User-Specified' System Frameworks
  449. ==================================
  450. Clang provides a mechanism by which frameworks can be built in such a way that
  451. they will always be treated as being "system frameworks", even if they are not
  452. present in a system framework directory. This can be useful to system
  453. framework developers who want to be able to test building other applications
  454. with development builds of their framework, including the manner in which the
  455. compiler changes warning behavior for system headers.
  456. Framework developers can opt-in to this mechanism by creating a
  457. "``.system_framework``" file at the top-level of their framework. That is, the
  458. framework should have contents like:
  459. .. code-block:: none
  460. .../TestFramework.framework
  461. .../TestFramework.framework/.system_framework
  462. .../TestFramework.framework/Headers
  463. .../TestFramework.framework/Headers/TestFramework.h
  464. ...
  465. Clang will treat the presence of this file as an indicator that the framework
  466. should be treated as a system framework, regardless of how it was found in the
  467. framework search path. For consistency, we recommend that such files never be
  468. included in installed versions of the framework.
  469. Checks for Standard Language Features
  470. =====================================
  471. The ``__has_feature`` macro can be used to query if certain standard language
  472. features are enabled. The ``__has_extension`` macro can be used to query if
  473. language features are available as an extension when compiling for a standard
  474. which does not provide them. The features which can be tested are listed here.
  475. Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
  476. These are macros with names of the form ``__cpp_<feature_name>``, and are
  477. intended to be a portable way to query the supported features of the compiler.
  478. See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for
  479. information on the version of SD-6 supported by each Clang release, and the
  480. macros provided by that revision of the recommendations.
  481. C++98
  482. -----
  483. The features listed below are part of the C++98 standard. These features are
  484. enabled by default when compiling C++ code.
  485. C++ exceptions
  486. ^^^^^^^^^^^^^^
  487. Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
  488. enabled. For example, compiling code with ``-fno-exceptions`` disables C++
  489. exceptions.
  490. C++ RTTI
  491. ^^^^^^^^
  492. Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
  493. example, compiling code with ``-fno-rtti`` disables the use of RTTI.
  494. C++11
  495. -----
  496. The features listed below are part of the C++11 standard. As a result, all
  497. these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
  498. when compiling C++ code.
  499. C++11 SFINAE includes access control
  500. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  501. Use ``__has_feature(cxx_access_control_sfinae)`` or
  502. ``__has_extension(cxx_access_control_sfinae)`` to determine whether
  503. access-control errors (e.g., calling a private constructor) are considered to
  504. be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
  505. <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
  506. C++11 alias templates
  507. ^^^^^^^^^^^^^^^^^^^^^
  508. Use ``__has_feature(cxx_alias_templates)`` or
  509. ``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
  510. alias declarations and alias templates is enabled.
  511. C++11 alignment specifiers
  512. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  513. Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
  514. determine if support for alignment specifiers using ``alignas`` is enabled.
  515. Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
  516. determine if support for the ``alignof`` keyword is enabled.
  517. C++11 attributes
  518. ^^^^^^^^^^^^^^^^
  519. Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
  520. determine if support for attribute parsing with C++11's square bracket notation
  521. is enabled.
  522. C++11 generalized constant expressions
  523. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  524. Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
  525. constant expressions (e.g., ``constexpr``) is enabled.
  526. C++11 ``decltype()``
  527. ^^^^^^^^^^^^^^^^^^^^
  528. Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
  529. determine if support for the ``decltype()`` specifier is enabled. C++11's
  530. ``decltype`` does not require type-completeness of a function call expression.
  531. Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
  532. ``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
  533. support for this feature is enabled.
  534. C++11 default template arguments in function templates
  535. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  536. Use ``__has_feature(cxx_default_function_template_args)`` or
  537. ``__has_extension(cxx_default_function_template_args)`` to determine if support
  538. for default template arguments in function templates is enabled.
  539. C++11 ``default``\ ed functions
  540. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  541. Use ``__has_feature(cxx_defaulted_functions)`` or
  542. ``__has_extension(cxx_defaulted_functions)`` to determine if support for
  543. defaulted function definitions (with ``= default``) is enabled.
  544. C++11 delegating constructors
  545. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  546. Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
  547. delegating constructors is enabled.
  548. C++11 ``deleted`` functions
  549. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  550. Use ``__has_feature(cxx_deleted_functions)`` or
  551. ``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
  552. function definitions (with ``= delete``) is enabled.
  553. C++11 explicit conversion functions
  554. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  555. Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
  556. ``explicit`` conversion functions is enabled.
  557. C++11 generalized initializers
  558. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  559. Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
  560. generalized initializers (using braced lists and ``std::initializer_list``) is
  561. enabled.
  562. C++11 implicit move constructors/assignment operators
  563. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  564. Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
  565. generate move constructors and move assignment operators where needed.
  566. C++11 inheriting constructors
  567. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  568. Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
  569. inheriting constructors is enabled.
  570. C++11 inline namespaces
  571. ^^^^^^^^^^^^^^^^^^^^^^^
  572. Use ``__has_feature(cxx_inline_namespaces)`` or
  573. ``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
  574. namespaces is enabled.
  575. C++11 lambdas
  576. ^^^^^^^^^^^^^
  577. Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
  578. determine if support for lambdas is enabled.
  579. C++11 local and unnamed types as template arguments
  580. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  581. Use ``__has_feature(cxx_local_type_template_args)`` or
  582. ``__has_extension(cxx_local_type_template_args)`` to determine if support for
  583. local and unnamed types as template arguments is enabled.
  584. C++11 noexcept
  585. ^^^^^^^^^^^^^^
  586. Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
  587. determine if support for noexcept exception specifications is enabled.
  588. C++11 in-class non-static data member initialization
  589. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  590. Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
  591. initialization of non-static data members is enabled.
  592. C++11 ``nullptr``
  593. ^^^^^^^^^^^^^^^^^
  594. Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
  595. determine if support for ``nullptr`` is enabled.
  596. C++11 ``override control``
  597. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  598. Use ``__has_feature(cxx_override_control)`` or
  599. ``__has_extension(cxx_override_control)`` to determine if support for the
  600. override control keywords is enabled.
  601. C++11 reference-qualified functions
  602. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  603. Use ``__has_feature(cxx_reference_qualified_functions)`` or
  604. ``__has_extension(cxx_reference_qualified_functions)`` to determine if support
  605. for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
  606. applied to ``*this``) is enabled.
  607. C++11 range-based ``for`` loop
  608. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  609. Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
  610. determine if support for the range-based for loop is enabled.
  611. C++11 raw string literals
  612. ^^^^^^^^^^^^^^^^^^^^^^^^^
  613. Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
  614. string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
  615. C++11 rvalue references
  616. ^^^^^^^^^^^^^^^^^^^^^^^
  617. Use ``__has_feature(cxx_rvalue_references)`` or
  618. ``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
  619. references is enabled.
  620. C++11 ``static_assert()``
  621. ^^^^^^^^^^^^^^^^^^^^^^^^^
  622. Use ``__has_feature(cxx_static_assert)`` or
  623. ``__has_extension(cxx_static_assert)`` to determine if support for compile-time
  624. assertions using ``static_assert`` is enabled.
  625. C++11 ``thread_local``
  626. ^^^^^^^^^^^^^^^^^^^^^^
  627. Use ``__has_feature(cxx_thread_local)`` to determine if support for
  628. ``thread_local`` variables is enabled.
  629. C++11 type inference
  630. ^^^^^^^^^^^^^^^^^^^^
  631. Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
  632. determine C++11 type inference is supported using the ``auto`` specifier. If
  633. this is disabled, ``auto`` will instead be a storage class specifier, as in C
  634. or C++98.
  635. C++11 strongly typed enumerations
  636. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  637. Use ``__has_feature(cxx_strong_enums)`` or
  638. ``__has_extension(cxx_strong_enums)`` to determine if support for strongly
  639. typed, scoped enumerations is enabled.
  640. C++11 trailing return type
  641. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  642. Use ``__has_feature(cxx_trailing_return)`` or
  643. ``__has_extension(cxx_trailing_return)`` to determine if support for the
  644. alternate function declaration syntax with trailing return type is enabled.
  645. C++11 Unicode string literals
  646. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  647. Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
  648. string literals is enabled.
  649. C++11 unrestricted unions
  650. ^^^^^^^^^^^^^^^^^^^^^^^^^
  651. Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
  652. unrestricted unions is enabled.
  653. C++11 user-defined literals
  654. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  655. Use ``__has_feature(cxx_user_literals)`` to determine if support for
  656. user-defined literals is enabled.
  657. C++11 variadic templates
  658. ^^^^^^^^^^^^^^^^^^^^^^^^
  659. Use ``__has_feature(cxx_variadic_templates)`` or
  660. ``__has_extension(cxx_variadic_templates)`` to determine if support for
  661. variadic templates is enabled.
  662. C++14
  663. -----
  664. The features listed below are part of the C++14 standard. As a result, all
  665. these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option
  666. when compiling C++ code.
  667. C++14 binary literals
  668. ^^^^^^^^^^^^^^^^^^^^^
  669. Use ``__has_feature(cxx_binary_literals)`` or
  670. ``__has_extension(cxx_binary_literals)`` to determine whether
  671. binary literals (for instance, ``0b10010``) are recognized. Clang supports this
  672. feature as an extension in all language modes.
  673. C++14 contextual conversions
  674. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  675. Use ``__has_feature(cxx_contextual_conversions)`` or
  676. ``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules
  677. are used when performing an implicit conversion for an array bound in a
  678. *new-expression*, the operand of a *delete-expression*, an integral constant
  679. expression, or a condition in a ``switch`` statement.
  680. C++14 decltype(auto)
  681. ^^^^^^^^^^^^^^^^^^^^
  682. Use ``__has_feature(cxx_decltype_auto)`` or
  683. ``__has_extension(cxx_decltype_auto)`` to determine if support
  684. for the ``decltype(auto)`` placeholder type is enabled.
  685. C++14 default initializers for aggregates
  686. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  687. Use ``__has_feature(cxx_aggregate_nsdmi)`` or
  688. ``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
  689. for default initializers in aggregate members is enabled.
  690. C++14 digit separators
  691. ^^^^^^^^^^^^^^^^^^^^^^
  692. Use ``__cpp_digit_separators`` to determine if support for digit separators
  693. using single quotes (for instance, ``10'000``) is enabled. At this time, there
  694. is no corresponding ``__has_feature`` name
  695. C++14 generalized lambda capture
  696. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  697. Use ``__has_feature(cxx_init_captures)`` or
  698. ``__has_extension(cxx_init_captures)`` to determine if support for
  699. lambda captures with explicit initializers is enabled
  700. (for instance, ``[n(0)] { return ++n; }``).
  701. C++14 generic lambdas
  702. ^^^^^^^^^^^^^^^^^^^^^
  703. Use ``__has_feature(cxx_generic_lambdas)`` or
  704. ``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
  705. (polymorphic) lambdas is enabled
  706. (for instance, ``[] (auto x) { return x + 1; }``).
  707. C++14 relaxed constexpr
  708. ^^^^^^^^^^^^^^^^^^^^^^^
  709. Use ``__has_feature(cxx_relaxed_constexpr)`` or
  710. ``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
  711. declarations, local variable modification, and control flow constructs
  712. are permitted in ``constexpr`` functions.
  713. C++14 return type deduction
  714. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  715. Use ``__has_feature(cxx_return_type_deduction)`` or
  716. ``__has_extension(cxx_return_type_deduction)`` to determine if support
  717. for return type deduction for functions (using ``auto`` as a return type)
  718. is enabled.
  719. C++14 runtime-sized arrays
  720. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  721. Use ``__has_feature(cxx_runtime_array)`` or
  722. ``__has_extension(cxx_runtime_array)`` to determine if support
  723. for arrays of runtime bound (a restricted form of variable-length arrays)
  724. is enabled.
  725. Clang's implementation of this feature is incomplete.
  726. C++14 variable templates
  727. ^^^^^^^^^^^^^^^^^^^^^^^^
  728. Use ``__has_feature(cxx_variable_templates)`` or
  729. ``__has_extension(cxx_variable_templates)`` to determine if support for
  730. templated variable declarations is enabled.
  731. C11
  732. ---
  733. The features listed below are part of the C11 standard. As a result, all these
  734. features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
  735. compiling C code. Additionally, because these features are all
  736. backward-compatible, they are available as extensions in all language modes.
  737. C11 alignment specifiers
  738. ^^^^^^^^^^^^^^^^^^^^^^^^
  739. Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
  740. if support for alignment specifiers using ``_Alignas`` is enabled.
  741. Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
  742. if support for the ``_Alignof`` keyword is enabled.
  743. C11 atomic operations
  744. ^^^^^^^^^^^^^^^^^^^^^
  745. Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
  746. if support for atomic types using ``_Atomic`` is enabled. Clang also provides
  747. :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
  748. the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
  749. ``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
  750. is available.
  751. Clang will use the system's ``<stdatomic.h>`` header when one is available, and
  752. will otherwise use its own. When using its own, implementations of the atomic
  753. operations are provided as macros. In the cases where C11 also requires a real
  754. function, this header provides only the declaration of that function (along
  755. with a shadowing macro implementation), and you must link to a library which
  756. provides a definition of the function if you use it instead of the macro.
  757. C11 generic selections
  758. ^^^^^^^^^^^^^^^^^^^^^^
  759. Use ``__has_feature(c_generic_selections)`` or
  760. ``__has_extension(c_generic_selections)`` to determine if support for generic
  761. selections is enabled.
  762. As an extension, the C11 generic selection expression is available in all
  763. languages supported by Clang. The syntax is the same as that given in the C11
  764. standard.
  765. In C, type compatibility is decided according to the rules given in the
  766. appropriate standard, but in C++, which lacks the type compatibility rules used
  767. in C, types are considered compatible only if they are equivalent.
  768. C11 ``_Static_assert()``
  769. ^^^^^^^^^^^^^^^^^^^^^^^^
  770. Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
  771. to determine if support for compile-time assertions using ``_Static_assert`` is
  772. enabled.
  773. C11 ``_Thread_local``
  774. ^^^^^^^^^^^^^^^^^^^^^
  775. Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
  776. to determine if support for ``_Thread_local`` variables is enabled.
  777. Modules
  778. -------
  779. Use ``__has_feature(modules)`` to determine if Modules have been enabled.
  780. For example, compiling code with ``-fmodules`` enables the use of Modules.
  781. More information could be found `here <https://clang.llvm.org/docs/Modules.html>`_.
  782. Type Trait Primitives
  783. =====================
  784. Type trait primitives are special builtin constant expressions that can be used
  785. by the standard C++ library to facilitate or simplify the implementation of
  786. user-facing type traits in the <type_traits> header.
  787. They are not intended to be used directly by user code because they are
  788. implementation-defined and subject to change -- as such they're tied closely to
  789. the supported set of system headers, currently:
  790. * LLVM's own libc++
  791. * GNU libstdc++
  792. * The Microsoft standard C++ library
  793. Clang supports the `GNU C++ type traits
  794. <https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
  795. `Microsoft Visual C++ type traits
  796. <https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_,
  797. as well as nearly all of the
  798. `Embarcadero C++ type traits
  799. <http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_.
  800. The following type trait primitives are supported by Clang. Those traits marked
  801. (C++) provide implementations for type traits specified by the C++ standard;
  802. ``__X(...)`` has the same semantics and constraints as the corresponding
  803. ``std::X_t<...>`` or ``std::X_v<...>`` type trait.
  804. * ``__array_rank(type)`` (Embarcadero):
  805. Returns the number of levels of array in the type ``type``:
  806. ``0`` if ``type`` is not an array type, and
  807. ``__array_rank(element) + 1`` if ``type`` is an array of ``element``.
  808. * ``__array_extent(type, dim)`` (Embarcadero):
  809. The ``dim``'th array bound in the type ``type``, or ``0`` if
  810. ``dim >= __array_rank(type)``.
  811. * ``__has_nothrow_assign`` (GNU, Microsoft, Embarcadero):
  812. Deprecated, use ``__is_nothrow_assignable`` instead.
  813. * ``__has_nothrow_move_assign`` (GNU, Microsoft):
  814. Deprecated, use ``__is_nothrow_assignable`` instead.
  815. * ``__has_nothrow_copy`` (GNU, Microsoft):
  816. Deprecated, use ``__is_nothrow_constructible`` instead.
  817. * ``__has_nothrow_constructor`` (GNU, Microsoft):
  818. Deprecated, use ``__is_nothrow_constructible`` instead.
  819. * ``__has_trivial_assign`` (GNU, Microsoft, Embarcadero):
  820. Deprecated, use ``__is_trivially_assignable`` instead.
  821. * ``__has_trivial_move_assign`` (GNU, Microsoft):
  822. Deprecated, use ``__is_trivially_assignable`` instead.
  823. * ``__has_trivial_copy`` (GNU, Microsoft):
  824. Deprecated, use ``__is_trivially_constructible`` instead.
  825. * ``__has_trivial_constructor`` (GNU, Microsoft):
  826. Deprecated, use ``__is_trivially_constructible`` instead.
  827. * ``__has_trivial_move_constructor`` (GNU, Microsoft):
  828. Deprecated, use ``__is_trivially_constructible`` instead.
  829. * ``__has_trivial_destructor`` (GNU, Microsoft, Embarcadero):
  830. Deprecated, use ``__is_trivially_destructible`` instead.
  831. * ``__has_unique_object_representations`` (C++, GNU)
  832. * ``__has_virtual_destructor`` (C++, GNU, Microsoft, Embarcadero)
  833. * ``__is_abstract`` (C++, GNU, Microsoft, Embarcadero)
  834. * ``__is_aggregate`` (C++, GNU, Microsoft)
  835. * ``__is_arithmetic`` (C++, Embarcadero)
  836. * ``__is_array`` (C++, Embarcadero)
  837. * ``__is_assignable`` (C++, MSVC 2015)
  838. * ``__is_base_of`` (C++, GNU, Microsoft, Embarcadero)
  839. * ``__is_class`` (C++, GNU, Microsoft, Embarcadero)
  840. * ``__is_complete_type(type)`` (Embarcadero):
  841. Return ``true`` if ``type`` is a complete type.
  842. Warning: this trait is dangerous because it can return different values at
  843. different points in the same program.
  844. * ``__is_compound`` (C++, Embarcadero)
  845. * ``__is_const`` (C++, Embarcadero)
  846. * ``__is_constructible`` (C++, MSVC 2013)
  847. * ``__is_convertible`` (C++, Embarcadero)
  848. * ``__is_convertible_to`` (Microsoft):
  849. Synonym for ``__is_convertible``.
  850. * ``__is_destructible`` (C++, MSVC 2013):
  851. Only available in ``-fms-extensions`` mode.
  852. * ``__is_empty`` (C++, GNU, Microsoft, Embarcadero)
  853. * ``__is_enum`` (C++, GNU, Microsoft, Embarcadero)
  854. * ``__is_final`` (C++, GNU, Microsoft)
  855. * ``__is_floating_point`` (C++, Embarcadero)
  856. * ``__is_function`` (C++, Embarcadero)
  857. * ``__is_fundamental`` (C++, Embarcadero)
  858. * ``__is_integral`` (C++, Embarcadero)
  859. * ``__is_interface_class`` (Microsoft):
  860. Returns ``false``, even for types defined with ``__interface``.
  861. * ``__is_literal`` (Clang):
  862. Synonym for ``__is_literal_type``.
  863. * ``__is_literal_type`` (C++, GNU, Microsoft):
  864. Note, the corresponding standard trait was deprecated in C++17
  865. and removed in C++20.
  866. * ``__is_lvalue_reference`` (C++, Embarcadero)
  867. * ``__is_member_object_pointer`` (C++, Embarcadero)
  868. * ``__is_member_function_pointer`` (C++, Embarcadero)
  869. * ``__is_member_pointer`` (C++, Embarcadero)
  870. * ``__is_nothrow_assignable`` (C++, MSVC 2013)
  871. * ``__is_nothrow_constructible`` (C++, MSVC 2013)
  872. * ``__is_nothrow_destructible`` (C++, MSVC 2013)
  873. Only available in ``-fms-extensions`` mode.
  874. * ``__is_object`` (C++, Embarcadero)
  875. * ``__is_pod`` (C++, GNU, Microsoft, Embarcadero):
  876. Note, the corresponding standard trait was deprecated in C++20.
  877. * ``__is_pointer`` (C++, Embarcadero)
  878. * ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero)
  879. * ``__is_reference`` (C++, Embarcadero)
  880. * ``__is_rvalue_reference`` (C++, Embarcadero)
  881. * ``__is_same`` (C++, Embarcadero)
  882. * ``__is_scalar`` (C++, Embarcadero)
  883. * ``__is_sealed`` (Microsoft):
  884. Synonym for ``__is_final``.
  885. * ``__is_signed`` (C++, Embarcadero):
  886. Returns false for enumeration types, and returns true for floating-point types. Note, before Clang 10, returned true for enumeration types if the underlying type was signed, and returned false for floating-point types.
  887. * ``__is_standard_layout`` (C++, GNU, Microsoft, Embarcadero)
  888. * ``__is_trivial`` (C++, GNU, Microsoft, Embarcadero)
  889. * ``__is_trivially_assignable`` (C++, GNU, Microsoft)
  890. * ``__is_trivially_constructible`` (C++, GNU, Microsoft)
  891. * ``__is_trivially_copyable`` (C++, GNU, Microsoft)
  892. * ``__is_trivially_destructible`` (C++, MSVC 2013)
  893. * ``__is_union`` (C++, GNU, Microsoft, Embarcadero)
  894. * ``__is_unsigned`` (C++, Embarcadero)
  895. Note that this currently returns true for enumeration types if the underlying
  896. type is unsigned, in violation of the requirements for ``std::is_unsigned``.
  897. This behavior is likely to change in a future version of Clang.
  898. * ``__is_void`` (C++, Embarcadero)
  899. * ``__is_volatile`` (C++, Embarcadero)
  900. * ``__reference_binds_to_temporary(T, U)`` (Clang): Determines whether a
  901. reference of type ``T`` bound to an expression of type ``U`` would bind to a
  902. materialized temporary object. If ``T`` is not a reference type the result
  903. is false. Note this trait will also return false when the initialization of
  904. ``T`` from ``U`` is ill-formed.
  905. * ``__underlying_type`` (C++, GNU, Microsoft)
  906. In addition, the following expression traits are supported:
  907. * ``__is_lvalue_expr(e)`` (Embarcadero):
  908. Returns true if ``e`` is an lvalue expression.
  909. Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead.
  910. * ``__is_rvalue_expr(e)`` (Embarcadero):
  911. Returns true if ``e`` is a prvalue expression.
  912. Deprecated, use ``!__is_reference(decltype((e)))`` instead.
  913. There are multiple ways to detect support for a type trait ``__X`` in the
  914. compiler, depending on the oldest version of Clang you wish to support.
  915. * From Clang 10 onwards, ``__has_builtin(__X)`` can be used.
  916. * From Clang 6 onwards, ``!__is_identifier(__X)`` can be used.
  917. * From Clang 3 onwards, ``__has_feature(X)`` can be used, but only supports
  918. the following traits:
  919. * ``__has_nothrow_assign``
  920. * ``__has_nothrow_copy``
  921. * ``__has_nothrow_constructor``
  922. * ``__has_trivial_assign``
  923. * ``__has_trivial_copy``
  924. * ``__has_trivial_constructor``
  925. * ``__has_trivial_destructor``
  926. * ``__has_virtual_destructor``
  927. * ``__is_abstract``
  928. * ``__is_base_of``
  929. * ``__is_class``
  930. * ``__is_constructible``
  931. * ``__is_convertible_to``
  932. * ``__is_empty``
  933. * ``__is_enum``
  934. * ``__is_final``
  935. * ``__is_literal``
  936. * ``__is_standard_layout``
  937. * ``__is_pod``
  938. * ``__is_polymorphic``
  939. * ``__is_sealed``
  940. * ``__is_trivial``
  941. * ``__is_trivially_assignable``
  942. * ``__is_trivially_constructible``
  943. * ``__is_trivially_copyable``
  944. * ``__is_union``
  945. * ``__underlying_type``
  946. A simplistic usage example as might be seen in standard C++ headers follows:
  947. .. code-block:: c++
  948. #if __has_builtin(__is_convertible_to)
  949. template<typename From, typename To>
  950. struct is_convertible_to {
  951. static const bool value = __is_convertible_to(From, To);
  952. };
  953. #else
  954. // Emulate type trait for compatibility with other compilers.
  955. #endif
  956. Blocks
  957. ======
  958. The syntax and high level language feature description is in
  959. :doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
  960. the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
  961. Query for this feature with ``__has_extension(blocks)``.
  962. Objective-C Features
  963. ====================
  964. Related result types
  965. --------------------
  966. According to Cocoa conventions, Objective-C methods with certain names
  967. ("``init``", "``alloc``", etc.) always return objects that are an instance of
  968. the receiving class's type. Such methods are said to have a "related result
  969. type", meaning that a message send to one of these methods will have the same
  970. static type as an instance of the receiver class. For example, given the
  971. following classes:
  972. .. code-block:: objc
  973. @interface NSObject
  974. + (id)alloc;
  975. - (id)init;
  976. @end
  977. @interface NSArray : NSObject
  978. @end
  979. and this common initialization pattern
  980. .. code-block:: objc
  981. NSArray *array = [[NSArray alloc] init];
  982. the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
  983. ``alloc`` implicitly has a related result type. Similarly, the type of the
  984. expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
  985. related result type and its receiver is known to have the type ``NSArray *``.
  986. If neither ``alloc`` nor ``init`` had a related result type, the expressions
  987. would have had type ``id``, as declared in the method signature.
  988. A method with a related result type can be declared by using the type
  989. ``instancetype`` as its result type. ``instancetype`` is a contextual keyword
  990. that is only permitted in the result type of an Objective-C method, e.g.
  991. .. code-block:: objc
  992. @interface A
  993. + (instancetype)constructAnA;
  994. @end
  995. The related result type can also be inferred for some methods. To determine
  996. whether a method has an inferred related result type, the first word in the
  997. camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
  998. and the method will have a related result type if its return type is compatible
  999. with the type of its class and if:
  1000. * the first word is "``alloc``" or "``new``", and the method is a class method,
  1001. or
  1002. * the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
  1003. and the method is an instance method.
  1004. If a method with a related result type is overridden by a subclass method, the
  1005. subclass method must also return a type that is compatible with the subclass
  1006. type. For example:
  1007. .. code-block:: objc
  1008. @interface NSString : NSObject
  1009. - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
  1010. @end
  1011. Related result types only affect the type of a message send or property access
  1012. via the given method. In all other respects, a method with a related result
  1013. type is treated the same way as method that returns ``id``.
  1014. Use ``__has_feature(objc_instancetype)`` to determine whether the
  1015. ``instancetype`` contextual keyword is available.
  1016. Automatic reference counting
  1017. ----------------------------
  1018. Clang provides support for :doc:`automated reference counting
  1019. <AutomaticReferenceCounting>` in Objective-C, which eliminates the need
  1020. for manual ``retain``/``release``/``autorelease`` message sends. There are three
  1021. feature macros associated with automatic reference counting:
  1022. ``__has_feature(objc_arc)`` indicates the availability of automated reference
  1023. counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
  1024. automated reference counting also includes support for ``__weak`` pointers to
  1025. Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs
  1026. are allowed to have fields that are pointers to Objective-C objects managed by
  1027. automatic reference counting.
  1028. .. _objc-weak:
  1029. Weak references
  1030. ---------------
  1031. Clang supports ARC-style weak and unsafe references in Objective-C even
  1032. outside of ARC mode. Weak references must be explicitly enabled with
  1033. the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))``
  1034. to test whether they are enabled. Unsafe references are enabled
  1035. unconditionally. ARC-style weak and unsafe references cannot be used
  1036. when Objective-C garbage collection is enabled.
  1037. Except as noted below, the language rules for the ``__weak`` and
  1038. ``__unsafe_unretained`` qualifiers (and the ``weak`` and
  1039. ``unsafe_unretained`` property attributes) are just as laid out
  1040. in the :doc:`ARC specification <AutomaticReferenceCounting>`.
  1041. In particular, note that some classes do not support forming weak
  1042. references to their instances, and note that special care must be
  1043. taken when storing weak references in memory where initialization
  1044. and deinitialization are outside the responsibility of the compiler
  1045. (such as in ``malloc``-ed memory).
  1046. Loading from a ``__weak`` variable always implicitly retains the
  1047. loaded value. In non-ARC modes, this retain is normally balanced
  1048. by an implicit autorelease. This autorelease can be suppressed
  1049. by performing the load in the receiver position of a ``-retain``
  1050. message send (e.g. ``[weakReference retain]``); note that this performs
  1051. only a single retain (the retain done when primitively loading from
  1052. the weak reference).
  1053. For the most part, ``__unsafe_unretained`` in non-ARC modes is just the
  1054. default behavior of variables and therefore is not needed. However,
  1055. it does have an effect on the semantics of block captures: normally,
  1056. copying a block which captures an Objective-C object or block pointer
  1057. causes the captured pointer to be retained or copied, respectively,
  1058. but that behavior is suppressed when the captured variable is qualified
  1059. with ``__unsafe_unretained``.
  1060. Note that the ``__weak`` qualifier formerly meant the GC qualifier in
  1061. all non-ARC modes and was silently ignored outside of GC modes. It now
  1062. means the ARC-style qualifier in all non-GC modes and is no longer
  1063. allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``.
  1064. It is expected that ``-fobjc-weak`` will eventually be enabled by default
  1065. in all non-GC Objective-C modes.
  1066. .. _objc-fixed-enum:
  1067. Enumerations with a fixed underlying type
  1068. -----------------------------------------
  1069. Clang provides support for C++11 enumerations with a fixed underlying type
  1070. within Objective-C. For example, one can write an enumeration type as:
  1071. .. code-block:: c++
  1072. typedef enum : unsigned char { Red, Green, Blue } Color;
  1073. This specifies that the underlying type, which is used to store the enumeration
  1074. value, is ``unsigned char``.
  1075. Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
  1076. underlying types is available in Objective-C.
  1077. Interoperability with C++11 lambdas
  1078. -----------------------------------
  1079. Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
  1080. permitting a lambda to be implicitly converted to a block pointer with the
  1081. corresponding signature. For example, consider an API such as ``NSArray``'s
  1082. array-sorting method:
  1083. .. code-block:: objc
  1084. - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
  1085. ``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
  1086. (^)(id, id)``, and parameters of this type are generally provided with block
  1087. literals as arguments. However, one can also use a C++11 lambda so long as it
  1088. provides the same signature (in this case, accepting two parameters of type
  1089. ``id`` and returning an ``NSComparisonResult``):
  1090. .. code-block:: objc
  1091. NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
  1092. @"String 02"];
  1093. const NSStringCompareOptions comparisonOptions
  1094. = NSCaseInsensitiveSearch | NSNumericSearch |
  1095. NSWidthInsensitiveSearch | NSForcedOrderingSearch;
  1096. NSLocale *currentLocale = [NSLocale currentLocale];
  1097. NSArray *sorted
  1098. = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
  1099. NSRange string1Range = NSMakeRange(0, [s1 length]);
  1100. return [s1 compare:s2 options:comparisonOptions
  1101. range:string1Range locale:currentLocale];
  1102. }];
  1103. NSLog(@"sorted: %@", sorted);
  1104. This code relies on an implicit conversion from the type of the lambda
  1105. expression (an unnamed, local class type called the *closure type*) to the
  1106. corresponding block pointer type. The conversion itself is expressed by a
  1107. conversion operator in that closure type that produces a block pointer with the
  1108. same signature as the lambda itself, e.g.,
  1109. .. code-block:: objc
  1110. operator NSComparisonResult (^)(id, id)() const;
  1111. This conversion function returns a new block that simply forwards the two
  1112. parameters to the lambda object (which it captures by copy), then returns the
  1113. result. The returned block is first copied (with ``Block_copy``) and then
  1114. autoreleased. As an optimization, if a lambda expression is immediately
  1115. converted to a block pointer (as in the first example, above), then the block
  1116. is not copied and autoreleased: rather, it is given the same lifetime as a
  1117. block literal written at that point in the program, which avoids the overhead
  1118. of copying a block to the heap in the common case.
  1119. The conversion from a lambda to a block pointer is only available in
  1120. Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
  1121. management (autorelease).
  1122. Object Literals and Subscripting
  1123. --------------------------------
  1124. Clang provides support for :doc:`Object Literals and Subscripting
  1125. <ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
  1126. programming patterns, makes programs more concise, and improves the safety of
  1127. container creation. There are several feature macros associated with object
  1128. literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
  1129. availability of array literals; ``__has_feature(objc_dictionary_literals)``
  1130. tests the availability of dictionary literals;
  1131. ``__has_feature(objc_subscripting)`` tests the availability of object
  1132. subscripting.
  1133. Objective-C Autosynthesis of Properties
  1134. ---------------------------------------
  1135. Clang provides support for autosynthesis of declared properties. Using this
  1136. feature, clang provides default synthesis of those properties not declared
  1137. @dynamic and not having user provided backing getter and setter methods.
  1138. ``__has_feature(objc_default_synthesize_properties)`` checks for availability
  1139. of this feature in version of clang being used.
  1140. .. _langext-objc-retain-release:
  1141. Objective-C retaining behavior attributes
  1142. -----------------------------------------
  1143. In Objective-C, functions and methods are generally assumed to follow the
  1144. `Cocoa Memory Management
  1145. <https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
  1146. conventions for ownership of object arguments and
  1147. return values. However, there are exceptions, and so Clang provides attributes
  1148. to allow these exceptions to be documented. This are used by ARC and the
  1149. `static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be
  1150. better described using the ``objc_method_family`` attribute instead.
  1151. **Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
  1152. ``ns_returns_autoreleased``, ``cf_returns_retained``, and
  1153. ``cf_returns_not_retained`` attributes can be placed on methods and functions
  1154. that return Objective-C or CoreFoundation objects. They are commonly placed at
  1155. the end of a function prototype or method declaration:
  1156. .. code-block:: objc
  1157. id foo() __attribute__((ns_returns_retained));
  1158. - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
  1159. The ``*_returns_retained`` attributes specify that the returned object has a +1
  1160. retain count. The ``*_returns_not_retained`` attributes specify that the return
  1161. object has a +0 retain count, even if the normal convention for its selector
  1162. would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
  1163. +0, but is guaranteed to live at least as long as the next flush of an
  1164. autorelease pool.
  1165. **Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
  1166. an parameter declaration; they specify that the argument is expected to have a
  1167. +1 retain count, which will be balanced in some way by the function or method.
  1168. The ``ns_consumes_self`` attribute can only be placed on an Objective-C
  1169. method; it specifies that the method expects its ``self`` parameter to have a
  1170. +1 retain count, which it will balance in some way.
  1171. .. code-block:: objc
  1172. void foo(__attribute__((ns_consumed)) NSString *string);
  1173. - (void) bar __attribute__((ns_consumes_self));
  1174. - (void) baz:(id) __attribute__((ns_consumed)) x;
  1175. Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
  1176. <https://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
  1177. Query for these features with ``__has_attribute(ns_consumed)``,
  1178. ``__has_attribute(ns_returns_retained)``, etc.
  1179. Objective-C @available
  1180. ----------------------
  1181. It is possible to use the newest SDK but still build a program that can run on
  1182. older versions of macOS and iOS by passing ``-mmacosx-version-min=`` /
  1183. ``-miphoneos-version-min=``.
  1184. Before LLVM 5.0, when calling a function that exists only in the OS that's
  1185. newer than the target OS (as determined by the minimum deployment version),
  1186. programmers had to carefully check if the function exists at runtime, using
  1187. null checks for weakly-linked C functions, ``+class`` for Objective-C classes,
  1188. and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for
  1189. Objective-C methods. If such a check was missed, the program would compile
  1190. fine, run fine on newer systems, but crash on older systems.
  1191. As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes
  1192. <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together
  1193. with the new ``@available()`` keyword to assist with this issue.
  1194. When a method that's introduced in the OS newer than the target OS is called, a
  1195. -Wunguarded-availability warning is emitted if that call is not guarded:
  1196. .. code-block:: objc
  1197. void my_fun(NSSomeClass* var) {
  1198. // If fancyNewMethod was added in e.g. macOS 10.12, but the code is
  1199. // built with -mmacosx-version-min=10.11, then this unconditional call
  1200. // will emit a -Wunguarded-availability warning:
  1201. [var fancyNewMethod];
  1202. }
  1203. To fix the warning and to avoid the crash on macOS 10.11, wrap it in
  1204. ``if(@available())``:
  1205. .. code-block:: objc
  1206. void my_fun(NSSomeClass* var) {
  1207. if (@available(macOS 10.12, *)) {
  1208. [var fancyNewMethod];
  1209. } else {
  1210. // Put fallback behavior for old macOS versions (and for non-mac
  1211. // platforms) here.
  1212. }
  1213. }
  1214. The ``*`` is required and means that platforms not explicitly listed will take
  1215. the true branch, and the compiler will emit ``-Wunguarded-availability``
  1216. warnings for unlisted platforms based on those platform's deployment target.
  1217. More than one platform can be listed in ``@available()``:
  1218. .. code-block:: objc
  1219. void my_fun(NSSomeClass* var) {
  1220. if (@available(macOS 10.12, iOS 10, *)) {
  1221. [var fancyNewMethod];
  1222. }
  1223. }
  1224. If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called
  1225. on 10.12, then add an `availability attribute
  1226. <https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it,
  1227. which will also suppress the warning and require that calls to my_fun() are
  1228. checked:
  1229. .. code-block:: objc
  1230. API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {
  1231. [var fancyNewMethod]; // Now ok.
  1232. }
  1233. ``@available()`` is only available in Objective-C code. To use the feature
  1234. in C and C++ code, use the ``__builtin_available()`` spelling instead.
  1235. If existing code uses null checks or ``-respondsToSelector:``, it should
  1236. be changed to use ``@available()`` (or ``__builtin_available``) instead.
  1237. ``-Wunguarded-availability`` is disabled by default, but
  1238. ``-Wunguarded-availability-new``, which only emits this warning for APIs
  1239. that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and
  1240. tvOS >= 11, is enabled by default.
  1241. .. _langext-overloading:
  1242. Objective-C++ ABI: protocol-qualifier mangling of parameters
  1243. ------------------------------------------------------------
  1244. Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
  1245. type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such
  1246. parameters to be differentiated from those with the regular unqualified ``id``
  1247. type.
  1248. This was a non-backward compatible mangling change to the ABI. This change
  1249. allows proper overloading, and also prevents mangling conflicts with template
  1250. parameters of protocol-qualified type.
  1251. Query the presence of this new mangling with
  1252. ``__has_feature(objc_protocol_qualifier_mangling)``.
  1253. OpenCL Features
  1254. ===============
  1255. C++ for OpenCL
  1256. --------------
  1257. This functionality is built on top of OpenCL C v2.0 and C++17 enabling most of
  1258. regular C++ features in OpenCL kernel code. Most functionality from OpenCL C
  1259. is inherited. This section describes minor differences to OpenCL C and any
  1260. limitations related to C++ support as well as interactions between OpenCL and
  1261. C++ features that are not documented elsewhere.
  1262. Restrictions to C++17
  1263. ^^^^^^^^^^^^^^^^^^^^^
  1264. The following features are not supported:
  1265. - Virtual functions
  1266. - Exceptions
  1267. - ``dynamic_cast`` operator
  1268. - Non-placement ``new``/``delete`` operators
  1269. - Standard C++ libraries. Currently there is no solution for alternative C++
  1270. libraries provided. Future release will feature library support.
  1271. Interplay of OpenCL and C++ features
  1272. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1273. Address space behavior
  1274. """"""""""""""""""""""
  1275. Address spaces are part of the type qualifiers; many rules are just inherited
  1276. from the qualifier behavior documented in OpenCL C v2.0 s6.5 and Embedded C
  1277. extension ISO/IEC JTC1 SC22 WG14 N1021 s3.1. Note that since the address space
  1278. behavior in C++ is not documented formally, Clang extends the existing concept
  1279. from C and OpenCL. For example conversion rules are extended from qualification
  1280. conversion but the compatibility is determined using notation of sets and
  1281. overlapping of address spaces from Embedded C (ISO/IEC JTC1 SC22 WG14 N1021
  1282. s3.1.3). For OpenCL it means that implicit conversions are allowed from
  1283. a named address space (except for ``__constant``) to ``__generic`` (OpenCL C
  1284. v2.0 6.5.5). Reverse conversion is only allowed explicitly. The ``__constant``
  1285. address space does not overlap with any other and therefore no valid conversion
  1286. between ``__constant`` and other address spaces exists. Most of the rules
  1287. follow this logic.
  1288. **Casts**
  1289. C-style casts follow OpenCL C v2.0 rules (s6.5.5). All cast operators
  1290. permit conversion to ``__generic`` implicitly. However converting from
  1291. ``__generic`` to named address spaces can only be done using ``addrspace_cast``.
  1292. Note that conversions between ``__constant`` and any other address space
  1293. are disallowed.
  1294. .. _opencl_cpp_addrsp_deduction:
  1295. **Deduction**
  1296. Address spaces are not deduced for:
  1297. - non-pointer/non-reference template parameters or any dependent types except
  1298. for template specializations.
  1299. - non-pointer/non-reference class members except for static data members that are
  1300. deduced to ``__global`` address space.
  1301. - non-pointer/non-reference alias declarations.
  1302. - ``decltype`` expressions.
  1303. .. code-block:: c++
  1304. template <typename T>
  1305. void foo() {
  1306. T m; // address space of m will be known at template instantiation time.
  1307. T * ptr; // ptr points to __generic address space object.
  1308. T & ref = ...; // ref references an object in __generic address space.
  1309. };
  1310. template <int N>
  1311. struct S {
  1312. int i; // i has no address space
  1313. static int ii; // ii is in global address space
  1314. int * ptr; // ptr points to __generic address space int.
  1315. int & ref = ...; // ref references int in __generic address space.
  1316. };
  1317. template <int N>
  1318. void bar()
  1319. {
  1320. S<N> s; // s is in __private address space
  1321. }
  1322. TODO: Add example for type alias and decltype!
  1323. **References**
  1324. Reference types can be qualified with an address space.
  1325. .. code-block:: c++
  1326. __private int & ref = ...; // references int in __private address space
  1327. By default references will refer to ``__generic`` address space objects, except
  1328. for dependent types that are not template specializations
  1329. (see :ref:`Deduction <opencl_cpp_addrsp_deduction>`). Address space compatibility
  1330. checks are performed when references are bound to values. The logic follows the
  1331. rules from address space pointer conversion (OpenCL v2.0 s6.5.5).
  1332. **Default address space**
  1333. All non-static member functions take an implicit object parameter ``this`` that
  1334. is a pointer type. By default this pointer parameter is in the ``__generic``
  1335. address space. All concrete objects passed as an argument to ``this`` parameter
  1336. will be converted to the ``__generic`` address space first if such conversion is
  1337. valid. Therefore programs using objects in the ``__constant`` address space will
  1338. not be compiled unless the address space is explicitly specified using address
  1339. space qualifiers on member functions
  1340. (see :ref:`Member function qualifier <opencl_cpp_addrspace_method_qual>`) as the
  1341. conversion between ``__constant`` and ``__generic`` is disallowed. Member function
  1342. qualifiers can also be used in case conversion to the ``__generic`` address space
  1343. is undesirable (even if it is legal). For example, a method can be implemented to
  1344. exploit memory access coalescing for segments with memory bank. This not only
  1345. applies to regular member functions but to constructors and destructors too.
  1346. .. _opencl_cpp_addrspace_method_qual:
  1347. **Member function qualifier**
  1348. Clang allows specifying an address space qualifier on member functions to signal
  1349. that they are to be used with objects constructed in some specific address space.
  1350. This works just the same as qualifying member functions with ``const`` or any
  1351. other qualifiers. The overloading resolution will select the candidate with the
  1352. most specific address space if multiple candidates are provided. If there is no
  1353. conversion to an address space among candidates, compilation will fail with a
  1354. diagnostic.
  1355. .. code-block:: c++
  1356. struct C {
  1357. void foo() __local;
  1358. void foo();
  1359. };
  1360. __kernel void bar() {
  1361. __local C c1;
  1362. C c2;
  1363. __constant C c3;
  1364. c1.foo(); // will resolve to the first foo
  1365. c2.foo(); // will resolve to the second foo
  1366. c3.foo(); // error due to mismatching address spaces - can't convert to
  1367. // __local or __generic
  1368. }
  1369. **Implicit special members**
  1370. All implicit special members (default, copy, or move constructor, copy or move
  1371. assignment, destructor) will be generated with the ``__generic`` address space.
  1372. .. code-block:: c++
  1373. class C {
  1374. // Has the following implicit definition
  1375. // void C() __generic;
  1376. // void C(const __generic C &) __generic;
  1377. // void C(__generic C &&) __generic;
  1378. // operator= '__generic C &(__generic C &&)'
  1379. // operator= '__generic C &(const __generic C &) __generic
  1380. }
  1381. **Builtin operators**
  1382. All builtin operators are available in the specific address spaces, thus no
  1383. conversion to ``__generic`` is performed.
  1384. **Templates**
  1385. There is no deduction of address spaces in non-pointer/non-reference template
  1386. parameters and dependent types (see :ref:`Deduction <opencl_cpp_addrsp_deduction>`).
  1387. The address space of a template parameter is deduced during type deduction if
  1388. it is not explicitly provided in the instantiation.
  1389. .. code-block:: c++
  1390. 1 template<typename T>
  1391. 2 void foo(T* i){
  1392. 3 T var;
  1393. 4 }
  1394. 5
  1395. 6 __global int g;
  1396. 7 void bar(){
  1397. 8 foo(&g); // error: template instantiation failed as function scope variable
  1398. 9 // appears to be declared in __global address space (see line 3)
  1399. 10 }
  1400. It is not legal to specify multiple different address spaces between template
  1401. definition and instantiation. If multiple different address spaces are specified in
  1402. template definition and instantiation, compilation of such a program will fail with
  1403. a diagnostic.
  1404. .. code-block:: c++
  1405. template <typename T>
  1406. void foo() {
  1407. __private T var;
  1408. }
  1409. void bar() {
  1410. foo<__global int>(); // error: conflicting address space qualifiers are provided
  1411. // __global and __private
  1412. }
  1413. Once a template has been instantiated, regular restrictions for address spaces will
  1414. apply.
  1415. .. code-block:: c++
  1416. template<typename T>
  1417. void foo(){
  1418. T var;
  1419. }
  1420. void bar(){
  1421. foo<__global int>(); // error: function scope variable cannot be declared in
  1422. // __global address space
  1423. }
  1424. **Temporary materialization**
  1425. All temporaries are materialized in the ``__private`` address space. If a
  1426. reference with another address space is bound to them, the conversion will be
  1427. generated in case it is valid, otherwise compilation will fail with a diagnostic.
  1428. .. code-block:: c++
  1429. int bar(const unsigned int &i);
  1430. void foo() {
  1431. bar(1); // temporary is created in __private address space but converted
  1432. // to __generic address space of parameter reference
  1433. }
  1434. __global const int& f(__global float &ref) {
  1435. return ref; // error: address space mismatch between temporary object
  1436. // created to hold value converted float->int and return
  1437. // value type (can't convert from __private to __global)
  1438. }
  1439. **Initialization of local and constant address space objects**
  1440. TODO
  1441. Constructing and destroying global objects
  1442. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1443. Global objects must be constructed before the first kernel using the global
  1444. objects is executed and destroyed just after the last kernel using the
  1445. program objects is executed. In OpenCL v2.0 drivers there is no specific
  1446. API for invoking global constructors. However, an easy workaround would be
  1447. to enqueue a constructor initialization kernel that has a name
  1448. ``@_GLOBAL__sub_I_<compiled file name>``. This kernel is only present if there
  1449. are any global objects to be initialized in the compiled binary. One way to
  1450. check this is by passing ``CL_PROGRAM_KERNEL_NAMES`` to ``clGetProgramInfo``
  1451. (OpenCL v2.0 s5.8.7).
  1452. Note that if multiple files are compiled and linked into libraries, multiple
  1453. kernels that initialize global objects for multiple modules would have to be
  1454. invoked.
  1455. Applications are currently required to run initialization of global objects
  1456. manually before running any kernels in which the objects are used.
  1457. .. code-block:: console
  1458. clang -cl-std=clc++ test.cl
  1459. If there are any global objects to be initialized, the final binary will
  1460. contain the ``@_GLOBAL__sub_I_test.cl`` kernel to be enqueued.
  1461. Global destructors can not be invoked in OpenCL v2.0 drivers. However, all
  1462. memory used for program scope objects is released on ``clReleaseProgram``.
  1463. Initializer lists for complex numbers in C
  1464. ==========================================
  1465. clang supports an extension which allows the following in C:
  1466. .. code-block:: c++
  1467. #include <math.h>
  1468. #include <complex.h>
  1469. complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
  1470. This construct is useful because there is no way to separately initialize the
  1471. real and imaginary parts of a complex variable in standard C, given that clang
  1472. does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
  1473. ``__imag__`` extensions from gcc, which help in some cases, but are not usable
  1474. in static initializers.)
  1475. Note that this extension does not allow eliding the braces; the meaning of the
  1476. following two lines is different:
  1477. .. code-block:: c++
  1478. complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
  1479. complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
  1480. This extension also works in C++ mode, as far as that goes, but does not apply
  1481. to the C++ ``std::complex``. (In C++11, list initialization allows the same
  1482. syntax to be used with ``std::complex`` with the same meaning.)
  1483. Builtin Functions
  1484. =================
  1485. Clang supports a number of builtin library functions with the same syntax as
  1486. GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
  1487. ``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
  1488. ``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to
  1489. the GCC builtins, Clang supports a number of builtins that GCC does not, which
  1490. are listed here.
  1491. Please note that Clang does not and will not support all of the GCC builtins
  1492. for vector operations. Instead of using builtins, you should use the functions
  1493. defined in target-specific header files like ``<xmmintrin.h>``, which define
  1494. portable wrappers for these. Many of the Clang versions of these functions are
  1495. implemented directly in terms of :ref:`extended vector support
  1496. <langext-vectors>` instead of builtins, in order to reduce the number of
  1497. builtins that we need to implement.
  1498. ``__builtin_assume``
  1499. ------------------------------
  1500. ``__builtin_assume`` is used to provide the optimizer with a boolean
  1501. invariant that is defined to be true.
  1502. **Syntax**:
  1503. .. code-block:: c++
  1504. __builtin_assume(bool)
  1505. **Example of Use**:
  1506. .. code-block:: c++
  1507. int foo(int x) {
  1508. __builtin_assume(x != 0);
  1509. // The optimizer may short-circuit this check using the invariant.
  1510. if (x == 0)
  1511. return do_something();
  1512. return do_something_else();
  1513. }
  1514. **Description**:
  1515. The boolean argument to this function is defined to be true. The optimizer may
  1516. analyze the form of the expression provided as the argument and deduce from
  1517. that information used to optimize the program. If the condition is violated
  1518. during execution, the behavior is undefined. The argument itself is never
  1519. evaluated, so any side effects of the expression will be discarded.
  1520. Query for this feature with ``__has_builtin(__builtin_assume)``.
  1521. ``__builtin_readcyclecounter``
  1522. ------------------------------
  1523. ``__builtin_readcyclecounter`` is used to access the cycle counter register (or
  1524. a similar low-latency, high-accuracy clock) on those targets that support it.
  1525. **Syntax**:
  1526. .. code-block:: c++
  1527. __builtin_readcyclecounter()
  1528. **Example of Use**:
  1529. .. code-block:: c++
  1530. unsigned long long t0 = __builtin_readcyclecounter();
  1531. do_something();
  1532. unsigned long long t1 = __builtin_readcyclecounter();
  1533. unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
  1534. **Description**:
  1535. The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
  1536. which may be either global or process/thread-specific depending on the target.
  1537. As the backing counters often overflow quickly (on the order of seconds) this
  1538. should only be used for timing small intervals. When not supported by the
  1539. target, the return value is always zero. This builtin takes no arguments and
  1540. produces an unsigned long long result.
  1541. Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
  1542. that even if present, its use may depend on run-time privilege or other OS
  1543. controlled state.
  1544. .. _langext-__builtin_shufflevector:
  1545. ``__builtin_shufflevector``
  1546. ---------------------------
  1547. ``__builtin_shufflevector`` is used to express generic vector
  1548. permutation/shuffle/swizzle operations. This builtin is also very important
  1549. for the implementation of various target-specific header files like
  1550. ``<xmmintrin.h>``.
  1551. **Syntax**:
  1552. .. code-block:: c++
  1553. __builtin_shufflevector(vec1, vec2, index1, index2, ...)
  1554. **Examples**:
  1555. .. code-block:: c++
  1556. // identity operation - return 4-element vector v1.
  1557. __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
  1558. // "Splat" element 0 of V1 into a 4-element result.
  1559. __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
  1560. // Reverse 4-element vector V1.
  1561. __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
  1562. // Concatenate every other element of 4-element vectors V1 and V2.
  1563. __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
  1564. // Concatenate every other element of 8-element vectors V1 and V2.
  1565. __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
  1566. // Shuffle v1 with some elements being undefined
  1567. __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
  1568. **Description**:
  1569. The first two arguments to ``__builtin_shufflevector`` are vectors that have
  1570. the same element type. The remaining arguments are a list of integers that
  1571. specify the elements indices of the first two vectors that should be extracted
  1572. and returned in a new vector. These element indices are numbered sequentially
  1573. starting with the first vector, continuing into the second vector. Thus, if
  1574. ``vec1`` is a 4-element vector, index 5 would refer to the second element of
  1575. ``vec2``. An index of -1 can be used to indicate that the corresponding element
  1576. in the returned vector is a don't care and can be optimized by the backend.
  1577. The result of ``__builtin_shufflevector`` is a vector with the same element
  1578. type as ``vec1``/``vec2`` but that has an element count equal to the number of
  1579. indices specified.
  1580. Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
  1581. .. _langext-__builtin_convertvector:
  1582. ``__builtin_convertvector``
  1583. ---------------------------
  1584. ``__builtin_convertvector`` is used to express generic vector
  1585. type-conversion operations. The input vector and the output vector
  1586. type must have the same number of elements.
  1587. **Syntax**:
  1588. .. code-block:: c++
  1589. __builtin_convertvector(src_vec, dst_vec_type)
  1590. **Examples**:
  1591. .. code-block:: c++
  1592. typedef double vector4double __attribute__((__vector_size__(32)));
  1593. typedef float vector4float __attribute__((__vector_size__(16)));
  1594. typedef short vector4short __attribute__((__vector_size__(8)));
  1595. vector4float vf; vector4short vs;
  1596. // convert from a vector of 4 floats to a vector of 4 doubles.
  1597. __builtin_convertvector(vf, vector4double)
  1598. // equivalent to:
  1599. (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
  1600. // convert from a vector of 4 shorts to a vector of 4 floats.
  1601. __builtin_convertvector(vs, vector4float)
  1602. // equivalent to:
  1603. (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
  1604. **Description**:
  1605. The first argument to ``__builtin_convertvector`` is a vector, and the second
  1606. argument is a vector type with the same number of elements as the first
  1607. argument.
  1608. The result of ``__builtin_convertvector`` is a vector with the same element
  1609. type as the second argument, with a value defined in terms of the action of a
  1610. C-style cast applied to each element of the first argument.
  1611. Query for this feature with ``__has_builtin(__builtin_convertvector)``.
  1612. ``__builtin_bitreverse``
  1613. ------------------------
  1614. * ``__builtin_bitreverse8``
  1615. * ``__builtin_bitreverse16``
  1616. * ``__builtin_bitreverse32``
  1617. * ``__builtin_bitreverse64``
  1618. **Syntax**:
  1619. .. code-block:: c++
  1620. __builtin_bitreverse32(x)
  1621. **Examples**:
  1622. .. code-block:: c++
  1623. uint8_t rev_x = __builtin_bitreverse8(x);
  1624. uint16_t rev_x = __builtin_bitreverse16(x);
  1625. uint32_t rev_y = __builtin_bitreverse32(y);
  1626. uint64_t rev_z = __builtin_bitreverse64(z);
  1627. **Description**:
  1628. The '``__builtin_bitreverse``' family of builtins is used to reverse
  1629. the bitpattern of an integer value; for example ``0b10110110`` becomes
  1630. ``0b01101101``.
  1631. ``__builtin_rotateleft``
  1632. ------------------------
  1633. * ``__builtin_rotateleft8``
  1634. * ``__builtin_rotateleft16``
  1635. * ``__builtin_rotateleft32``
  1636. * ``__builtin_rotateleft64``
  1637. **Syntax**:
  1638. .. code-block:: c++
  1639. __builtin_rotateleft32(x, y)
  1640. **Examples**:
  1641. .. code-block:: c++
  1642. uint8_t rot_x = __builtin_rotateleft8(x, y);
  1643. uint16_t rot_x = __builtin_rotateleft16(x, y);
  1644. uint32_t rot_x = __builtin_rotateleft32(x, y);
  1645. uint64_t rot_x = __builtin_rotateleft64(x, y);
  1646. **Description**:
  1647. The '``__builtin_rotateleft``' family of builtins is used to rotate
  1648. the bits in the first argument by the amount in the second argument.
  1649. For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``.
  1650. The shift value is treated as an unsigned amount modulo the size of
  1651. the arguments. Both arguments and the result have the bitwidth specified
  1652. by the name of the builtin.
  1653. ``__builtin_rotateright``
  1654. -------------------------
  1655. * ``__builtin_rotateright8``
  1656. * ``__builtin_rotateright16``
  1657. * ``__builtin_rotateright32``
  1658. * ``__builtin_rotateright64``
  1659. **Syntax**:
  1660. .. code-block:: c++
  1661. __builtin_rotateright32(x, y)
  1662. **Examples**:
  1663. .. code-block:: c++
  1664. uint8_t rot_x = __builtin_rotateright8(x, y);
  1665. uint16_t rot_x = __builtin_rotateright16(x, y);
  1666. uint32_t rot_x = __builtin_rotateright32(x, y);
  1667. uint64_t rot_x = __builtin_rotateright64(x, y);
  1668. **Description**:
  1669. The '``__builtin_rotateright``' family of builtins is used to rotate
  1670. the bits in the first argument by the amount in the second argument.
  1671. For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``.
  1672. The shift value is treated as an unsigned amount modulo the size of
  1673. the arguments. Both arguments and the result have the bitwidth specified
  1674. by the name of the builtin.
  1675. ``__builtin_unreachable``
  1676. -------------------------
  1677. ``__builtin_unreachable`` is used to indicate that a specific point in the
  1678. program cannot be reached, even if the compiler might otherwise think it can.
  1679. This is useful to improve optimization and eliminates certain warnings. For
  1680. example, without the ``__builtin_unreachable`` in the example below, the
  1681. compiler assumes that the inline asm can fall through and prints a "function
  1682. declared '``noreturn``' should not return" warning.
  1683. **Syntax**:
  1684. .. code-block:: c++
  1685. __builtin_unreachable()
  1686. **Example of use**:
  1687. .. code-block:: c++
  1688. void myabort(void) __attribute__((noreturn));
  1689. void myabort(void) {
  1690. asm("int3");
  1691. __builtin_unreachable();
  1692. }
  1693. **Description**:
  1694. The ``__builtin_unreachable()`` builtin has completely undefined behavior.
  1695. Since it has undefined behavior, it is a statement that it is never reached and
  1696. the optimizer can take advantage of this to produce better code. This builtin
  1697. takes no arguments and produces a void result.
  1698. Query for this feature with ``__has_builtin(__builtin_unreachable)``.
  1699. ``__builtin_unpredictable``
  1700. ---------------------------
  1701. ``__builtin_unpredictable`` is used to indicate that a branch condition is
  1702. unpredictable by hardware mechanisms such as branch prediction logic.
  1703. **Syntax**:
  1704. .. code-block:: c++
  1705. __builtin_unpredictable(long long)
  1706. **Example of use**:
  1707. .. code-block:: c++
  1708. if (__builtin_unpredictable(x > 0)) {
  1709. foo();
  1710. }
  1711. **Description**:
  1712. The ``__builtin_unpredictable()`` builtin is expected to be used with control
  1713. flow conditions such as in ``if`` and ``switch`` statements.
  1714. Query for this feature with ``__has_builtin(__builtin_unpredictable)``.
  1715. ``__sync_swap``
  1716. ---------------
  1717. ``__sync_swap`` is used to atomically swap integers or pointers in memory.
  1718. **Syntax**:
  1719. .. code-block:: c++
  1720. type __sync_swap(type *ptr, type value, ...)
  1721. **Example of Use**:
  1722. .. code-block:: c++
  1723. int old_value = __sync_swap(&value, new_value);
  1724. **Description**:
  1725. The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
  1726. atomic intrinsics to allow code to atomically swap the current value with the
  1727. new value. More importantly, it helps developers write more efficient and
  1728. correct code by avoiding expensive loops around
  1729. ``__sync_bool_compare_and_swap()`` or relying on the platform specific
  1730. implementation details of ``__sync_lock_test_and_set()``. The
  1731. ``__sync_swap()`` builtin is a full barrier.
  1732. ``__builtin_addressof``
  1733. -----------------------
  1734. ``__builtin_addressof`` performs the functionality of the built-in ``&``
  1735. operator, ignoring any ``operator&`` overload. This is useful in constant
  1736. expressions in C++11, where there is no other way to take the address of an
  1737. object that overloads ``operator&``.
  1738. **Example of use**:
  1739. .. code-block:: c++
  1740. template<typename T> constexpr T *addressof(T &value) {
  1741. return __builtin_addressof(value);
  1742. }
  1743. ``__builtin_operator_new`` and ``__builtin_operator_delete``
  1744. ------------------------------------------------------------
  1745. ``__builtin_operator_new`` allocates memory just like a non-placement non-class
  1746. *new-expression*. This is exactly like directly calling the normal
  1747. non-placement ``::operator new``, except that it allows certain optimizations
  1748. that the C++ standard does not permit for a direct function call to
  1749. ``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
  1750. merging allocations).
  1751. Likewise, ``__builtin_operator_delete`` deallocates memory just like a
  1752. non-class *delete-expression*, and is exactly like directly calling the normal
  1753. ``::operator delete``, except that it permits optimizations. Only the unsized
  1754. form of ``__builtin_operator_delete`` is currently available.
  1755. These builtins are intended for use in the implementation of ``std::allocator``
  1756. and other similar allocation libraries, and are only available in C++.
  1757. ``__builtin_preserve_access_index``
  1758. -----------------------------------
  1759. ``__builtin_preserve_access_index`` specifies a code section where
  1760. array subscript access and structure/union member access are relocatable
  1761. under bpf compile-once run-everywhere framework. Debuginfo (typically
  1762. with ``-g``) is needed, otherwise, the compiler will exit with an error.
  1763. The return type for the intrinsic is the same as the type of the
  1764. argument.
  1765. **Syntax**:
  1766. .. code-block:: c
  1767. type __builtin_preserve_access_index(type arg)
  1768. **Example of Use**:
  1769. .. code-block:: c
  1770. struct t {
  1771. int i;
  1772. int j;
  1773. union {
  1774. int a;
  1775. int b;
  1776. } c[4];
  1777. };
  1778. struct t *v = ...;
  1779. int *pb =__builtin_preserve_access_index(&v->c[3].b);
  1780. __builtin_preserve_access_index(v->j);
  1781. Multiprecision Arithmetic Builtins
  1782. ----------------------------------
  1783. Clang provides a set of builtins which expose multiprecision arithmetic in a
  1784. manner amenable to C. They all have the following form:
  1785. .. code-block:: c
  1786. unsigned x = ..., y = ..., carryin = ..., carryout;
  1787. unsigned sum = __builtin_addc(x, y, carryin, &carryout);
  1788. Thus one can form a multiprecision addition chain in the following manner:
  1789. .. code-block:: c
  1790. unsigned *x, *y, *z, carryin=0, carryout;
  1791. z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
  1792. carryin = carryout;
  1793. z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
  1794. carryin = carryout;
  1795. z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
  1796. carryin = carryout;
  1797. z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
  1798. The complete list of builtins are:
  1799. .. code-block:: c
  1800. unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
  1801. unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
  1802. unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
  1803. unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
  1804. unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
  1805. unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
  1806. unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
  1807. unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
  1808. unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
  1809. unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
  1810. Checked Arithmetic Builtins
  1811. ---------------------------
  1812. Clang provides a set of builtins that implement checked arithmetic for security
  1813. critical applications in a manner that is fast and easily expressable in C. As
  1814. an example of their usage:
  1815. .. code-block:: c
  1816. errorcode_t security_critical_application(...) {
  1817. unsigned x, y, result;
  1818. ...
  1819. if (__builtin_mul_overflow(x, y, &result))
  1820. return kErrorCodeHackers;
  1821. ...
  1822. use_multiply(result);
  1823. ...
  1824. }
  1825. Clang provides the following checked arithmetic builtins:
  1826. .. code-block:: c
  1827. bool __builtin_add_overflow (type1 x, type2 y, type3 *sum);
  1828. bool __builtin_sub_overflow (type1 x, type2 y, type3 *diff);
  1829. bool __builtin_mul_overflow (type1 x, type2 y, type3 *prod);
  1830. bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
  1831. bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
  1832. bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
  1833. bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
  1834. bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
  1835. bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
  1836. bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
  1837. bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
  1838. bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
  1839. bool __builtin_sadd_overflow (int x, int y, int *sum);
  1840. bool __builtin_saddl_overflow (long x, long y, long *sum);
  1841. bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
  1842. bool __builtin_ssub_overflow (int x, int y, int *diff);
  1843. bool __builtin_ssubl_overflow (long x, long y, long *diff);
  1844. bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
  1845. bool __builtin_smul_overflow (int x, int y, int *prod);
  1846. bool __builtin_smull_overflow (long x, long y, long *prod);
  1847. bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
  1848. Each builtin performs the specified mathematical operation on the
  1849. first two arguments and stores the result in the third argument. If
  1850. possible, the result will be equal to mathematically-correct result
  1851. and the builtin will return 0. Otherwise, the builtin will return
  1852. 1 and the result will be equal to the unique value that is equivalent
  1853. to the mathematically-correct result modulo two raised to the *k*
  1854. power, where *k* is the number of bits in the result type. The
  1855. behavior of these builtins is well-defined for all argument values.
  1856. The first three builtins work generically for operands of any integer type,
  1857. including boolean types. The operands need not have the same type as each
  1858. other, or as the result. The other builtins may implicitly promote or
  1859. convert their operands before performing the operation.
  1860. Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc.
  1861. Floating point builtins
  1862. ---------------------------------------
  1863. ``__builtin_canonicalize``
  1864. --------------------------
  1865. .. code-block:: c
  1866. double __builtin_canonicalize(double);
  1867. float __builtin_canonicalizef(float);
  1868. long double__builtin_canonicalizel(long double);
  1869. Returns the platform specific canonical encoding of a floating point
  1870. number. This canonicalization is useful for implementing certain
  1871. numeric primitives such as frexp. See `LLVM canonicalize intrinsic
  1872. <https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for
  1873. more information on the semantics.
  1874. String builtins
  1875. ---------------
  1876. Clang provides constant expression evaluation support for builtins forms of
  1877. the following functions from the C standard library ``<string.h>`` header:
  1878. * ``memchr``
  1879. * ``memcmp``
  1880. * ``strchr``
  1881. * ``strcmp``
  1882. * ``strlen``
  1883. * ``strncmp``
  1884. * ``wcschr``
  1885. * ``wcscmp``
  1886. * ``wcslen``
  1887. * ``wcsncmp``
  1888. * ``wmemchr``
  1889. * ``wmemcmp``
  1890. In each case, the builtin form has the name of the C library function prefixed
  1891. by ``__builtin_``. Example:
  1892. .. code-block:: c
  1893. void *p = __builtin_memchr("foobar", 'b', 5);
  1894. In addition to the above, one further builtin is provided:
  1895. .. code-block:: c
  1896. char *__builtin_char_memchr(const char *haystack, int needle, size_t size);
  1897. ``__builtin_char_memchr(a, b, c)`` is identical to
  1898. ``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within
  1899. constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*``
  1900. is disallowed in general).
  1901. Support for constant expression evaluation for the above builtins be detected
  1902. with ``__has_feature(cxx_constexpr_string_builtins)``.
  1903. Atomic Min/Max builtins with memory ordering
  1904. --------------------------------------------
  1905. There are two atomic builtins with min/max in-memory comparison and swap.
  1906. The syntax and semantics are similar to GCC-compatible __atomic_* builtins.
  1907. * ``__atomic_fetch_min``
  1908. * ``__atomic_fetch_max``
  1909. The builtins work with signed and unsigned integers and require to specify memory ordering.
  1910. The return value is the original value that was stored in memory before comparison.
  1911. Example:
  1912. .. code-block:: c
  1913. unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);
  1914. The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``,
  1915. ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``,
  1916. ``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics.
  1917. In terms or aquire-release ordering barriers these two operations are always
  1918. considered as operations with *load-store* semantics, even when the original value
  1919. is not actually modified after comparison.
  1920. .. _langext-__c11_atomic:
  1921. __c11_atomic builtins
  1922. ---------------------
  1923. Clang provides a set of builtins which are intended to be used to implement
  1924. C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
  1925. ``_explicit`` form of the corresponding C11 operation, and are named with a
  1926. ``__c11_`` prefix. The supported operations, and the differences from
  1927. the corresponding C11 operations, are:
  1928. * ``__c11_atomic_init``
  1929. * ``__c11_atomic_thread_fence``
  1930. * ``__c11_atomic_signal_fence``
  1931. * ``__c11_atomic_is_lock_free`` (The argument is the size of the
  1932. ``_Atomic(...)`` object, instead of its address)
  1933. * ``__c11_atomic_store``
  1934. * ``__c11_atomic_load``
  1935. * ``__c11_atomic_exchange``
  1936. * ``__c11_atomic_compare_exchange_strong``
  1937. * ``__c11_atomic_compare_exchange_weak``
  1938. * ``__c11_atomic_fetch_add``
  1939. * ``__c11_atomic_fetch_sub``
  1940. * ``__c11_atomic_fetch_and``
  1941. * ``__c11_atomic_fetch_or``
  1942. * ``__c11_atomic_fetch_xor``
  1943. The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
  1944. ``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
  1945. provided, with values corresponding to the enumerators of C11's
  1946. ``memory_order`` enumeration.
  1947. (Note that Clang additionally provides GCC-compatible ``__atomic_*``
  1948. builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0
  1949. atomic builtins are an explicit form of the corresponding OpenCL 2.0
  1950. builtin function, and are named with a ``__opencl_`` prefix. The macros
  1951. ``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``,
  1952. ``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``,
  1953. and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values
  1954. corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.)
  1955. Low-level ARM exclusive memory builtins
  1956. ---------------------------------------
  1957. Clang provides overloaded builtins giving direct access to the three key ARM
  1958. instructions for implementing atomic operations.
  1959. .. code-block:: c
  1960. T __builtin_arm_ldrex(const volatile T *addr);
  1961. T __builtin_arm_ldaex(const volatile T *addr);
  1962. int __builtin_arm_strex(T val, volatile T *addr);
  1963. int __builtin_arm_stlex(T val, volatile T *addr);
  1964. void __builtin_arm_clrex(void);
  1965. The types ``T`` currently supported are:
  1966. * Integer types with width at most 64 bits (or 128 bits on AArch64).
  1967. * Floating-point types
  1968. * Pointer types.
  1969. Note that the compiler does not guarantee it will not insert stores which clear
  1970. the exclusive monitor in between an ``ldrex`` type operation and its paired
  1971. ``strex``. In practice this is only usually a risk when the extra store is on
  1972. the same cache line as the variable being modified and Clang will only insert
  1973. stack stores on its own, so it is best not to use these operations on variables
  1974. with automatic storage duration.
  1975. Also, loads and stores may be implicit in code written between the ``ldrex`` and
  1976. ``strex``. Clang will not necessarily mitigate the effects of these either, so
  1977. care should be exercised.
  1978. For these reasons the higher level atomic primitives should be preferred where
  1979. possible.
  1980. Non-temporal load/store builtins
  1981. --------------------------------
  1982. Clang provides overloaded builtins allowing generation of non-temporal memory
  1983. accesses.
  1984. .. code-block:: c
  1985. T __builtin_nontemporal_load(T *addr);
  1986. void __builtin_nontemporal_store(T value, T *addr);
  1987. The types ``T`` currently supported are:
  1988. * Integer types.
  1989. * Floating-point types.
  1990. * Vector types.
  1991. Note that the compiler does not guarantee that non-temporal loads or stores
  1992. will be used.
  1993. C++ Coroutines support builtins
  1994. --------------------------------
  1995. .. warning::
  1996. This is a work in progress. Compatibility across Clang/LLVM releases is not
  1997. guaranteed.
  1998. Clang provides experimental builtins to support C++ Coroutines as defined by
  1999. https://wg21.link/P0057. The following four are intended to be used by the
  2000. standard library to implement `std::experimental::coroutine_handle` type.
  2001. **Syntax**:
  2002. .. code-block:: c
  2003. void __builtin_coro_resume(void *addr);
  2004. void __builtin_coro_destroy(void *addr);
  2005. bool __builtin_coro_done(void *addr);
  2006. void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)
  2007. **Example of use**:
  2008. .. code-block:: c++
  2009. template <> struct coroutine_handle<void> {
  2010. void resume() const { __builtin_coro_resume(ptr); }
  2011. void destroy() const { __builtin_coro_destroy(ptr); }
  2012. bool done() const { return __builtin_coro_done(ptr); }
  2013. // ...
  2014. protected:
  2015. void *ptr;
  2016. };
  2017. template <typename Promise> struct coroutine_handle : coroutine_handle<> {
  2018. // ...
  2019. Promise &promise() const {
  2020. return *reinterpret_cast<Promise *>(
  2021. __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
  2022. }
  2023. static coroutine_handle from_promise(Promise &promise) {
  2024. coroutine_handle p;
  2025. p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
  2026. /*from-promise=*/true);
  2027. return p;
  2028. }
  2029. };
  2030. Other coroutine builtins are either for internal clang use or for use during
  2031. development of the coroutine feature. See `Coroutines in LLVM
  2032. <https://llvm.org/docs/Coroutines.html#intrinsics>`_ for
  2033. more information on their semantics. Note that builtins matching the intrinsics
  2034. that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
  2035. llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
  2036. an appropriate value during the emission.
  2037. **Syntax**:
  2038. .. code-block:: c
  2039. size_t __builtin_coro_size()
  2040. void *__builtin_coro_frame()
  2041. void *__builtin_coro_free(void *coro_frame)
  2042. void *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)
  2043. bool __builtin_coro_alloc()
  2044. void *__builtin_coro_begin(void *memory)
  2045. void __builtin_coro_end(void *coro_frame, bool unwind)
  2046. char __builtin_coro_suspend(bool final)
  2047. bool __builtin_coro_param(void *original, void *copy)
  2048. Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
  2049. automatically will insert one if the first argument to `llvm.coro.suspend` is
  2050. token `none`. If a user calls `__builin_suspend`, clang will insert `token none`
  2051. as the first argument to the intrinsic.
  2052. Source location builtins
  2053. ------------------------
  2054. Clang provides experimental builtins to support C++ standard library implementation
  2055. of ``std::experimental::source_location`` as specified in http://wg21.link/N4600.
  2056. With the exception of ``__builtin_COLUMN``, these builtins are also implemented by
  2057. GCC.
  2058. **Syntax**:
  2059. .. code-block:: c
  2060. const char *__builtin_FILE();
  2061. const char *__builtin_FUNCTION();
  2062. unsigned __builtin_LINE();
  2063. unsigned __builtin_COLUMN(); // Clang only
  2064. **Example of use**:
  2065. .. code-block:: c++
  2066. void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller
  2067. const char* file = __builtin_FILE(),
  2068. const char* function = __builtin_FUNCTION()) {
  2069. if (pred) return;
  2070. printf("%s:%d assertion failed in function %s\n", file, line, function);
  2071. std::abort();
  2072. }
  2073. struct MyAggregateType {
  2074. int x;
  2075. int line = __builtin_LINE(); // captures line where aggregate initialization occurs
  2076. };
  2077. static_assert(MyAggregateType{42}.line == __LINE__);
  2078. struct MyClassType {
  2079. int line = __builtin_LINE(); // captures line of the constructor used during initialization
  2080. constexpr MyClassType(int) { assert(line == __LINE__); }
  2081. };
  2082. **Description**:
  2083. The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, and ``__builtin_FILE`` return
  2084. the values, at the "invocation point", for ``__LINE__``, ``__FUNCTION__``, and
  2085. ``__FILE__`` respectively. These builtins are constant expressions.
  2086. When the builtins appear as part of a default function argument the invocation
  2087. point is the location of the caller. When the builtins appear as part of a
  2088. default member initializer, the invocation point is the location of the
  2089. constructor or aggregate initialization used to create the object. Otherwise
  2090. the invocation point is the same as the location of the builtin.
  2091. When the invocation point of ``__builtin_FUNCTION`` is not a function scope the
  2092. empty string is returned.
  2093. Non-standard C++11 Attributes
  2094. =============================
  2095. Clang's non-standard C++11 attributes live in the ``clang`` attribute
  2096. namespace.
  2097. Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
  2098. are accepted with the ``__attribute__((foo))`` syntax are also accepted as
  2099. ``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
  2100. (see the list of `GCC function attributes
  2101. <https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
  2102. attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
  2103. `GCC type attributes
  2104. <https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
  2105. implementation, these attributes must appertain to the *declarator-id* in a
  2106. declaration, which means they must go either at the start of the declaration or
  2107. immediately after the name being declared.
  2108. For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
  2109. also applies the GNU ``noreturn`` attribute to ``f``.
  2110. .. code-block:: c++
  2111. [[gnu::unused]] int a, f [[gnu::noreturn]] ();
  2112. Target-Specific Extensions
  2113. ==========================
  2114. Clang supports some language features conditionally on some targets.
  2115. ARM/AArch64 Language Extensions
  2116. -------------------------------
  2117. Memory Barrier Intrinsics
  2118. ^^^^^^^^^^^^^^^^^^^^^^^^^
  2119. Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
  2120. in the `ARM C Language Extensions Release 2.0
  2121. <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_.
  2122. Note that these intrinsics are implemented as motion barriers that block
  2123. reordering of memory accesses and side effect instructions. Other instructions
  2124. like simple arithmetic may be reordered around the intrinsic. If you expect to
  2125. have no reordering at all, use inline assembly instead.
  2126. X86/X86-64 Language Extensions
  2127. ------------------------------
  2128. The X86 backend has these language extensions:
  2129. Memory references to specified segments
  2130. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  2131. Annotating a pointer with address space #256 causes it to be code generated
  2132. relative to the X86 GS segment register, address space #257 causes it to be
  2133. relative to the X86 FS segment, and address space #258 causes it to be
  2134. relative to the X86 SS segment. Note that this is a very very low-level
  2135. feature that should only be used if you know what you're doing (for example in
  2136. an OS kernel).
  2137. Here is an example:
  2138. .. code-block:: c++
  2139. #define GS_RELATIVE __attribute__((address_space(256)))
  2140. int foo(int GS_RELATIVE *P) {
  2141. return *P;
  2142. }
  2143. Which compiles to (on X86-32):
  2144. .. code-block:: gas
  2145. _foo:
  2146. movl 4(%esp), %eax
  2147. movl %gs:(%eax), %eax
  2148. ret
  2149. You can also use the GCC compatibility macros ``__seg_fs`` and ``__seg_gs`` for
  2150. the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS``
  2151. indicate their support.
  2152. PowerPC Language Extensions
  2153. ------------------------------
  2154. Set the Floating Point Rounding Mode
  2155. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  2156. PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set
  2157. the floating point rounding mode. This function will use the least significant
  2158. two bits of integer argument to set the floating point rounding mode.
  2159. .. code-block:: c++
  2160. double __builtin_setrnd(int mode);
  2161. The effective values for mode are:
  2162. - 0 - round to nearest
  2163. - 1 - round to zero
  2164. - 2 - round to +infinity
  2165. - 3 - round to -infinity
  2166. Note that the mode argument will modulo 4, so if the integer argument is greater
  2167. than 3, it will only use the least significant two bits of the mode.
  2168. Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``.
  2169. PowerPC cache builtins
  2170. ^^^^^^^^^^^^^^^^^^^^^^
  2171. The PowerPC architecture specifies instructions implementing cache operations.
  2172. Clang provides builtins that give direct programmer access to these cache
  2173. instructions.
  2174. Currently the following builtins are implemented in clang:
  2175. ``__builtin_dcbf`` copies the contents of a modified block from the data cache
  2176. to main memory and flushes the copy from the data cache.
  2177. **Syntax**:
  2178. .. code-block:: c
  2179. void __dcbf(const void* addr); /* Data Cache Block Flush */
  2180. **Example of Use**:
  2181. .. code-block:: c
  2182. int a = 1;
  2183. __builtin_dcbf (&a);
  2184. Extensions for Static Analysis
  2185. ==============================
  2186. Clang supports additional attributes that are useful for documenting program
  2187. invariants and rules for static analysis tools, such as the `Clang Static
  2188. Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented
  2189. in the analyzer's `list of source-level annotations
  2190. <https://clang-analyzer.llvm.org/annotations.html>`_.
  2191. Extensions for Dynamic Analysis
  2192. ===============================
  2193. Use ``__has_feature(address_sanitizer)`` to check if the code is being built
  2194. with :doc:`AddressSanitizer`.
  2195. Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
  2196. with :doc:`ThreadSanitizer`.
  2197. Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
  2198. with :doc:`MemorySanitizer`.
  2199. Use ``__has_feature(safe_stack)`` to check if the code is being built
  2200. with :doc:`SafeStack`.
  2201. Extensions for selectively disabling optimization
  2202. =================================================
  2203. Clang provides a mechanism for selectively disabling optimizations in functions
  2204. and methods.
  2205. To disable optimizations in a single function definition, the GNU-style or C++11
  2206. non-standard attribute ``optnone`` can be used.
  2207. .. code-block:: c++
  2208. // The following functions will not be optimized.
  2209. // GNU-style attribute
  2210. __attribute__((optnone)) int foo() {
  2211. // ... code
  2212. }
  2213. // C++11 attribute
  2214. [[clang::optnone]] int bar() {
  2215. // ... code
  2216. }
  2217. To facilitate disabling optimization for a range of function definitions, a
  2218. range-based pragma is provided. Its syntax is ``#pragma clang optimize``
  2219. followed by ``off`` or ``on``.
  2220. All function definitions in the region between an ``off`` and the following
  2221. ``on`` will be decorated with the ``optnone`` attribute unless doing so would
  2222. conflict with explicit attributes already present on the function (e.g. the
  2223. ones that control inlining).
  2224. .. code-block:: c++
  2225. #pragma clang optimize off
  2226. // This function will be decorated with optnone.
  2227. int foo() {
  2228. // ... code
  2229. }
  2230. // optnone conflicts with always_inline, so bar() will not be decorated.
  2231. __attribute__((always_inline)) int bar() {
  2232. // ... code
  2233. }
  2234. #pragma clang optimize on
  2235. If no ``on`` is found to close an ``off`` region, the end of the region is the
  2236. end of the compilation unit.
  2237. Note that a stray ``#pragma clang optimize on`` does not selectively enable
  2238. additional optimizations when compiling at low optimization levels. This feature
  2239. can only be used to selectively disable optimizations.
  2240. The pragma has an effect on functions only at the point of their definition; for
  2241. function templates, this means that the state of the pragma at the point of an
  2242. instantiation is not necessarily relevant. Consider the following example:
  2243. .. code-block:: c++
  2244. template<typename T> T twice(T t) {
  2245. return 2 * t;
  2246. }
  2247. #pragma clang optimize off
  2248. template<typename T> T thrice(T t) {
  2249. return 3 * t;
  2250. }
  2251. int container(int a, int b) {
  2252. return twice(a) + thrice(b);
  2253. }
  2254. #pragma clang optimize on
  2255. In this example, the definition of the template function ``twice`` is outside
  2256. the pragma region, whereas the definition of ``thrice`` is inside the region.
  2257. The ``container`` function is also in the region and will not be optimized, but
  2258. it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
  2259. these two instantiations, ``twice`` will be optimized (because its definition
  2260. was outside the region) and ``thrice`` will not be optimized.
  2261. Extensions for loop hint optimizations
  2262. ======================================
  2263. The ``#pragma clang loop`` directive is used to specify hints for optimizing the
  2264. subsequent for, while, do-while, or c++11 range-based for loop. The directive
  2265. provides options for vectorization, interleaving, predication, unrolling and
  2266. distribution. Loop hints can be specified before any loop and will be ignored if
  2267. the optimization is not safe to apply.
  2268. There are loop hints that control transformations (e.g. vectorization, loop
  2269. unrolling) and there are loop hints that set transformation options (e.g.
  2270. ``vectorize_width``, ``unroll_count``). Pragmas setting transformation options
  2271. imply the transformation is enabled, as if it was enabled via the corresponding
  2272. transformation pragma (e.g. ``vectorize(enable)``). If the transformation is
  2273. disabled (e.g. ``vectorize(disable)``), that takes precedence over
  2274. transformations option pragmas implying that transformation.
  2275. Vectorization, Interleaving, and Predication
  2276. --------------------------------------------
  2277. A vectorized loop performs multiple iterations of the original loop
  2278. in parallel using vector instructions. The instruction set of the target
  2279. processor determines which vector instructions are available and their vector
  2280. widths. This restricts the types of loops that can be vectorized. The vectorizer
  2281. automatically determines if the loop is safe and profitable to vectorize. A
  2282. vector instruction cost model is used to select the vector width.
  2283. Interleaving multiple loop iterations allows modern processors to further
  2284. improve instruction-level parallelism (ILP) using advanced hardware features,
  2285. such as multiple execution units and out-of-order execution. The vectorizer uses
  2286. a cost model that depends on the register pressure and generated code size to
  2287. select the interleaving count.
  2288. Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
  2289. by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
  2290. manually enable vectorization or interleaving.
  2291. .. code-block:: c++
  2292. #pragma clang loop vectorize(enable)
  2293. #pragma clang loop interleave(enable)
  2294. for(...) {
  2295. ...
  2296. }
  2297. The vector width is specified by ``vectorize_width(_value_)`` and the interleave
  2298. count is specified by ``interleave_count(_value_)``, where
  2299. _value_ is a positive integer. This is useful for specifying the optimal
  2300. width/count of the set of target architectures supported by your application.
  2301. .. code-block:: c++
  2302. #pragma clang loop vectorize_width(2)
  2303. #pragma clang loop interleave_count(2)
  2304. for(...) {
  2305. ...
  2306. }
  2307. Specifying a width/count of 1 disables the optimization, and is equivalent to
  2308. ``vectorize(disable)`` or ``interleave(disable)``.
  2309. Vector predication is enabled by ``vectorize_predicate(enable)``, for example:
  2310. .. code-block:: c++
  2311. #pragma clang loop vectorize(enable)
  2312. #pragma clang loop vectorize_predicate(enable)
  2313. for(...) {
  2314. ...
  2315. }
  2316. This predicates (masks) all instructions in the loop, which allows the scalar
  2317. remainder loop (the tail) to be folded into the main vectorized loop. This
  2318. might be more efficient when vector predication is efficiently supported by the
  2319. target platform.
  2320. Loop Unrolling
  2321. --------------
  2322. Unrolling a loop reduces the loop control overhead and exposes more
  2323. opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
  2324. eliminates the loop and replaces it with an enumerated sequence of loop
  2325. iterations. Full unrolling is only possible if the loop trip count is known at
  2326. compile time. Partial unrolling replicates the loop body within the loop and
  2327. reduces the trip count.
  2328. If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the
  2329. loop if the trip count is known at compile time. If the fully unrolled code size
  2330. is greater than an internal limit the loop will be partially unrolled up to this
  2331. limit. If the trip count is not known at compile time the loop will be partially
  2332. unrolled with a heuristically chosen unroll factor.
  2333. .. code-block:: c++
  2334. #pragma clang loop unroll(enable)
  2335. for(...) {
  2336. ...
  2337. }
  2338. If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
  2339. loop if the trip count is known at compile time identically to
  2340. ``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled
  2341. if the loop count is not known at compile time.
  2342. .. code-block:: c++
  2343. #pragma clang loop unroll(full)
  2344. for(...) {
  2345. ...
  2346. }
  2347. The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
  2348. _value_ is a positive integer. If this value is greater than the trip count the
  2349. loop will be fully unrolled. Otherwise the loop is partially unrolled subject
  2350. to the same code size limit as with ``unroll(enable)``.
  2351. .. code-block:: c++
  2352. #pragma clang loop unroll_count(8)
  2353. for(...) {
  2354. ...
  2355. }
  2356. Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
  2357. Loop Distribution
  2358. -----------------
  2359. Loop Distribution allows splitting a loop into multiple loops. This is
  2360. beneficial for example when the entire loop cannot be vectorized but some of the
  2361. resulting loops can.
  2362. If ``distribute(enable))`` is specified and the loop has memory dependencies
  2363. that inhibit vectorization, the compiler will attempt to isolate the offending
  2364. operations into a new loop. This optimization is not enabled by default, only
  2365. loops marked with the pragma are considered.
  2366. .. code-block:: c++
  2367. #pragma clang loop distribute(enable)
  2368. for (i = 0; i < N; ++i) {
  2369. S1: A[i + 1] = A[i] + B[i];
  2370. S2: C[i] = D[i] * E[i];
  2371. }
  2372. This loop will be split into two loops between statements S1 and S2. The
  2373. second loop containing S2 will be vectorized.
  2374. Loop Distribution is currently not enabled by default in the optimizer because
  2375. it can hurt performance in some cases. For example, instruction-level
  2376. parallelism could be reduced by sequentializing the execution of the
  2377. statements S1 and S2 above.
  2378. If Loop Distribution is turned on globally with
  2379. ``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can
  2380. be used the disable it on a per-loop basis.
  2381. Additional Information
  2382. ----------------------
  2383. For convenience multiple loop hints can be specified on a single line.
  2384. .. code-block:: c++
  2385. #pragma clang loop vectorize_width(4) interleave_count(8)
  2386. for(...) {
  2387. ...
  2388. }
  2389. If an optimization cannot be applied any hints that apply to it will be ignored.
  2390. For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
  2391. proven safe to vectorize. To identify and diagnose optimization issues use
  2392. `-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
  2393. user guide for details.
  2394. Extensions to specify floating-point flags
  2395. ====================================================
  2396. The ``#pragma clang fp`` pragma allows floating-point options to be specified
  2397. for a section of the source code. This pragma can only appear at file scope or
  2398. at the start of a compound statement (excluding comments). When using within a
  2399. compound statement, the pragma is active within the scope of the compound
  2400. statement.
  2401. Currently, only FP contraction can be controlled with the pragma. ``#pragma
  2402. clang fp contract`` specifies whether the compiler should contract a multiply
  2403. and an addition (or subtraction) into a fused FMA operation when supported by
  2404. the target.
  2405. The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on``
  2406. option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows
  2407. fusion as specified the language standard. The ``fast`` option allows fusiong
  2408. in cases when the language standard does not make this possible (e.g. across
  2409. statements in C)
  2410. .. code-block:: c++
  2411. for(...) {
  2412. #pragma clang fp contract(fast)
  2413. a = b[i] * c[i];
  2414. d[i] += a;
  2415. }
  2416. The pragma can also be used with ``off`` which turns FP contraction off for a
  2417. section of the code. This can be useful when fast contraction is otherwise
  2418. enabled for the translation unit with the ``-ffp-contract=fast`` flag.
  2419. Specifying an attribute for multiple declarations (#pragma clang attribute)
  2420. ===========================================================================
  2421. The ``#pragma clang attribute`` directive can be used to apply an attribute to
  2422. multiple declarations. The ``#pragma clang attribute push`` variation of the
  2423. directive pushes a new "scope" of ``#pragma clang attribute`` that attributes
  2424. can be added to. The ``#pragma clang attribute (...)`` variation adds an
  2425. attribute to that scope, and the ``#pragma clang attribute pop`` variation pops
  2426. the scope. You can also use ``#pragma clang attribute push (...)``, which is a
  2427. shorthand for when you want to add one attribute to a new scope. Multiple push
  2428. directives can be nested inside each other.
  2429. The attributes that are used in the ``#pragma clang attribute`` directives
  2430. can be written using the GNU-style syntax:
  2431. .. code-block:: c++
  2432. #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)
  2433. void function(); // The function now has the annotate("custom") attribute
  2434. #pragma clang attribute pop
  2435. The attributes can also be written using the C++11 style syntax:
  2436. .. code-block:: c++
  2437. #pragma clang attribute push ([[noreturn]], apply_to = function)
  2438. void function(); // The function now has the [[noreturn]] attribute
  2439. #pragma clang attribute pop
  2440. The ``__declspec`` style syntax is also supported:
  2441. .. code-block:: c++
  2442. #pragma clang attribute push (__declspec(dllexport), apply_to = function)
  2443. void function(); // The function now has the __declspec(dllexport) attribute
  2444. #pragma clang attribute pop
  2445. A single push directive accepts only one attribute regardless of the syntax
  2446. used.
  2447. Because multiple push directives can be nested, if you're writing a macro that
  2448. expands to ``_Pragma("clang attribute")`` it's good hygiene (though not
  2449. required) to add a namespace to your push/pop directives. A pop directive with a
  2450. namespace will pop the innermost push that has that same namespace. This will
  2451. ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note
  2452. that an ``pop`` without a namespace will pop the innermost ``push`` without a
  2453. namespace. ``push``es with a namespace can only be popped by ``pop`` with the
  2454. same namespace. For instance:
  2455. .. code-block:: c++
  2456. #define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")
  2457. #define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop")
  2458. #define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")
  2459. #define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop")
  2460. ASSUME_NORETURN_BEGIN
  2461. ASSUME_UNAVAILABLE_BEGIN
  2462. void function(); // function has [[noreturn]] and __attribute__((unavailable))
  2463. ASSUME_NORETURN_END
  2464. void other_function(); // function has __attribute__((unavailable))
  2465. ASSUME_UNAVAILABLE_END
  2466. Without the namespaces on the macros, ``other_function`` will be annotated with
  2467. ``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like
  2468. a contrived example, but its very possible for this kind of situation to appear
  2469. in real code if the pragmas are spread out across a large file. You can test if
  2470. your version of clang supports namespaces on ``#pragma clang attribute`` with
  2471. ``__has_extension(pragma_clang_attribute_namespaces)``.
  2472. Subject Match Rules
  2473. -------------------
  2474. The set of declarations that receive a single attribute from the attribute stack
  2475. depends on the subject match rules that were specified in the pragma. Subject
  2476. match rules are specified after the attribute. The compiler expects an
  2477. identifier that corresponds to the subject set specifier. The ``apply_to``
  2478. specifier is currently the only supported subject set specifier. It allows you
  2479. to specify match rules that form a subset of the attribute's allowed subject
  2480. set, i.e. the compiler doesn't require all of the attribute's subjects. For
  2481. example, an attribute like ``[[nodiscard]]`` whose subject set includes
  2482. ``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at
  2483. least one of these rules after ``apply_to``:
  2484. .. code-block:: c++
  2485. #pragma clang attribute push([[nodiscard]], apply_to = enum)
  2486. enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]
  2487. struct Record1 { }; // The struct will *not* receive [[nodiscard]]
  2488. #pragma clang attribute pop
  2489. #pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))
  2490. enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]
  2491. struct Record2 { }; // The struct *will* receive [[nodiscard]]
  2492. #pragma clang attribute pop
  2493. // This is an error, since [[nodiscard]] can't be applied to namespaces:
  2494. #pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))
  2495. #pragma clang attribute pop
  2496. Multiple match rules can be specified using the ``any`` match rule, as shown
  2497. in the example above. The ``any`` rule applies attributes to all declarations
  2498. that are matched by at least one of the rules in the ``any``. It doesn't nest
  2499. and can't be used inside the other match rules. Redundant match rules or rules
  2500. that conflict with one another should not be used inside of ``any``.
  2501. Clang supports the following match rules:
  2502. - ``function``: Can be used to apply attributes to functions. This includes C++
  2503. member functions, static functions, operators, and constructors/destructors.
  2504. - ``function(is_member)``: Can be used to apply attributes to C++ member
  2505. functions. This includes members like static functions, operators, and
  2506. constructors/destructors.
  2507. - ``hasType(functionType)``: Can be used to apply attributes to functions, C++
  2508. member functions, and variables/fields whose type is a function pointer. It
  2509. does not apply attributes to Objective-C methods or blocks.
  2510. - ``type_alias``: Can be used to apply attributes to ``typedef`` declarations
  2511. and C++11 type aliases.
  2512. - ``record``: Can be used to apply attributes to ``struct``, ``class``, and
  2513. ``union`` declarations.
  2514. - ``record(unless(is_union))``: Can be used to apply attributes only to
  2515. ``struct`` and ``class`` declarations.
  2516. - ``enum``: Can be be used to apply attributes to enumeration declarations.
  2517. - ``enum_constant``: Can be used to apply attributes to enumerators.
  2518. - ``variable``: Can be used to apply attributes to variables, including
  2519. local variables, parameters, global variables, and static member variables.
  2520. It does not apply attributes to instance member variables or Objective-C
  2521. ivars.
  2522. - ``variable(is_thread_local)``: Can be used to apply attributes to thread-local
  2523. variables only.
  2524. - ``variable(is_global)``: Can be used to apply attributes to global variables
  2525. only.
  2526. - ``variable(is_parameter)``: Can be used to apply attributes to parameters
  2527. only.
  2528. - ``variable(unless(is_parameter))``: Can be used to apply attributes to all
  2529. the variables that are not parameters.
  2530. - ``field``: Can be used to apply attributes to non-static member variables
  2531. in a record. This includes Objective-C ivars.
  2532. - ``namespace``: Can be used to apply attributes to ``namespace`` declarations.
  2533. - ``objc_interface``: Can be used to apply attributes to ``@interface``
  2534. declarations.
  2535. - ``objc_protocol``: Can be used to apply attributes to ``@protocol``
  2536. declarations.
  2537. - ``objc_category``: Can be used to apply attributes to category declarations,
  2538. including class extensions.
  2539. - ``objc_method``: Can be used to apply attributes to Objective-C methods,
  2540. including instance and class methods. Implicit methods like implicit property
  2541. getters and setters do not receive the attribute.
  2542. - ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C
  2543. instance methods.
  2544. - ``objc_property``: Can be used to apply attributes to ``@property``
  2545. declarations.
  2546. - ``block``: Can be used to apply attributes to block declarations. This does
  2547. not include variables/fields of block pointer type.
  2548. The use of ``unless`` in match rules is currently restricted to a strict set of
  2549. sub-rules that are used by the supported attributes. That means that even though
  2550. ``variable(unless(is_parameter))`` is a valid match rule,
  2551. ``variable(unless(is_thread_local))`` is not.
  2552. Supported Attributes
  2553. --------------------
  2554. Not all attributes can be used with the ``#pragma clang attribute`` directive.
  2555. Notably, statement attributes like ``[[fallthrough]]`` or type attributes
  2556. like ``address_space`` aren't supported by this directive. You can determine
  2557. whether or not an attribute is supported by the pragma by referring to the
  2558. :doc:`individual documentation for that attribute <AttributeReference>`.
  2559. The attributes are applied to all matching declarations individually, even when
  2560. the attribute is semantically incorrect. The attributes that aren't applied to
  2561. any declaration are not verified semantically.
  2562. Specifying section names for global objects (#pragma clang section)
  2563. ===================================================================
  2564. The ``#pragma clang section`` directive provides a means to assign section-names
  2565. to global variables, functions and static variables.
  2566. The section names can be specified as:
  2567. .. code-block:: c++
  2568. #pragma clang section bss="myBSS" data="myData" rodata="myRodata" relro="myRelro" text="myText"
  2569. The section names can be reverted back to default name by supplying an empty
  2570. string to the section kind, for example:
  2571. .. code-block:: c++
  2572. #pragma clang section bss="" data="" text="" rodata="" relro=""
  2573. The ``#pragma clang section`` directive obeys the following rules:
  2574. * The pragma applies to all global variable, statics and function declarations
  2575. from the pragma to the end of the translation unit.
  2576. * The pragma clang section is enabled automatically, without need of any flags.
  2577. * This feature is only defined to work sensibly for ELF targets.
  2578. * If section name is specified through _attribute_((section("myname"))), then
  2579. the attribute name gains precedence.
  2580. * Global variables that are initialized to zero will be placed in the named
  2581. bss section, if one is present.
  2582. * The ``#pragma clang section`` directive does not does try to infer section-kind
  2583. from the name. For example, naming a section "``.bss.mySec``" does NOT mean
  2584. it will be a bss section name.
  2585. * The decision about which section-kind applies to each global is taken in the back-end.
  2586. Once the section-kind is known, appropriate section name, as specified by the user using
  2587. ``#pragma clang section`` directive, is applied to that global.
  2588. Specifying Linker Options on ELF Targets
  2589. ========================================
  2590. The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets.
  2591. The second parameter is the library name (without the traditional Unix prefix of
  2592. ``lib``). This allows you to provide an implicit link of dependent libraries.
  2593. Evaluating Object Size Dynamically
  2594. ==================================
  2595. Clang supports the builtin ``__builtin_dynamic_object_size``, the semantics are
  2596. the same as GCC's ``__builtin_object_size`` (which Clang also supports), but
  2597. ``__builtin_dynamic_object_size`` can evaluate the object's size at runtime.
  2598. ``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement
  2599. for ``__builtin_object_size`` in libraries that support it.
  2600. For instance, here is a program that ``__builtin_dynamic_object_size`` will make
  2601. safer:
  2602. .. code-block:: c
  2603. void copy_into_buffer(size_t size) {
  2604. char* buffer = malloc(size);
  2605. strlcpy(buffer, "some string", strlen("some string"));
  2606. // Previous line preprocesses to:
  2607. // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0))
  2608. }
  2609. Since the size of ``buffer`` can't be known at compile time, Clang will fold
  2610. ``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written
  2611. as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into
  2612. ``size``, providing some extra runtime safety.