LanguageExtensions.rst 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889
  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. <http://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. It evaluates to 1 if the builtin is supported or 0 if not.
  32. It can be used like this:
  33. .. code-block:: c++
  34. #ifndef __has_builtin // Optional of course.
  35. #define __has_builtin(x) 0 // Compatibility with non-clang compilers.
  36. #endif
  37. ...
  38. #if __has_builtin(__builtin_trap)
  39. __builtin_trap();
  40. #else
  41. abort();
  42. #endif
  43. ...
  44. .. _langext-__has_feature-__has_extension:
  45. ``__has_feature`` and ``__has_extension``
  46. -----------------------------------------
  47. These function-like macros take a single identifier argument that is the name
  48. of a feature. ``__has_feature`` evaluates to 1 if the feature is both
  49. supported by Clang and standardized in the current language standard or 0 if
  50. not (but see :ref:`below <langext-has-feature-back-compat>`), while
  51. ``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
  52. current language (either as a language extension or a standard language
  53. feature) or 0 if not. They can be used like this:
  54. .. code-block:: c++
  55. #ifndef __has_feature // Optional of course.
  56. #define __has_feature(x) 0 // Compatibility with non-clang compilers.
  57. #endif
  58. #ifndef __has_extension
  59. #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
  60. #endif
  61. ...
  62. #if __has_feature(cxx_rvalue_references)
  63. // This code will only be compiled with the -std=c++11 and -std=gnu++11
  64. // options, because rvalue references are only standardized in C++11.
  65. #endif
  66. #if __has_extension(cxx_rvalue_references)
  67. // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
  68. // and -std=gnu++98 options, because rvalue references are supported as a
  69. // language extension in C++98.
  70. #endif
  71. .. _langext-has-feature-back-compat:
  72. For backward compatibility, ``__has_feature`` can also be used to test
  73. for support for non-standardized features, i.e. features not prefixed ``c_``,
  74. ``cxx_`` or ``objc_``.
  75. Another use of ``__has_feature`` is to check for compiler features not related
  76. to the language standard, such as e.g. :doc:`AddressSanitizer
  77. <AddressSanitizer>`.
  78. If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
  79. to ``__has_feature``.
  80. The feature tag is described along with the language feature below.
  81. The feature name or extension name can also be specified with a preceding and
  82. following ``__`` (double underscore) to avoid interference from a macro with
  83. the same name. For instance, ``__cxx_rvalue_references__`` can be used instead
  84. of ``cxx_rvalue_references``.
  85. ``__has_attribute``
  86. -------------------
  87. This function-like macro takes a single identifier argument that is the name of
  88. an attribute. It evaluates to 1 if the attribute is supported by the current
  89. compilation target, or 0 if not. It can be used like this:
  90. .. code-block:: c++
  91. #ifndef __has_attribute // Optional of course.
  92. #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
  93. #endif
  94. ...
  95. #if __has_attribute(always_inline)
  96. #define ALWAYS_INLINE __attribute__((always_inline))
  97. #else
  98. #define ALWAYS_INLINE
  99. #endif
  100. ...
  101. The attribute name can also be specified with a preceding and following ``__``
  102. (double underscore) to avoid interference from a macro with the same name. For
  103. instance, ``__always_inline__`` can be used instead of ``always_inline``.
  104. ``__is_identifier``
  105. -------------------
  106. This function-like macro takes a single identifier argument that might be either
  107. a reserved word or a regular identifier. It evaluates to 1 if the argument is just
  108. a regular identifier and not a reserved word, in the sense that it can then be
  109. used as the name of a user-defined function or variable. Otherwise it evaluates
  110. to 0. It can be used like this:
  111. .. code-block:: c++
  112. ...
  113. #ifdef __is_identifier // Compatibility with non-clang compilers.
  114. #if __is_identifier(__wchar_t)
  115. typedef wchar_t __wchar_t;
  116. #endif
  117. #endif
  118. __wchar_t WideCharacter;
  119. ...
  120. Include File Checking Macros
  121. ============================
  122. Not all developments systems have the same include files. The
  123. :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
  124. you to check for the existence of an include file before doing a possibly
  125. failing ``#include`` directive. Include file checking macros must be used
  126. as expressions in ``#if`` or ``#elif`` preprocessing directives.
  127. .. _langext-__has_include:
  128. ``__has_include``
  129. -----------------
  130. This function-like macro takes a single file name string argument that is the
  131. name of an include file. It evaluates to 1 if the file can be found using the
  132. include paths, or 0 otherwise:
  133. .. code-block:: c++
  134. // Note the two possible file name string formats.
  135. #if __has_include("myinclude.h") && __has_include(<stdint.h>)
  136. # include "myinclude.h"
  137. #endif
  138. To test for this feature, use ``#if defined(__has_include)``:
  139. .. code-block:: c++
  140. // To avoid problem with non-clang compilers not having this macro.
  141. #if defined(__has_include)
  142. #if __has_include("myinclude.h")
  143. # include "myinclude.h"
  144. #endif
  145. #endif
  146. .. _langext-__has_include_next:
  147. ``__has_include_next``
  148. ----------------------
  149. This function-like macro takes a single file name string argument that is the
  150. name of an include file. It is like ``__has_include`` except that it looks for
  151. the second instance of the given file found in the include paths. It evaluates
  152. to 1 if the second instance of the file can be found using the include paths,
  153. or 0 otherwise:
  154. .. code-block:: c++
  155. // Note the two possible file name string formats.
  156. #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
  157. # include_next "myinclude.h"
  158. #endif
  159. // To avoid problem with non-clang compilers not having this macro.
  160. #if defined(__has_include_next)
  161. #if __has_include_next("myinclude.h")
  162. # include_next "myinclude.h"
  163. #endif
  164. #endif
  165. Note that ``__has_include_next``, like the GNU extension ``#include_next``
  166. directive, is intended for use in headers only, and will issue a warning if
  167. used in the top-level compilation file. A warning will also be issued if an
  168. absolute path is used in the file argument.
  169. ``__has_warning``
  170. -----------------
  171. This function-like macro takes a string literal that represents a command line
  172. option for a warning and returns true if that is a valid warning option.
  173. .. code-block:: c++
  174. #if __has_warning("-Wformat")
  175. ...
  176. #endif
  177. Builtin Macros
  178. ==============
  179. ``__BASE_FILE__``
  180. Defined to a string that contains the name of the main input file passed to
  181. Clang.
  182. ``__COUNTER__``
  183. Defined to an integer value that starts at zero and is incremented each time
  184. the ``__COUNTER__`` macro is expanded.
  185. ``__INCLUDE_LEVEL__``
  186. Defined to an integral value that is the include depth of the file currently
  187. being translated. For the main file, this value is zero.
  188. ``__TIMESTAMP__``
  189. Defined to the date and time of the last modification of the current source
  190. file.
  191. ``__clang__``
  192. Defined when compiling with Clang
  193. ``__clang_major__``
  194. Defined to the major marketing version number of Clang (e.g., the 2 in
  195. 2.0.1). Note that marketing version numbers should not be used to check for
  196. language features, as different vendors use different numbering schemes.
  197. Instead, use the :ref:`langext-feature_check`.
  198. ``__clang_minor__``
  199. Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
  200. that marketing version numbers should not be used to check for language
  201. features, as different vendors use different numbering schemes. Instead, use
  202. the :ref:`langext-feature_check`.
  203. ``__clang_patchlevel__``
  204. Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
  205. ``__clang_version__``
  206. Defined to a string that captures the Clang marketing version, including the
  207. Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
  208. .. _langext-vectors:
  209. Vectors and Extended Vectors
  210. ============================
  211. Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
  212. OpenCL vector types are created using ``ext_vector_type`` attribute. It
  213. support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
  214. is:
  215. .. code-block:: c++
  216. typedef float float4 __attribute__((ext_vector_type(4)));
  217. typedef float float2 __attribute__((ext_vector_type(2)));
  218. float4 foo(float2 a, float2 b) {
  219. float4 c;
  220. c.xz = a;
  221. c.yw = b;
  222. return c;
  223. }
  224. Query for this feature with ``__has_extension(attribute_ext_vector_type)``.
  225. Giving ``-faltivec`` option to clang enables support for AltiVec vector syntax
  226. and functions. For example:
  227. .. code-block:: c++
  228. vector float foo(vector int a) {
  229. vector int b;
  230. b = vec_add(a, a) + a;
  231. return (vector float)b;
  232. }
  233. NEON vector types are created using ``neon_vector_type`` and
  234. ``neon_polyvector_type`` attributes. For example:
  235. .. code-block:: c++
  236. typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
  237. typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
  238. int8x8_t foo(int8x8_t a) {
  239. int8x8_t v;
  240. v = a;
  241. return v;
  242. }
  243. Vector Literals
  244. ---------------
  245. Vector literals can be used to create vectors from a set of scalars, or
  246. vectors. Either parentheses or braces form can be used. In the parentheses
  247. form the number of literal values specified must be one, i.e. referring to a
  248. scalar value, or must match the size of the vector type being created. If a
  249. single scalar literal value is specified, the scalar literal value will be
  250. replicated to all the components of the vector type. In the brackets form any
  251. number of literals can be specified. For example:
  252. .. code-block:: c++
  253. typedef int v4si __attribute__((__vector_size__(16)));
  254. typedef float float4 __attribute__((ext_vector_type(4)));
  255. typedef float float2 __attribute__((ext_vector_type(2)));
  256. v4si vsi = (v4si){1, 2, 3, 4};
  257. float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
  258. vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
  259. vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
  260. vector int vi3 = (vector int)(1, 2); // error
  261. vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
  262. vector int vi5 = (vector int)(1, 2, 3, 4);
  263. float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
  264. Vector Operations
  265. -----------------
  266. The table below shows the support for each operation by vector extension. A
  267. dash indicates that an operation is not accepted according to a corresponding
  268. specification.
  269. ============================== ====== ======= === ====
  270. Opeator OpenCL AltiVec GCC NEON
  271. ============================== ====== ======= === ====
  272. [] yes yes yes --
  273. unary operators +, -- yes yes yes --
  274. ++, -- -- yes yes yes --
  275. +,--,*,/,% yes yes yes --
  276. bitwise operators &,|,^,~ yes yes yes --
  277. >>,<< yes yes yes --
  278. !, &&, || no -- -- --
  279. ==, !=, >, <, >=, <= yes yes -- --
  280. = yes yes yes yes
  281. :? yes -- -- --
  282. sizeof yes yes yes yes
  283. ============================== ====== ======= === ====
  284. See also :ref:`langext-__builtin_shufflevector`.
  285. Messages on ``deprecated`` and ``unavailable`` Attributes
  286. =========================================================
  287. An optional string message can be added to the ``deprecated`` and
  288. ``unavailable`` attributes. For example:
  289. .. code-block:: c++
  290. void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
  291. If the deprecated or unavailable declaration is used, the message will be
  292. incorporated into the appropriate diagnostic:
  293. .. code-block:: c++
  294. harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
  295. [-Wdeprecated-declarations]
  296. explode();
  297. ^
  298. Query for this feature with
  299. ``__has_extension(attribute_deprecated_with_message)`` and
  300. ``__has_extension(attribute_unavailable_with_message)``.
  301. Attributes on Enumerators
  302. =========================
  303. Clang allows attributes to be written on individual enumerators. This allows
  304. enumerators to be deprecated, made unavailable, etc. The attribute must appear
  305. after the enumerator name and before any initializer, like so:
  306. .. code-block:: c++
  307. enum OperationMode {
  308. OM_Invalid,
  309. OM_Normal,
  310. OM_Terrified __attribute__((deprecated)),
  311. OM_AbortOnError __attribute__((deprecated)) = 4
  312. };
  313. Attributes on the ``enum`` declaration do not apply to individual enumerators.
  314. Query for this feature with ``__has_extension(enumerator_attributes)``.
  315. 'User-Specified' System Frameworks
  316. ==================================
  317. Clang provides a mechanism by which frameworks can be built in such a way that
  318. they will always be treated as being "system frameworks", even if they are not
  319. present in a system framework directory. This can be useful to system
  320. framework developers who want to be able to test building other applications
  321. with development builds of their framework, including the manner in which the
  322. compiler changes warning behavior for system headers.
  323. Framework developers can opt-in to this mechanism by creating a
  324. "``.system_framework``" file at the top-level of their framework. That is, the
  325. framework should have contents like:
  326. .. code-block:: none
  327. .../TestFramework.framework
  328. .../TestFramework.framework/.system_framework
  329. .../TestFramework.framework/Headers
  330. .../TestFramework.framework/Headers/TestFramework.h
  331. ...
  332. Clang will treat the presence of this file as an indicator that the framework
  333. should be treated as a system framework, regardless of how it was found in the
  334. framework search path. For consistency, we recommend that such files never be
  335. included in installed versions of the framework.
  336. Checks for Standard Language Features
  337. =====================================
  338. The ``__has_feature`` macro can be used to query if certain standard language
  339. features are enabled. The ``__has_extension`` macro can be used to query if
  340. language features are available as an extension when compiling for a standard
  341. which does not provide them. The features which can be tested are listed here.
  342. C++98
  343. -----
  344. The features listed below are part of the C++98 standard. These features are
  345. enabled by default when compiling C++ code.
  346. C++ exceptions
  347. ^^^^^^^^^^^^^^
  348. Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
  349. enabled. For example, compiling code with ``-fno-exceptions`` disables C++
  350. exceptions.
  351. C++ RTTI
  352. ^^^^^^^^
  353. Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
  354. example, compiling code with ``-fno-rtti`` disables the use of RTTI.
  355. C++11
  356. -----
  357. The features listed below are part of the C++11 standard. As a result, all
  358. these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
  359. when compiling C++ code.
  360. C++11 SFINAE includes access control
  361. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  362. Use ``__has_feature(cxx_access_control_sfinae)`` or
  363. ``__has_extension(cxx_access_control_sfinae)`` to determine whether
  364. access-control errors (e.g., calling a private constructor) are considered to
  365. be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
  366. <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
  367. C++11 alias templates
  368. ^^^^^^^^^^^^^^^^^^^^^
  369. Use ``__has_feature(cxx_alias_templates)`` or
  370. ``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
  371. alias declarations and alias templates is enabled.
  372. C++11 alignment specifiers
  373. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  374. Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
  375. determine if support for alignment specifiers using ``alignas`` is enabled.
  376. C++11 attributes
  377. ^^^^^^^^^^^^^^^^
  378. Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
  379. determine if support for attribute parsing with C++11's square bracket notation
  380. is enabled.
  381. C++11 generalized constant expressions
  382. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  383. Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
  384. constant expressions (e.g., ``constexpr``) is enabled.
  385. C++11 ``decltype()``
  386. ^^^^^^^^^^^^^^^^^^^^
  387. Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
  388. determine if support for the ``decltype()`` specifier is enabled. C++11's
  389. ``decltype`` does not require type-completeness of a function call expression.
  390. Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
  391. ``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
  392. support for this feature is enabled.
  393. C++11 default template arguments in function templates
  394. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  395. Use ``__has_feature(cxx_default_function_template_args)`` or
  396. ``__has_extension(cxx_default_function_template_args)`` to determine if support
  397. for default template arguments in function templates is enabled.
  398. C++11 ``default``\ ed functions
  399. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  400. Use ``__has_feature(cxx_defaulted_functions)`` or
  401. ``__has_extension(cxx_defaulted_functions)`` to determine if support for
  402. defaulted function definitions (with ``= default``) is enabled.
  403. C++11 delegating constructors
  404. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  405. Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
  406. delegating constructors is enabled.
  407. C++11 ``deleted`` functions
  408. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  409. Use ``__has_feature(cxx_deleted_functions)`` or
  410. ``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
  411. function definitions (with ``= delete``) is enabled.
  412. C++11 explicit conversion functions
  413. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  414. Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
  415. ``explicit`` conversion functions is enabled.
  416. C++11 generalized initializers
  417. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  418. Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
  419. generalized initializers (using braced lists and ``std::initializer_list``) is
  420. enabled.
  421. C++11 implicit move constructors/assignment operators
  422. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  423. Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
  424. generate move constructors and move assignment operators where needed.
  425. C++11 inheriting constructors
  426. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  427. Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
  428. inheriting constructors is enabled.
  429. C++11 inline namespaces
  430. ^^^^^^^^^^^^^^^^^^^^^^^
  431. Use ``__has_feature(cxx_inline_namespaces)`` or
  432. ``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
  433. namespaces is enabled.
  434. C++11 lambdas
  435. ^^^^^^^^^^^^^
  436. Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
  437. determine if support for lambdas is enabled.
  438. C++11 local and unnamed types as template arguments
  439. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  440. Use ``__has_feature(cxx_local_type_template_args)`` or
  441. ``__has_extension(cxx_local_type_template_args)`` to determine if support for
  442. local and unnamed types as template arguments is enabled.
  443. C++11 noexcept
  444. ^^^^^^^^^^^^^^
  445. Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
  446. determine if support for noexcept exception specifications is enabled.
  447. C++11 in-class non-static data member initialization
  448. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  449. Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
  450. initialization of non-static data members is enabled.
  451. C++11 ``nullptr``
  452. ^^^^^^^^^^^^^^^^^
  453. Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
  454. determine if support for ``nullptr`` is enabled.
  455. C++11 ``override control``
  456. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  457. Use ``__has_feature(cxx_override_control)`` or
  458. ``__has_extension(cxx_override_control)`` to determine if support for the
  459. override control keywords is enabled.
  460. C++11 reference-qualified functions
  461. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  462. Use ``__has_feature(cxx_reference_qualified_functions)`` or
  463. ``__has_extension(cxx_reference_qualified_functions)`` to determine if support
  464. for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
  465. applied to ``*this``) is enabled.
  466. C++11 range-based ``for`` loop
  467. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  468. Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
  469. determine if support for the range-based for loop is enabled.
  470. C++11 raw string literals
  471. ^^^^^^^^^^^^^^^^^^^^^^^^^
  472. Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
  473. string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
  474. C++11 rvalue references
  475. ^^^^^^^^^^^^^^^^^^^^^^^
  476. Use ``__has_feature(cxx_rvalue_references)`` or
  477. ``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
  478. references is enabled.
  479. C++11 ``static_assert()``
  480. ^^^^^^^^^^^^^^^^^^^^^^^^^
  481. Use ``__has_feature(cxx_static_assert)`` or
  482. ``__has_extension(cxx_static_assert)`` to determine if support for compile-time
  483. assertions using ``static_assert`` is enabled.
  484. C++11 ``thread_local``
  485. ^^^^^^^^^^^^^^^^^^^^^^
  486. Use ``__has_feature(cxx_thread_local)`` to determine if support for
  487. ``thread_local`` variables is enabled.
  488. C++11 type inference
  489. ^^^^^^^^^^^^^^^^^^^^
  490. Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
  491. determine C++11 type inference is supported using the ``auto`` specifier. If
  492. this is disabled, ``auto`` will instead be a storage class specifier, as in C
  493. or C++98.
  494. C++11 strongly typed enumerations
  495. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  496. Use ``__has_feature(cxx_strong_enums)`` or
  497. ``__has_extension(cxx_strong_enums)`` to determine if support for strongly
  498. typed, scoped enumerations is enabled.
  499. C++11 trailing return type
  500. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  501. Use ``__has_feature(cxx_trailing_return)`` or
  502. ``__has_extension(cxx_trailing_return)`` to determine if support for the
  503. alternate function declaration syntax with trailing return type is enabled.
  504. C++11 Unicode string literals
  505. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  506. Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
  507. string literals is enabled.
  508. C++11 unrestricted unions
  509. ^^^^^^^^^^^^^^^^^^^^^^^^^
  510. Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
  511. unrestricted unions is enabled.
  512. C++11 user-defined literals
  513. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  514. Use ``__has_feature(cxx_user_literals)`` to determine if support for
  515. user-defined literals is enabled.
  516. C++11 variadic templates
  517. ^^^^^^^^^^^^^^^^^^^^^^^^
  518. Use ``__has_feature(cxx_variadic_templates)`` or
  519. ``__has_extension(cxx_variadic_templates)`` to determine if support for
  520. variadic templates is enabled.
  521. C++1y
  522. -----
  523. The features listed below are part of the committee draft for the C++1y
  524. standard. As a result, all these features are enabled with the ``-std=c++1y``
  525. or ``-std=gnu++1y`` option when compiling C++ code.
  526. C++1y binary literals
  527. ^^^^^^^^^^^^^^^^^^^^^
  528. Use ``__has_feature(cxx_binary_literals)`` or
  529. ``__has_extension(cxx_binary_literals)`` to determine whether
  530. binary literals (for instance, ``0b10010``) are recognized. Clang supports this
  531. feature as an extension in all language modes.
  532. C++1y contextual conversions
  533. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  534. Use ``__has_feature(cxx_contextual_conversions)`` or
  535. ``__has_extension(cxx_contextual_conversions)`` to determine if the C++1y rules
  536. are used when performing an implicit conversion for an array bound in a
  537. *new-expression*, the operand of a *delete-expression*, an integral constant
  538. expression, or a condition in a ``switch`` statement.
  539. C++1y decltype(auto)
  540. ^^^^^^^^^^^^^^^^^^^^
  541. Use ``__has_feature(cxx_decltype_auto)`` or
  542. ``__has_extension(cxx_decltype_auto)`` to determine if support
  543. for the ``decltype(auto)`` placeholder type is enabled.
  544. C++1y default initializers for aggregates
  545. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  546. Use ``__has_feature(cxx_aggregate_nsdmi)`` or
  547. ``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
  548. for default initializers in aggregate members is enabled.
  549. C++1y generalized lambda capture
  550. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  551. Use ``__has_feature(cxx_init_captures)`` or
  552. ``__has_extension(cxx_init_captures)`` to determine if support for
  553. lambda captures with explicit initializers is enabled
  554. (for instance, ``[n(0)] { return ++n; }``).
  555. C++1y generic lambdas
  556. ^^^^^^^^^^^^^^^^^^^^^
  557. Use ``__has_feature(cxx_generic_lambdas)`` or
  558. ``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
  559. (polymorphic) lambdas is enabled
  560. (for instance, ``[] (auto x) { return x + 1; }``).
  561. C++1y relaxed constexpr
  562. ^^^^^^^^^^^^^^^^^^^^^^^
  563. Use ``__has_feature(cxx_relaxed_constexpr)`` or
  564. ``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
  565. declarations, local variable modification, and control flow constructs
  566. are permitted in ``constexpr`` functions.
  567. C++1y return type deduction
  568. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  569. Use ``__has_feature(cxx_return_type_deduction)`` or
  570. ``__has_extension(cxx_return_type_deduction)`` to determine if support
  571. for return type deduction for functions (using ``auto`` as a return type)
  572. is enabled.
  573. C++1y runtime-sized arrays
  574. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  575. Use ``__has_feature(cxx_runtime_array)`` or
  576. ``__has_extension(cxx_runtime_array)`` to determine if support
  577. for arrays of runtime bound (a restricted form of variable-length arrays)
  578. is enabled.
  579. Clang's implementation of this feature is incomplete.
  580. C++1y variable templates
  581. ^^^^^^^^^^^^^^^^^^^^^^^^
  582. Use ``__has_feature(cxx_variable_templates)`` or
  583. ``__has_extension(cxx_variable_templates)`` to determine if support for
  584. templated variable declarations is enabled.
  585. C11
  586. ---
  587. The features listed below are part of the C11 standard. As a result, all these
  588. features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
  589. compiling C code. Additionally, because these features are all
  590. backward-compatible, they are available as extensions in all language modes.
  591. C11 alignment specifiers
  592. ^^^^^^^^^^^^^^^^^^^^^^^^
  593. Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
  594. if support for alignment specifiers using ``_Alignas`` is enabled.
  595. C11 atomic operations
  596. ^^^^^^^^^^^^^^^^^^^^^
  597. Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
  598. if support for atomic types using ``_Atomic`` is enabled. Clang also provides
  599. :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
  600. the ``<stdatomic.h>`` operations on ``_Atomic`` types.
  601. C11 generic selections
  602. ^^^^^^^^^^^^^^^^^^^^^^
  603. Use ``__has_feature(c_generic_selections)`` or
  604. ``__has_extension(c_generic_selections)`` to determine if support for generic
  605. selections is enabled.
  606. As an extension, the C11 generic selection expression is available in all
  607. languages supported by Clang. The syntax is the same as that given in the C11
  608. standard.
  609. In C, type compatibility is decided according to the rules given in the
  610. appropriate standard, but in C++, which lacks the type compatibility rules used
  611. in C, types are considered compatible only if they are equivalent.
  612. C11 ``_Static_assert()``
  613. ^^^^^^^^^^^^^^^^^^^^^^^^
  614. Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
  615. to determine if support for compile-time assertions using ``_Static_assert`` is
  616. enabled.
  617. C11 ``_Thread_local``
  618. ^^^^^^^^^^^^^^^^^^^^^
  619. Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
  620. to determine if support for ``_Thread_local`` variables is enabled.
  621. Checks for Type Trait Primitives
  622. ================================
  623. Type trait primitives are special builtin constant expressions that can be used
  624. by the standard C++ library to facilitate or simplify the implementation of
  625. user-facing type traits in the <type_traits> header.
  626. They are not intended to be used directly by user code because they are
  627. implementation-defined and subject to change -- as such they're tied closely to
  628. the supported set of system headers, currently:
  629. * LLVM's own libc++
  630. * GNU libstdc++
  631. * The Microsoft standard C++ library
  632. Clang supports the `GNU C++ type traits
  633. <http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
  634. `Microsoft Visual C++ Type traits
  635. <http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_.
  636. Feature detection is supported only for some of the primitives at present. User
  637. code should not use these checks because they bear no direct relation to the
  638. actual set of type traits supported by the C++ standard library.
  639. For type trait ``__X``, ``__has_extension(X)`` indicates the presence of the
  640. type trait primitive in the compiler. A simplistic usage example as might be
  641. seen in standard C++ headers follows:
  642. .. code-block:: c++
  643. #if __has_extension(is_convertible_to)
  644. template<typename From, typename To>
  645. struct is_convertible_to {
  646. static const bool value = __is_convertible_to(From, To);
  647. };
  648. #else
  649. // Emulate type trait for compatibility with other compilers.
  650. #endif
  651. The following type trait primitives are supported by Clang:
  652. * ``__has_nothrow_assign`` (GNU, Microsoft)
  653. * ``__has_nothrow_copy`` (GNU, Microsoft)
  654. * ``__has_nothrow_constructor`` (GNU, Microsoft)
  655. * ``__has_trivial_assign`` (GNU, Microsoft)
  656. * ``__has_trivial_copy`` (GNU, Microsoft)
  657. * ``__has_trivial_constructor`` (GNU, Microsoft)
  658. * ``__has_trivial_destructor`` (GNU, Microsoft)
  659. * ``__has_virtual_destructor`` (GNU, Microsoft)
  660. * ``__is_abstract`` (GNU, Microsoft)
  661. * ``__is_base_of`` (GNU, Microsoft)
  662. * ``__is_class`` (GNU, Microsoft)
  663. * ``__is_convertible_to`` (Microsoft)
  664. * ``__is_empty`` (GNU, Microsoft)
  665. * ``__is_enum`` (GNU, Microsoft)
  666. * ``__is_interface_class`` (Microsoft)
  667. * ``__is_pod`` (GNU, Microsoft)
  668. * ``__is_polymorphic`` (GNU, Microsoft)
  669. * ``__is_union`` (GNU, Microsoft)
  670. * ``__is_literal(type)``: Determines whether the given type is a literal type
  671. * ``__is_final``: Determines whether the given type is declared with a
  672. ``final`` class-virt-specifier.
  673. * ``__underlying_type(type)``: Retrieves the underlying type for a given
  674. ``enum`` type. This trait is required to implement the C++11 standard
  675. library.
  676. * ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value
  677. of type ``totype`` can be assigned to from a value of type ``fromtype`` such
  678. that no non-trivial functions are called as part of that assignment. This
  679. trait is required to implement the C++11 standard library.
  680. * ``__is_trivially_constructible(type, argtypes...)``: Determines whether a
  681. value of type ``type`` can be direct-initialized with arguments of types
  682. ``argtypes...`` such that no non-trivial functions are called as part of
  683. that initialization. This trait is required to implement the C++11 standard
  684. library.
  685. * ``__is_destructible`` (MSVC 2013): partially implemented
  686. * ``__is_nothrow_destructible`` (MSVC 2013): partially implemented
  687. * ``__is_nothrow_assignable`` (MSVC 2013, clang)
  688. * ``__is_constructible`` (MSVC 2013, clang)
  689. * ``__is_nothrow_constructible`` (MSVC 2013, clang)
  690. Blocks
  691. ======
  692. The syntax and high level language feature description is in
  693. :doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
  694. the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
  695. Query for this feature with ``__has_extension(blocks)``.
  696. Objective-C Features
  697. ====================
  698. Related result types
  699. --------------------
  700. According to Cocoa conventions, Objective-C methods with certain names
  701. ("``init``", "``alloc``", etc.) always return objects that are an instance of
  702. the receiving class's type. Such methods are said to have a "related result
  703. type", meaning that a message send to one of these methods will have the same
  704. static type as an instance of the receiver class. For example, given the
  705. following classes:
  706. .. code-block:: objc
  707. @interface NSObject
  708. + (id)alloc;
  709. - (id)init;
  710. @end
  711. @interface NSArray : NSObject
  712. @end
  713. and this common initialization pattern
  714. .. code-block:: objc
  715. NSArray *array = [[NSArray alloc] init];
  716. the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
  717. ``alloc`` implicitly has a related result type. Similarly, the type of the
  718. expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
  719. related result type and its receiver is known to have the type ``NSArray *``.
  720. If neither ``alloc`` nor ``init`` had a related result type, the expressions
  721. would have had type ``id``, as declared in the method signature.
  722. A method with a related result type can be declared by using the type
  723. ``instancetype`` as its result type. ``instancetype`` is a contextual keyword
  724. that is only permitted in the result type of an Objective-C method, e.g.
  725. .. code-block:: objc
  726. @interface A
  727. + (instancetype)constructAnA;
  728. @end
  729. The related result type can also be inferred for some methods. To determine
  730. whether a method has an inferred related result type, the first word in the
  731. camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
  732. and the method will have a related result type if its return type is compatible
  733. with the type of its class and if:
  734. * the first word is "``alloc``" or "``new``", and the method is a class method,
  735. or
  736. * the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
  737. and the method is an instance method.
  738. If a method with a related result type is overridden by a subclass method, the
  739. subclass method must also return a type that is compatible with the subclass
  740. type. For example:
  741. .. code-block:: objc
  742. @interface NSString : NSObject
  743. - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
  744. @end
  745. Related result types only affect the type of a message send or property access
  746. via the given method. In all other respects, a method with a related result
  747. type is treated the same way as method that returns ``id``.
  748. Use ``__has_feature(objc_instancetype)`` to determine whether the
  749. ``instancetype`` contextual keyword is available.
  750. Automatic reference counting
  751. ----------------------------
  752. Clang provides support for :doc:`automated reference counting
  753. <AutomaticReferenceCounting>` in Objective-C, which eliminates the need
  754. for manual ``retain``/``release``/``autorelease`` message sends. There are two
  755. feature macros associated with automatic reference counting:
  756. ``__has_feature(objc_arc)`` indicates the availability of automated reference
  757. counting in general, while ``__has_feature(objc_arc_weak)`` indicates that
  758. automated reference counting also includes support for ``__weak`` pointers to
  759. Objective-C objects.
  760. .. _objc-fixed-enum:
  761. Enumerations with a fixed underlying type
  762. -----------------------------------------
  763. Clang provides support for C++11 enumerations with a fixed underlying type
  764. within Objective-C. For example, one can write an enumeration type as:
  765. .. code-block:: c++
  766. typedef enum : unsigned char { Red, Green, Blue } Color;
  767. This specifies that the underlying type, which is used to store the enumeration
  768. value, is ``unsigned char``.
  769. Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
  770. underlying types is available in Objective-C.
  771. Interoperability with C++11 lambdas
  772. -----------------------------------
  773. Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
  774. permitting a lambda to be implicitly converted to a block pointer with the
  775. corresponding signature. For example, consider an API such as ``NSArray``'s
  776. array-sorting method:
  777. .. code-block:: objc
  778. - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
  779. ``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
  780. (^)(id, id)``, and parameters of this type are generally provided with block
  781. literals as arguments. However, one can also use a C++11 lambda so long as it
  782. provides the same signature (in this case, accepting two parameters of type
  783. ``id`` and returning an ``NSComparisonResult``):
  784. .. code-block:: objc
  785. NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
  786. @"String 02"];
  787. const NSStringCompareOptions comparisonOptions
  788. = NSCaseInsensitiveSearch | NSNumericSearch |
  789. NSWidthInsensitiveSearch | NSForcedOrderingSearch;
  790. NSLocale *currentLocale = [NSLocale currentLocale];
  791. NSArray *sorted
  792. = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
  793. NSRange string1Range = NSMakeRange(0, [s1 length]);
  794. return [s1 compare:s2 options:comparisonOptions
  795. range:string1Range locale:currentLocale];
  796. }];
  797. NSLog(@"sorted: %@", sorted);
  798. This code relies on an implicit conversion from the type of the lambda
  799. expression (an unnamed, local class type called the *closure type*) to the
  800. corresponding block pointer type. The conversion itself is expressed by a
  801. conversion operator in that closure type that produces a block pointer with the
  802. same signature as the lambda itself, e.g.,
  803. .. code-block:: objc
  804. operator NSComparisonResult (^)(id, id)() const;
  805. This conversion function returns a new block that simply forwards the two
  806. parameters to the lambda object (which it captures by copy), then returns the
  807. result. The returned block is first copied (with ``Block_copy``) and then
  808. autoreleased. As an optimization, if a lambda expression is immediately
  809. converted to a block pointer (as in the first example, above), then the block
  810. is not copied and autoreleased: rather, it is given the same lifetime as a
  811. block literal written at that point in the program, which avoids the overhead
  812. of copying a block to the heap in the common case.
  813. The conversion from a lambda to a block pointer is only available in
  814. Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
  815. management (autorelease).
  816. Object Literals and Subscripting
  817. --------------------------------
  818. Clang provides support for :doc:`Object Literals and Subscripting
  819. <ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
  820. programming patterns, makes programs more concise, and improves the safety of
  821. container creation. There are several feature macros associated with object
  822. literals and subscripting: ``__has_feature(objc_array_literals)`` tests the
  823. availability of array literals; ``__has_feature(objc_dictionary_literals)``
  824. tests the availability of dictionary literals;
  825. ``__has_feature(objc_subscripting)`` tests the availability of object
  826. subscripting.
  827. Objective-C Autosynthesis of Properties
  828. ---------------------------------------
  829. Clang provides support for autosynthesis of declared properties. Using this
  830. feature, clang provides default synthesis of those properties not declared
  831. @dynamic and not having user provided backing getter and setter methods.
  832. ``__has_feature(objc_default_synthesize_properties)`` checks for availability
  833. of this feature in version of clang being used.
  834. .. _langext-objc-retain-release:
  835. Objective-C retaining behavior attributes
  836. -----------------------------------------
  837. In Objective-C, functions and methods are generally assumed to follow the
  838. `Cocoa Memory Management
  839. <http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_
  840. conventions for ownership of object arguments and
  841. return values. However, there are exceptions, and so Clang provides attributes
  842. to allow these exceptions to be documented. This are used by ARC and the
  843. `static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be
  844. better described using the ``objc_method_family`` attribute instead.
  845. **Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``,
  846. ``ns_returns_autoreleased``, ``cf_returns_retained``, and
  847. ``cf_returns_not_retained`` attributes can be placed on methods and functions
  848. that return Objective-C or CoreFoundation objects. They are commonly placed at
  849. the end of a function prototype or method declaration:
  850. .. code-block:: objc
  851. id foo() __attribute__((ns_returns_retained));
  852. - (NSString *)bar:(int)x __attribute__((ns_returns_retained));
  853. The ``*_returns_retained`` attributes specify that the returned object has a +1
  854. retain count. The ``*_returns_not_retained`` attributes specify that the return
  855. object has a +0 retain count, even if the normal convention for its selector
  856. would be +1. ``ns_returns_autoreleased`` specifies that the returned object is
  857. +0, but is guaranteed to live at least as long as the next flush of an
  858. autorelease pool.
  859. **Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on
  860. an parameter declaration; they specify that the argument is expected to have a
  861. +1 retain count, which will be balanced in some way by the function or method.
  862. The ``ns_consumes_self`` attribute can only be placed on an Objective-C
  863. method; it specifies that the method expects its ``self`` parameter to have a
  864. +1 retain count, which it will balance in some way.
  865. .. code-block:: objc
  866. void foo(__attribute__((ns_consumed)) NSString *string);
  867. - (void) bar __attribute__((ns_consumes_self));
  868. - (void) baz:(id) __attribute__((ns_consumed)) x;
  869. Further examples of these attributes are available in the static analyzer's `list of annotations for analysis
  870. <http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_.
  871. Query for these features with ``__has_attribute(ns_consumed)``,
  872. ``__has_attribute(ns_returns_retained)``, etc.
  873. Objective-C++ ABI: protocol-qualifier mangling of parameters
  874. ------------------------------------------------------------
  875. Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
  876. type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such
  877. parameters to be differentiated from those with the regular unqualified ``id``
  878. type.
  879. This was a non-backward compatible mangling change to the ABI. This change
  880. allows proper overloading, and also prevents mangling conflicts with template
  881. parameters of protocol-qualified type.
  882. Query the presence of this new mangling with
  883. ``__has_feature(objc_protocol_qualifier_mangling)``.
  884. .. _langext-overloading:
  885. Initializer lists for complex numbers in C
  886. ==========================================
  887. clang supports an extension which allows the following in C:
  888. .. code-block:: c++
  889. #include <math.h>
  890. #include <complex.h>
  891. complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
  892. This construct is useful because there is no way to separately initialize the
  893. real and imaginary parts of a complex variable in standard C, given that clang
  894. does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
  895. ``__imag__`` extensions from gcc, which help in some cases, but are not usable
  896. in static initializers.)
  897. Note that this extension does not allow eliding the braces; the meaning of the
  898. following two lines is different:
  899. .. code-block:: c++
  900. complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
  901. complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
  902. This extension also works in C++ mode, as far as that goes, but does not apply
  903. to the C++ ``std::complex``. (In C++11, list initialization allows the same
  904. syntax to be used with ``std::complex`` with the same meaning.)
  905. Builtin Functions
  906. =================
  907. Clang supports a number of builtin library functions with the same syntax as
  908. GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
  909. ``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
  910. ``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports
  911. a number of builtins that GCC does not, which are listed here.
  912. Please note that Clang does not and will not support all of the GCC builtins
  913. for vector operations. Instead of using builtins, you should use the functions
  914. defined in target-specific header files like ``<xmmintrin.h>``, which define
  915. portable wrappers for these. Many of the Clang versions of these functions are
  916. implemented directly in terms of :ref:`extended vector support
  917. <langext-vectors>` instead of builtins, in order to reduce the number of
  918. builtins that we need to implement.
  919. ``__builtin_readcyclecounter``
  920. ------------------------------
  921. ``__builtin_readcyclecounter`` is used to access the cycle counter register (or
  922. a similar low-latency, high-accuracy clock) on those targets that support it.
  923. **Syntax**:
  924. .. code-block:: c++
  925. __builtin_readcyclecounter()
  926. **Example of Use**:
  927. .. code-block:: c++
  928. unsigned long long t0 = __builtin_readcyclecounter();
  929. do_something();
  930. unsigned long long t1 = __builtin_readcyclecounter();
  931. unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
  932. **Description**:
  933. The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
  934. which may be either global or process/thread-specific depending on the target.
  935. As the backing counters often overflow quickly (on the order of seconds) this
  936. should only be used for timing small intervals. When not supported by the
  937. target, the return value is always zero. This builtin takes no arguments and
  938. produces an unsigned long long result.
  939. Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
  940. that even if present, its use may depend on run-time privilege or other OS
  941. controlled state.
  942. .. _langext-__builtin_shufflevector:
  943. ``__builtin_shufflevector``
  944. ---------------------------
  945. ``__builtin_shufflevector`` is used to express generic vector
  946. permutation/shuffle/swizzle operations. This builtin is also very important
  947. for the implementation of various target-specific header files like
  948. ``<xmmintrin.h>``.
  949. **Syntax**:
  950. .. code-block:: c++
  951. __builtin_shufflevector(vec1, vec2, index1, index2, ...)
  952. **Examples**:
  953. .. code-block:: c++
  954. // identity operation - return 4-element vector v1.
  955. __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
  956. // "Splat" element 0 of V1 into a 4-element result.
  957. __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
  958. // Reverse 4-element vector V1.
  959. __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
  960. // Concatenate every other element of 4-element vectors V1 and V2.
  961. __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
  962. // Concatenate every other element of 8-element vectors V1 and V2.
  963. __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
  964. // Shuffle v1 with some elements being undefined
  965. __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
  966. **Description**:
  967. The first two arguments to ``__builtin_shufflevector`` are vectors that have
  968. the same element type. The remaining arguments are a list of integers that
  969. specify the elements indices of the first two vectors that should be extracted
  970. and returned in a new vector. These element indices are numbered sequentially
  971. starting with the first vector, continuing into the second vector. Thus, if
  972. ``vec1`` is a 4-element vector, index 5 would refer to the second element of
  973. ``vec2``. An index of -1 can be used to indicate that the corresponding element
  974. in the returned vector is a don't care and can be optimized by the backend.
  975. The result of ``__builtin_shufflevector`` is a vector with the same element
  976. type as ``vec1``/``vec2`` but that has an element count equal to the number of
  977. indices specified.
  978. Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
  979. ``__builtin_convertvector``
  980. ---------------------------
  981. ``__builtin_convertvector`` is used to express generic vector
  982. type-conversion operations. The input vector and the output vector
  983. type must have the same number of elements.
  984. **Syntax**:
  985. .. code-block:: c++
  986. __builtin_convertvector(src_vec, dst_vec_type)
  987. **Examples**:
  988. .. code-block:: c++
  989. typedef double vector4double __attribute__((__vector_size__(32)));
  990. typedef float vector4float __attribute__((__vector_size__(16)));
  991. typedef short vector4short __attribute__((__vector_size__(8)));
  992. vector4float vf; vector4short vs;
  993. // convert from a vector of 4 floats to a vector of 4 doubles.
  994. __builtin_convertvector(vf, vector4double)
  995. // equivalent to:
  996. (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
  997. // convert from a vector of 4 shorts to a vector of 4 floats.
  998. __builtin_convertvector(vs, vector4float)
  999. // equivalent to:
  1000. (vector4float) { (float) vf[0], (float) vf[1], (float) vf[2], (float) vf[3] }
  1001. **Description**:
  1002. The first argument to ``__builtin_convertvector`` is a vector, and the second
  1003. argument is a vector type with the same number of elements as the first
  1004. argument.
  1005. The result of ``__builtin_convertvector`` is a vector with the same element
  1006. type as the second argument, with a value defined in terms of the action of a
  1007. C-style cast applied to each element of the first argument.
  1008. Query for this feature with ``__has_builtin(__builtin_convertvector)``.
  1009. ``__builtin_unreachable``
  1010. -------------------------
  1011. ``__builtin_unreachable`` is used to indicate that a specific point in the
  1012. program cannot be reached, even if the compiler might otherwise think it can.
  1013. This is useful to improve optimization and eliminates certain warnings. For
  1014. example, without the ``__builtin_unreachable`` in the example below, the
  1015. compiler assumes that the inline asm can fall through and prints a "function
  1016. declared '``noreturn``' should not return" warning.
  1017. **Syntax**:
  1018. .. code-block:: c++
  1019. __builtin_unreachable()
  1020. **Example of use**:
  1021. .. code-block:: c++
  1022. void myabort(void) __attribute__((noreturn));
  1023. void myabort(void) {
  1024. asm("int3");
  1025. __builtin_unreachable();
  1026. }
  1027. **Description**:
  1028. The ``__builtin_unreachable()`` builtin has completely undefined behavior.
  1029. Since it has undefined behavior, it is a statement that it is never reached and
  1030. the optimizer can take advantage of this to produce better code. This builtin
  1031. takes no arguments and produces a void result.
  1032. Query for this feature with ``__has_builtin(__builtin_unreachable)``.
  1033. ``__sync_swap``
  1034. ---------------
  1035. ``__sync_swap`` is used to atomically swap integers or pointers in memory.
  1036. **Syntax**:
  1037. .. code-block:: c++
  1038. type __sync_swap(type *ptr, type value, ...)
  1039. **Example of Use**:
  1040. .. code-block:: c++
  1041. int old_value = __sync_swap(&value, new_value);
  1042. **Description**:
  1043. The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
  1044. atomic intrinsics to allow code to atomically swap the current value with the
  1045. new value. More importantly, it helps developers write more efficient and
  1046. correct code by avoiding expensive loops around
  1047. ``__sync_bool_compare_and_swap()`` or relying on the platform specific
  1048. implementation details of ``__sync_lock_test_and_set()``. The
  1049. ``__sync_swap()`` builtin is a full barrier.
  1050. ``__builtin_addressof``
  1051. -----------------------
  1052. ``__builtin_addressof`` performs the functionality of the built-in ``&``
  1053. operator, ignoring any ``operator&`` overload. This is useful in constant
  1054. expressions in C++11, where there is no other way to take the address of an
  1055. object that overloads ``operator&``.
  1056. **Example of use**:
  1057. .. code-block:: c++
  1058. template<typename T> constexpr T *addressof(T &value) {
  1059. return __builtin_addressof(value);
  1060. }
  1061. ``__builtin_operator_new`` and ``__builtin_operator_delete``
  1062. ------------------------------------------------------------
  1063. ``__builtin_operator_new`` allocates memory just like a non-placement non-class
  1064. *new-expression*. This is exactly like directly calling the normal
  1065. non-placement ``::operator new``, except that it allows certain optimizations
  1066. that the C++ standard does not permit for a direct function call to
  1067. ``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
  1068. merging allocations).
  1069. Likewise, ``__builtin_operator_delete`` deallocates memory just like a
  1070. non-class *delete-expression*, and is exactly like directly calling the normal
  1071. ``::operator delete``, except that it permits optimizations. Only the unsized
  1072. form of ``__builtin_operator_delete`` is currently available.
  1073. These builtins are intended for use in the implementation of ``std::allocator``
  1074. and other similar allocation libraries, and are only available in C++.
  1075. Multiprecision Arithmetic Builtins
  1076. ----------------------------------
  1077. Clang provides a set of builtins which expose multiprecision arithmetic in a
  1078. manner amenable to C. They all have the following form:
  1079. .. code-block:: c
  1080. unsigned x = ..., y = ..., carryin = ..., carryout;
  1081. unsigned sum = __builtin_addc(x, y, carryin, &carryout);
  1082. Thus one can form a multiprecision addition chain in the following manner:
  1083. .. code-block:: c
  1084. unsigned *x, *y, *z, carryin=0, carryout;
  1085. z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
  1086. carryin = carryout;
  1087. z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
  1088. carryin = carryout;
  1089. z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
  1090. carryin = carryout;
  1091. z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
  1092. The complete list of builtins are:
  1093. .. code-block:: c
  1094. unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
  1095. unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
  1096. unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
  1097. unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
  1098. unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
  1099. unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
  1100. unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
  1101. unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
  1102. unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
  1103. unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
  1104. Checked Arithmetic Builtins
  1105. ---------------------------
  1106. Clang provides a set of builtins that implement checked arithmetic for security
  1107. critical applications in a manner that is fast and easily expressable in C. As
  1108. an example of their usage:
  1109. .. code-block:: c
  1110. errorcode_t security_critical_application(...) {
  1111. unsigned x, y, result;
  1112. ...
  1113. if (__builtin_umul_overflow(x, y, &result))
  1114. return kErrorCodeHackers;
  1115. ...
  1116. use_multiply(result);
  1117. ...
  1118. }
  1119. A complete enumeration of the builtins are:
  1120. .. code-block:: c
  1121. bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
  1122. bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
  1123. bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
  1124. bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
  1125. bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
  1126. bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
  1127. bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
  1128. bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
  1129. bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
  1130. bool __builtin_sadd_overflow (int x, int y, int *sum);
  1131. bool __builtin_saddl_overflow (long x, long y, long *sum);
  1132. bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
  1133. bool __builtin_ssub_overflow (int x, int y, int *diff);
  1134. bool __builtin_ssubl_overflow (long x, long y, long *diff);
  1135. bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
  1136. bool __builtin_smul_overflow (int x, int y, int *prod);
  1137. bool __builtin_smull_overflow (long x, long y, long *prod);
  1138. bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
  1139. .. _langext-__c11_atomic:
  1140. __c11_atomic builtins
  1141. ---------------------
  1142. Clang provides a set of builtins which are intended to be used to implement
  1143. C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
  1144. ``_explicit`` form of the corresponding C11 operation, and are named with a
  1145. ``__c11_`` prefix. The supported operations are:
  1146. * ``__c11_atomic_init``
  1147. * ``__c11_atomic_thread_fence``
  1148. * ``__c11_atomic_signal_fence``
  1149. * ``__c11_atomic_is_lock_free``
  1150. * ``__c11_atomic_store``
  1151. * ``__c11_atomic_load``
  1152. * ``__c11_atomic_exchange``
  1153. * ``__c11_atomic_compare_exchange_strong``
  1154. * ``__c11_atomic_compare_exchange_weak``
  1155. * ``__c11_atomic_fetch_add``
  1156. * ``__c11_atomic_fetch_sub``
  1157. * ``__c11_atomic_fetch_and``
  1158. * ``__c11_atomic_fetch_or``
  1159. * ``__c11_atomic_fetch_xor``
  1160. Low-level ARM exclusive memory builtins
  1161. ---------------------------------------
  1162. Clang provides overloaded builtins giving direct access to the three key ARM
  1163. instructions for implementing atomic operations.
  1164. .. code-block:: c
  1165. T __builtin_arm_ldrex(const volatile T *addr);
  1166. T __builtin_arm_ldaex(const volatile T *addr);
  1167. int __builtin_arm_strex(T val, volatile T *addr);
  1168. int __builtin_arm_stlex(T val, volatile T *addr);
  1169. void __builtin_arm_clrex(void);
  1170. The types ``T`` currently supported are:
  1171. * Integer types with width at most 64 bits (or 128 bits on AArch64).
  1172. * Floating-point types
  1173. * Pointer types.
  1174. Note that the compiler does not guarantee it will not insert stores which clear
  1175. the exclusive monitor in between an ``ldrex`` type operation and its paired
  1176. ``strex``. In practice this is only usually a risk when the extra store is on
  1177. the same cache line as the variable being modified and Clang will only insert
  1178. stack stores on its own, so it is best not to use these operations on variables
  1179. with automatic storage duration.
  1180. Also, loads and stores may be implicit in code written between the ``ldrex`` and
  1181. ``strex``. Clang will not necessarily mitigate the effects of these either, so
  1182. care should be exercised.
  1183. For these reasons the higher level atomic primitives should be preferred where
  1184. possible.
  1185. Non-standard C++11 Attributes
  1186. =============================
  1187. Clang's non-standard C++11 attributes live in the ``clang`` attribute
  1188. namespace.
  1189. Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
  1190. are accepted with the ``__attribute__((foo))`` syntax are also accepted as
  1191. ``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
  1192. (see the list of `GCC function attributes
  1193. <http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
  1194. attributes <http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
  1195. `GCC type attributes
  1196. <http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
  1197. implementation, these attributes must appertain to the *declarator-id* in a
  1198. declaration, which means they must go either at the start of the declaration or
  1199. immediately after the name being declared.
  1200. For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
  1201. also applies the GNU ``noreturn`` attribute to ``f``.
  1202. .. code-block:: c++
  1203. [[gnu::unused]] int a, f [[gnu::noreturn]] ();
  1204. Target-Specific Extensions
  1205. ==========================
  1206. Clang supports some language features conditionally on some targets.
  1207. ARM/AArch64 Language Extensions
  1208. -------------------------------
  1209. Memory Barrier Intrinsics
  1210. ^^^^^^^^^^^^^^^^^^^^^^^^^
  1211. Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
  1212. in the `ARM C Language Extensions Release 2.0
  1213. <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_.
  1214. Note that these intrinsics are implemented as motion barriers that block
  1215. reordering of memory accesses and side effect instructions. Other instructions
  1216. like simple arithmatic may be reordered around the intrinsic. If you expect to
  1217. have no reordering at all, use inline assembly instead.
  1218. X86/X86-64 Language Extensions
  1219. ------------------------------
  1220. The X86 backend has these language extensions:
  1221. Memory references off the GS segment
  1222. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1223. Annotating a pointer with address space #256 causes it to be code generated
  1224. relative to the X86 GS segment register, and address space #257 causes it to be
  1225. relative to the X86 FS segment. Note that this is a very very low-level
  1226. feature that should only be used if you know what you're doing (for example in
  1227. an OS kernel).
  1228. Here is an example:
  1229. .. code-block:: c++
  1230. #define GS_RELATIVE __attribute__((address_space(256)))
  1231. int foo(int GS_RELATIVE *P) {
  1232. return *P;
  1233. }
  1234. Which compiles to (on X86-32):
  1235. .. code-block:: gas
  1236. _foo:
  1237. movl 4(%esp), %eax
  1238. movl %gs:(%eax), %eax
  1239. ret
  1240. Extensions for Static Analysis
  1241. ==============================
  1242. Clang supports additional attributes that are useful for documenting program
  1243. invariants and rules for static analysis tools, such as the `Clang Static
  1244. Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented
  1245. in the analyzer's `list of source-level annotations
  1246. <http://clang-analyzer.llvm.org/annotations.html>`_.
  1247. Extensions for Dynamic Analysis
  1248. ===============================
  1249. Use ``__has_feature(address_sanitizer)`` to check if the code is being built
  1250. with :doc:`AddressSanitizer`.
  1251. Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
  1252. with :doc:`ThreadSanitizer`.
  1253. Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
  1254. with :doc:`MemorySanitizer`.
  1255. Extensions for selectively disabling optimization
  1256. =================================================
  1257. Clang provides a mechanism for selectively disabling optimizations in functions
  1258. and methods.
  1259. To disable optimizations in a single function definition, the GNU-style or C++11
  1260. non-standard attribute ``optnone`` can be used.
  1261. .. code-block:: c++
  1262. // The following functions will not be optimized.
  1263. // GNU-style attribute
  1264. __attribute__((optnone)) int foo() {
  1265. // ... code
  1266. }
  1267. // C++11 attribute
  1268. [[clang::optnone]] int bar() {
  1269. // ... code
  1270. }
  1271. To facilitate disabling optimization for a range of function definitions, a
  1272. range-based pragma is provided. Its syntax is ``#pragma clang optimize``
  1273. followed by ``off`` or ``on``.
  1274. All function definitions in the region between an ``off`` and the following
  1275. ``on`` will be decorated with the ``optnone`` attribute unless doing so would
  1276. conflict with explicit attributes already present on the function (e.g. the
  1277. ones that control inlining).
  1278. .. code-block:: c++
  1279. #pragma clang optimize off
  1280. // This function will be decorated with optnone.
  1281. int foo() {
  1282. // ... code
  1283. }
  1284. // optnone conflicts with always_inline, so bar() will not be decorated.
  1285. __attribute__((always_inline)) int bar() {
  1286. // ... code
  1287. }
  1288. #pragma clang optimize on
  1289. If no ``on`` is found to close an ``off`` region, the end of the region is the
  1290. end of the compilation unit.
  1291. Note that a stray ``#pragma clang optimize on`` does not selectively enable
  1292. additional optimizations when compiling at low optimization levels. This feature
  1293. can only be used to selectively disable optimizations.
  1294. The pragma has an effect on functions only at the point of their definition; for
  1295. function templates, this means that the state of the pragma at the point of an
  1296. instantiation is not necessarily relevant. Consider the following example:
  1297. .. code-block:: c++
  1298. template<typename T> T twice(T t) {
  1299. return 2 * t;
  1300. }
  1301. #pragma clang optimize off
  1302. template<typename T> T thrice(T t) {
  1303. return 3 * t;
  1304. }
  1305. int container(int a, int b) {
  1306. return twice(a) + thrice(b);
  1307. }
  1308. #pragma clang optimize on
  1309. In this example, the definition of the template function ``twice`` is outside
  1310. the pragma region, whereas the definition of ``thrice`` is inside the region.
  1311. The ``container`` function is also in the region and will not be optimized, but
  1312. it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
  1313. these two instantiations, ``twice`` will be optimized (because its definition
  1314. was outside the region) and ``thrice`` will not be optimized.
  1315. Extensions for loop hint optimizations
  1316. ======================================
  1317. The ``#pragma clang loop`` directive is used to specify hints for optimizing the
  1318. subsequent for, while, do-while, or c++11 range-based for loop. The directive
  1319. provides options for vectorization, interleaving, and unrolling. Loop hints can
  1320. be specified before any loop and will be ignored if the optimization is not safe
  1321. to apply.
  1322. Vectorization and Interleaving
  1323. ------------------------------
  1324. A vectorized loop performs multiple iterations of the original loop
  1325. in parallel using vector instructions. The instruction set of the target
  1326. processor determines which vector instructions are available and their vector
  1327. widths. This restricts the types of loops that can be vectorized. The vectorizer
  1328. automatically determines if the loop is safe and profitable to vectorize. A
  1329. vector instruction cost model is used to select the vector width.
  1330. Interleaving multiple loop iterations allows modern processors to further
  1331. improve instruction-level parallelism (ILP) using advanced hardware features,
  1332. such as multiple execution units and out-of-order execution. The vectorizer uses
  1333. a cost model that depends on the register pressure and generated code size to
  1334. select the interleaving count.
  1335. Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
  1336. by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
  1337. manually enable vectorization or interleaving.
  1338. .. code-block:: c++
  1339. #pragma clang loop vectorize(enable)
  1340. #pragma clang loop interleave(enable)
  1341. for(...) {
  1342. ...
  1343. }
  1344. The vector width is specified by ``vectorize_width(_value_)`` and the interleave
  1345. count is specified by ``interleave_count(_value_)``, where
  1346. _value_ is a positive integer. This is useful for specifying the optimal
  1347. width/count of the set of target architectures supported by your application.
  1348. .. code-block:: c++
  1349. #pragma clang loop vectorize_width(2)
  1350. #pragma clang loop interleave_count(2)
  1351. for(...) {
  1352. ...
  1353. }
  1354. Specifying a width/count of 1 disables the optimization, and is equivalent to
  1355. ``vectorize(disable)`` or ``interleave(disable)``.
  1356. Loop Unrolling
  1357. --------------
  1358. Unrolling a loop reduces the loop control overhead and exposes more
  1359. opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
  1360. eliminates the loop and replaces it with an enumerated sequence of loop
  1361. iterations. Full unrolling is only possible if the loop trip count is known at
  1362. compile time. Partial unrolling replicates the loop body within the loop and
  1363. reduces the trip count.
  1364. If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the
  1365. loop if the trip count is known at compile time. If the loop count is not known
  1366. or the fully unrolled code size is greater than the limit specified by the
  1367. `-pragma-unroll-threshold` command line option the loop will be partially
  1368. unrolled subject to the same limit.
  1369. .. code-block:: c++
  1370. #pragma clang loop unroll(enable)
  1371. for(...) {
  1372. ...
  1373. }
  1374. The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
  1375. _value_ is a positive integer. If this value is greater than the trip count the
  1376. loop will be fully unrolled. Otherwise the loop is partially unrolled subject
  1377. to the `-pragma-unroll-threshold` limit.
  1378. .. code-block:: c++
  1379. #pragma clang loop unroll_count(8)
  1380. for(...) {
  1381. ...
  1382. }
  1383. Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
  1384. Additional Information
  1385. ----------------------
  1386. For convenience multiple loop hints can be specified on a single line.
  1387. .. code-block:: c++
  1388. #pragma clang loop vectorize_width(4) interleave_count(8)
  1389. for(...) {
  1390. ...
  1391. }
  1392. If an optimization cannot be applied any hints that apply to it will be ignored.
  1393. For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
  1394. proven safe to vectorize. To identify and diagnose optimization issues use
  1395. `-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
  1396. user guide for details.