1 ==============================
2 LLVM Language Reference Manual
3 ==============================
12 This document is a reference manual for the LLVM assembly language. LLVM
13 is a Static Single Assignment (SSA) based representation that provides
14 type safety, low-level operations, flexibility, and the capability of
15 representing 'all' high-level languages cleanly. It is the common code
16 representation used throughout all phases of the LLVM compilation
22 The LLVM code representation is designed to be used in three different
23 forms: as an in-memory compiler IR, as an on-disk bitcode representation
24 (suitable for fast loading by a Just-In-Time compiler), and as a human
25 readable assembly language representation. This allows LLVM to provide a
26 powerful intermediate representation for efficient compiler
27 transformations and analysis, while providing a natural means to debug
28 and visualize the transformations. The three different forms of LLVM are
29 all equivalent. This document describes the human readable
30 representation and notation.
32 The LLVM representation aims to be light-weight and low-level while
33 being expressive, typed, and extensible at the same time. It aims to be
34 a "universal IR" of sorts, by being at a low enough level that
35 high-level ideas may be cleanly mapped to it (similar to how
36 microprocessors are "universal IR's", allowing many source languages to
37 be mapped to them). By providing type information, LLVM can be used as
38 the target of optimizations: for example, through pointer analysis, it
39 can be proven that a C automatic variable is never accessed outside of
40 the current function, allowing it to be promoted to a simple SSA value
41 instead of a memory location.
48 It is important to note that this document describes 'well formed' LLVM
49 assembly language. There is a difference between what the parser accepts
50 and what is considered 'well formed'. For example, the following
51 instruction is syntactically okay, but not well formed:
57 because the definition of ``%x`` does not dominate all of its uses. The
58 LLVM infrastructure provides a verification pass that may be used to
59 verify that an LLVM module is well formed. This pass is automatically
60 run by the parser after parsing input assembly and by the optimizer
61 before it outputs bitcode. The violations pointed out by the verifier
62 pass indicate bugs in transformation passes or input to the parser.
69 LLVM identifiers come in two basic types: global and local. Global
70 identifiers (functions, global variables) begin with the ``'@'``
71 character. Local identifiers (register names, types) begin with the
72 ``'%'`` character. Additionally, there are three different formats for
73 identifiers, for different purposes:
75 #. Named values are represented as a string of characters with their
76 prefix. For example, ``%foo``, ``@DivisionByZero``,
77 ``%a.really.long.identifier``. The actual regular expression used is
78 '``[%@][-a-zA-Z$._][-a-zA-Z$._0-9]*``'. Identifiers that require other
79 characters in their names can be surrounded with quotes. Special
80 characters may be escaped using ``"\xx"`` where ``xx`` is the ASCII
81 code for the character in hexadecimal. In this way, any character can
82 be used in a name value, even quotes themselves. The ``"\01"`` prefix
83 can be used on global variables to suppress mangling.
84 #. Unnamed values are represented as an unsigned numeric value with
85 their prefix. For example, ``%12``, ``@2``, ``%44``.
86 #. Constants, which are described in the section Constants_ below.
88 LLVM requires that values start with a prefix for two reasons: Compilers
89 don't need to worry about name clashes with reserved words, and the set
90 of reserved words may be expanded in the future without penalty.
91 Additionally, unnamed identifiers allow a compiler to quickly come up
92 with a temporary variable without having to avoid symbol table
95 Reserved words in LLVM are very similar to reserved words in other
96 languages. There are keywords for different opcodes ('``add``',
97 '``bitcast``', '``ret``', etc...), for primitive type names ('``void``',
98 '``i32``', etc...), and others. These reserved words cannot conflict
99 with variable names, because none of them start with a prefix character
100 (``'%'`` or ``'@'``).
102 Here is an example of LLVM code to multiply the integer variable
109 %result = mul i32 %X, 8
111 After strength reduction:
115 %result = shl i32 %X, 3
121 %0 = add i32 %X, %X ; yields i32:%0
122 %1 = add i32 %0, %0 ; yields i32:%1
123 %result = add i32 %1, %1
125 This last way of multiplying ``%X`` by 8 illustrates several important
126 lexical features of LLVM:
128 #. Comments are delimited with a '``;``' and go until the end of line.
129 #. Unnamed temporaries are created when the result of a computation is
130 not assigned to a named value.
131 #. Unnamed temporaries are numbered sequentially (using a per-function
132 incrementing counter, starting with 0). Note that basic blocks and unnamed
133 function parameters are included in this numbering. For example, if the
134 entry basic block is not given a label name and all function parameters are
135 named, then it will get number 0.
137 It also shows a convention that we follow in this document. When
138 demonstrating instructions, we will follow an instruction with a comment
139 that defines the type and name of value produced.
147 LLVM programs are composed of ``Module``'s, each of which is a
148 translation unit of the input programs. Each module consists of
149 functions, global variables, and symbol table entries. Modules may be
150 combined together with the LLVM linker, which merges function (and
151 global variable) definitions, resolves forward declarations, and merges
152 symbol table entries. Here is an example of the "hello world" module:
156 ; Declare the string constant as a global constant.
157 @.str = private unnamed_addr constant [13 x i8] c"hello world\0A\00"
159 ; External declaration of the puts function
160 declare i32 @puts(i8* nocapture) nounwind
162 ; Definition of main function
163 define i32 @main() { ; i32()*
164 ; Convert [13 x i8]* to i8 *...
165 %cast210 = getelementptr [13 x i8], [13 x i8]* @.str, i64 0, i64 0
167 ; Call puts function to write out the string to stdout.
168 call i32 @puts(i8* %cast210)
173 !0 = !{i32 42, null, !"string"}
176 This example is made up of a :ref:`global variable <globalvars>` named
177 "``.str``", an external declaration of the "``puts``" function, a
178 :ref:`function definition <functionstructure>` for "``main``" and
179 :ref:`named metadata <namedmetadatastructure>` "``foo``".
181 In general, a module is made up of a list of global values (where both
182 functions and global variables are global values). Global values are
183 represented by a pointer to a memory location (in this case, a pointer
184 to an array of char, and a pointer to a function), and have one of the
185 following :ref:`linkage types <linkage>`.
192 All Global Variables and Functions have one of the following types of
196 Global values with "``private``" linkage are only directly
197 accessible by objects in the current module. In particular, linking
198 code into a module with an private global value may cause the
199 private to be renamed as necessary to avoid collisions. Because the
200 symbol is private to the module, all references can be updated. This
201 doesn't show up in any symbol table in the object file.
203 Similar to private, but the value shows as a local symbol
204 (``STB_LOCAL`` in the case of ELF) in the object file. This
205 corresponds to the notion of the '``static``' keyword in C.
206 ``available_externally``
207 Globals with "``available_externally``" linkage are never emitted
208 into the object file corresponding to the LLVM module. They exist to
209 allow inlining and other optimizations to take place given knowledge
210 of the definition of the global, which is known to be somewhere
211 outside the module. Globals with ``available_externally`` linkage
212 are allowed to be discarded at will, and are otherwise the same as
213 ``linkonce_odr``. This linkage type is only allowed on definitions,
216 Globals with "``linkonce``" linkage are merged with other globals of
217 the same name when linkage occurs. This can be used to implement
218 some forms of inline functions, templates, or other code which must
219 be generated in each translation unit that uses it, but where the
220 body may be overridden with a more definitive definition later.
221 Unreferenced ``linkonce`` globals are allowed to be discarded. Note
222 that ``linkonce`` linkage does not actually allow the optimizer to
223 inline the body of this function into callers because it doesn't
224 know if this definition of the function is the definitive definition
225 within the program or whether it will be overridden by a stronger
226 definition. To enable inlining and other optimizations, use
227 "``linkonce_odr``" linkage.
229 "``weak``" linkage has the same merging semantics as ``linkonce``
230 linkage, except that unreferenced globals with ``weak`` linkage may
231 not be discarded. This is used for globals that are declared "weak"
234 "``common``" linkage is most similar to "``weak``" linkage, but they
235 are used for tentative definitions in C, such as "``int X;``" at
236 global scope. Symbols with "``common``" linkage are merged in the
237 same way as ``weak symbols``, and they may not be deleted if
238 unreferenced. ``common`` symbols may not have an explicit section,
239 must have a zero initializer, and may not be marked
240 ':ref:`constant <globalvars>`'. Functions and aliases may not have
243 .. _linkage_appending:
246 "``appending``" linkage may only be applied to global variables of
247 pointer to array type. When two global variables with appending
248 linkage are linked together, the two global arrays are appended
249 together. This is the LLVM, typesafe, equivalent of having the
250 system linker append together "sections" with identical names when
253 The semantics of this linkage follow the ELF object file model: the
254 symbol is weak until linked, if not linked, the symbol becomes null
255 instead of being an undefined reference.
256 ``linkonce_odr``, ``weak_odr``
257 Some languages allow differing globals to be merged, such as two
258 functions with different semantics. Other languages, such as
259 ``C++``, ensure that only equivalent globals are ever merged (the
260 "one definition rule" --- "ODR"). Such languages can use the
261 ``linkonce_odr`` and ``weak_odr`` linkage types to indicate that the
262 global will only be merged with equivalent globals. These linkage
263 types are otherwise the same as their non-``odr`` versions.
265 If none of the above identifiers are used, the global is externally
266 visible, meaning that it participates in linkage and can be used to
267 resolve external symbol references.
269 It is illegal for a function *declaration* to have any linkage type
270 other than ``external`` or ``extern_weak``.
277 LLVM :ref:`functions <functionstructure>`, :ref:`calls <i_call>` and
278 :ref:`invokes <i_invoke>` can all have an optional calling convention
279 specified for the call. The calling convention of any pair of dynamic
280 caller/callee must match, or the behavior of the program is undefined.
281 The following calling conventions are supported by LLVM, and more may be
284 "``ccc``" - The C calling convention
285 This calling convention (the default if no other calling convention
286 is specified) matches the target C calling conventions. This calling
287 convention supports varargs function calls and tolerates some
288 mismatch in the declared prototype and implemented declaration of
289 the function (as does normal C).
290 "``fastcc``" - The fast calling convention
291 This calling convention attempts to make calls as fast as possible
292 (e.g. by passing things in registers). This calling convention
293 allows the target to use whatever tricks it wants to produce fast
294 code for the target, without having to conform to an externally
295 specified ABI (Application Binary Interface). `Tail calls can only
296 be optimized when this, the GHC or the HiPE convention is
297 used. <CodeGenerator.html#id80>`_ This calling convention does not
298 support varargs and requires the prototype of all callees to exactly
299 match the prototype of the function definition.
300 "``coldcc``" - The cold calling convention
301 This calling convention attempts to make code in the caller as
302 efficient as possible under the assumption that the call is not
303 commonly executed. As such, these calls often preserve all registers
304 so that the call does not break any live ranges in the caller side.
305 This calling convention does not support varargs and requires the
306 prototype of all callees to exactly match the prototype of the
307 function definition. Furthermore the inliner doesn't consider such function
309 "``cc 10``" - GHC convention
310 This calling convention has been implemented specifically for use by
311 the `Glasgow Haskell Compiler (GHC) <http://www.haskell.org/ghc>`_.
312 It passes everything in registers, going to extremes to achieve this
313 by disabling callee save registers. This calling convention should
314 not be used lightly but only for specific situations such as an
315 alternative to the *register pinning* performance technique often
316 used when implementing functional programming languages. At the
317 moment only X86 supports this convention and it has the following
320 - On *X86-32* only supports up to 4 bit type parameters. No
321 floating point types are supported.
322 - On *X86-64* only supports up to 10 bit type parameters and 6
323 floating point parameters.
325 This calling convention supports `tail call
326 optimization <CodeGenerator.html#id80>`_ but requires both the
327 caller and callee are using it.
328 "``cc 11``" - The HiPE calling convention
329 This calling convention has been implemented specifically for use by
330 the `High-Performance Erlang
331 (HiPE) <http://www.it.uu.se/research/group/hipe/>`_ compiler, *the*
332 native code compiler of the `Ericsson's Open Source Erlang/OTP
333 system <http://www.erlang.org/download.shtml>`_. It uses more
334 registers for argument passing than the ordinary C calling
335 convention and defines no callee-saved registers. The calling
336 convention properly supports `tail call
337 optimization <CodeGenerator.html#id80>`_ but requires that both the
338 caller and the callee use it. It uses a *register pinning*
339 mechanism, similar to GHC's convention, for keeping frequently
340 accessed runtime components pinned to specific hardware registers.
341 At the moment only X86 supports this convention (both 32 and 64
343 "``webkit_jscc``" - WebKit's JavaScript calling convention
344 This calling convention has been implemented for `WebKit FTL JIT
345 <https://trac.webkit.org/wiki/FTLJIT>`_. It passes arguments on the
346 stack right to left (as cdecl does), and returns a value in the
347 platform's customary return register.
348 "``anyregcc``" - Dynamic calling convention for code patching
349 This is a special convention that supports patching an arbitrary code
350 sequence in place of a call site. This convention forces the call
351 arguments into registers but allows them to be dynamically
352 allocated. This can currently only be used with calls to
353 llvm.experimental.patchpoint because only this intrinsic records
354 the location of its arguments in a side table. See :doc:`StackMaps`.
355 "``preserve_mostcc``" - The `PreserveMost` calling convention
356 This calling convention attempts to make the code in the caller as
357 unintrusive as possible. This convention behaves identically to the `C`
358 calling convention on how arguments and return values are passed, but it
359 uses a different set of caller/callee-saved registers. This alleviates the
360 burden of saving and recovering a large register set before and after the
361 call in the caller. If the arguments are passed in callee-saved registers,
362 then they will be preserved by the callee across the call. This doesn't
363 apply for values returned in callee-saved registers.
365 - On X86-64 the callee preserves all general purpose registers, except for
366 R11. R11 can be used as a scratch register. Floating-point registers
367 (XMMs/YMMs) are not preserved and need to be saved by the caller.
369 The idea behind this convention is to support calls to runtime functions
370 that have a hot path and a cold path. The hot path is usually a small piece
371 of code that doesn't use many registers. The cold path might need to call out to
372 another function and therefore only needs to preserve the caller-saved
373 registers, which haven't already been saved by the caller. The
374 `PreserveMost` calling convention is very similar to the `cold` calling
375 convention in terms of caller/callee-saved registers, but they are used for
376 different types of function calls. `coldcc` is for function calls that are
377 rarely executed, whereas `preserve_mostcc` function calls are intended to be
378 on the hot path and definitely executed a lot. Furthermore `preserve_mostcc`
379 doesn't prevent the inliner from inlining the function call.
381 This calling convention will be used by a future version of the ObjectiveC
382 runtime and should therefore still be considered experimental at this time.
383 Although this convention was created to optimize certain runtime calls to
384 the ObjectiveC runtime, it is not limited to this runtime and might be used
385 by other runtimes in the future too. The current implementation only
386 supports X86-64, but the intention is to support more architectures in the
388 "``preserve_allcc``" - The `PreserveAll` calling convention
389 This calling convention attempts to make the code in the caller even less
390 intrusive than the `PreserveMost` calling convention. This calling
391 convention also behaves identical to the `C` calling convention on how
392 arguments and return values are passed, but it uses a different set of
393 caller/callee-saved registers. This removes the burden of saving and
394 recovering a large register set before and after the call in the caller. If
395 the arguments are passed in callee-saved registers, then they will be
396 preserved by the callee across the call. This doesn't apply for values
397 returned in callee-saved registers.
399 - On X86-64 the callee preserves all general purpose registers, except for
400 R11. R11 can be used as a scratch register. Furthermore it also preserves
401 all floating-point registers (XMMs/YMMs).
403 The idea behind this convention is to support calls to runtime functions
404 that don't need to call out to any other functions.
406 This calling convention, like the `PreserveMost` calling convention, will be
407 used by a future version of the ObjectiveC runtime and should be considered
408 experimental at this time.
409 "``cxx_fast_tlscc``" - The `CXX_FAST_TLS` calling convention for access functions
410 Clang generates an access function to access C++-style TLS. The access
411 function generally has an entry block, an exit block and an initialization
412 block that is run at the first time. The entry and exit blocks can access
413 a few TLS IR variables, each access will be lowered to a platform-specific
416 This calling convention aims to minimize overhead in the caller by
417 preserving as many registers as possible (all the registers that are
418 perserved on the fast path, composed of the entry and exit blocks).
420 This calling convention behaves identical to the `C` calling convention on
421 how arguments and return values are passed, but it uses a different set of
422 caller/callee-saved registers.
424 Given that each platform has its own lowering sequence, hence its own set
425 of preserved registers, we can't use the existing `PreserveMost`.
427 - On X86-64 the callee preserves all general purpose registers, except for
429 "``cc <n>``" - Numbered convention
430 Any calling convention may be specified by number, allowing
431 target-specific calling conventions to be used. Target specific
432 calling conventions start at 64.
434 More calling conventions can be added/defined on an as-needed basis, to
435 support Pascal conventions or any other well-known target-independent
438 .. _visibilitystyles:
443 All Global Variables and Functions have one of the following visibility
446 "``default``" - Default style
447 On targets that use the ELF object file format, default visibility
448 means that the declaration is visible to other modules and, in
449 shared libraries, means that the declared entity may be overridden.
450 On Darwin, default visibility means that the declaration is visible
451 to other modules. Default visibility corresponds to "external
452 linkage" in the language.
453 "``hidden``" - Hidden style
454 Two declarations of an object with hidden visibility refer to the
455 same object if they are in the same shared object. Usually, hidden
456 visibility indicates that the symbol will not be placed into the
457 dynamic symbol table, so no other module (executable or shared
458 library) can reference it directly.
459 "``protected``" - Protected style
460 On ELF, protected visibility indicates that the symbol will be
461 placed in the dynamic symbol table, but that references within the
462 defining module will bind to the local symbol. That is, the symbol
463 cannot be overridden by another module.
465 A symbol with ``internal`` or ``private`` linkage must have ``default``
473 All Global Variables, Functions and Aliases can have one of the following
477 "``dllimport``" causes the compiler to reference a function or variable via
478 a global pointer to a pointer that is set up by the DLL exporting the
479 symbol. On Microsoft Windows targets, the pointer name is formed by
480 combining ``__imp_`` and the function or variable name.
482 "``dllexport``" causes the compiler to provide a global pointer to a pointer
483 in a DLL, so that it can be referenced with the ``dllimport`` attribute. On
484 Microsoft Windows targets, the pointer name is formed by combining
485 ``__imp_`` and the function or variable name. Since this storage class
486 exists for defining a dll interface, the compiler, assembler and linker know
487 it is externally referenced and must refrain from deleting the symbol.
491 Thread Local Storage Models
492 ---------------------------
494 A variable may be defined as ``thread_local``, which means that it will
495 not be shared by threads (each thread will have a separated copy of the
496 variable). Not all targets support thread-local variables. Optionally, a
497 TLS model may be specified:
500 For variables that are only used within the current shared library.
502 For variables in modules that will not be loaded dynamically.
504 For variables defined in the executable and only used within it.
506 If no explicit model is given, the "general dynamic" model is used.
508 The models correspond to the ELF TLS models; see `ELF Handling For
509 Thread-Local Storage <http://people.redhat.com/drepper/tls.pdf>`_ for
510 more information on under which circumstances the different models may
511 be used. The target may choose a different TLS model if the specified
512 model is not supported, or if a better choice of model can be made.
514 A model can also be specified in an alias, but then it only governs how
515 the alias is accessed. It will not have any effect in the aliasee.
517 For platforms without linker support of ELF TLS model, the -femulated-tls
518 flag can be used to generate GCC compatible emulated TLS code.
525 LLVM IR allows you to specify both "identified" and "literal" :ref:`structure
526 types <t_struct>`. Literal types are uniqued structurally, but identified types
527 are never uniqued. An :ref:`opaque structural type <t_opaque>` can also be used
528 to forward declare a type that is not yet available.
530 An example of an identified structure specification is:
534 %mytype = type { %mytype*, i32 }
536 Prior to the LLVM 3.0 release, identified types were structurally uniqued. Only
537 literal types are uniqued in recent versions of LLVM.
544 Global variables define regions of memory allocated at compilation time
547 Global variable definitions must be initialized.
549 Global variables in other translation units can also be declared, in which
550 case they don't have an initializer.
552 Either global variable definitions or declarations may have an explicit section
553 to be placed in and may have an optional explicit alignment specified.
555 A variable may be defined as a global ``constant``, which indicates that
556 the contents of the variable will **never** be modified (enabling better
557 optimization, allowing the global data to be placed in the read-only
558 section of an executable, etc). Note that variables that need runtime
559 initialization cannot be marked ``constant`` as there is a store to the
562 LLVM explicitly allows *declarations* of global variables to be marked
563 constant, even if the final definition of the global is not. This
564 capability can be used to enable slightly better optimization of the
565 program, but requires the language definition to guarantee that
566 optimizations based on the 'constantness' are valid for the translation
567 units that do not include the definition.
569 As SSA values, global variables define pointer values that are in scope
570 (i.e. they dominate) all basic blocks in the program. Global variables
571 always define a pointer to their "content" type because they describe a
572 region of memory, and all memory objects in LLVM are accessed through
575 Global variables can be marked with ``unnamed_addr`` which indicates
576 that the address is not significant, only the content. Constants marked
577 like this can be merged with other constants if they have the same
578 initializer. Note that a constant with significant address *can* be
579 merged with a ``unnamed_addr`` constant, the result being a constant
580 whose address is significant.
582 A global variable may be declared to reside in a target-specific
583 numbered address space. For targets that support them, address spaces
584 may affect how optimizations are performed and/or what target
585 instructions are used to access the variable. The default address space
586 is zero. The address space qualifier must precede any other attributes.
588 LLVM allows an explicit section to be specified for globals. If the
589 target supports it, it will emit globals to the section specified.
590 Additionally, the global can placed in a comdat if the target has the necessary
593 By default, global initializers are optimized by assuming that global
594 variables defined within the module are not modified from their
595 initial values before the start of the global initializer. This is
596 true even for variables potentially accessible from outside the
597 module, including those with external linkage or appearing in
598 ``@llvm.used`` or dllexported variables. This assumption may be suppressed
599 by marking the variable with ``externally_initialized``.
601 An explicit alignment may be specified for a global, which must be a
602 power of 2. If not present, or if the alignment is set to zero, the
603 alignment of the global is set by the target to whatever it feels
604 convenient. If an explicit alignment is specified, the global is forced
605 to have exactly that alignment. Targets and optimizers are not allowed
606 to over-align the global if the global has an assigned section. In this
607 case, the extra alignment could be observable: for example, code could
608 assume that the globals are densely packed in their section and try to
609 iterate over them as an array, alignment padding would break this
610 iteration. The maximum alignment is ``1 << 29``.
612 Globals can also have a :ref:`DLL storage class <dllstorageclass>`.
614 Variables and aliases can have a
615 :ref:`Thread Local Storage Model <tls_model>`.
619 [@<GlobalVarName> =] [Linkage] [Visibility] [DLLStorageClass] [ThreadLocal]
620 [unnamed_addr] [AddrSpace] [ExternallyInitialized]
621 <global | constant> <Type> [<InitializerConstant>]
622 [, section "name"] [, comdat [($name)]]
623 [, align <Alignment>]
625 For example, the following defines a global in a numbered address space
626 with an initializer, section, and alignment:
630 @G = addrspace(5) constant float 1.0, section "foo", align 4
632 The following example just declares a global variable
636 @G = external global i32
638 The following example defines a thread-local global with the
639 ``initialexec`` TLS model:
643 @G = thread_local(initialexec) global i32 0, align 4
645 .. _functionstructure:
650 LLVM function definitions consist of the "``define``" keyword, an
651 optional :ref:`linkage type <linkage>`, an optional :ref:`visibility
652 style <visibility>`, an optional :ref:`DLL storage class <dllstorageclass>`,
653 an optional :ref:`calling convention <callingconv>`,
654 an optional ``unnamed_addr`` attribute, a return type, an optional
655 :ref:`parameter attribute <paramattrs>` for the return type, a function
656 name, a (possibly empty) argument list (each with optional :ref:`parameter
657 attributes <paramattrs>`), optional :ref:`function attributes <fnattrs>`,
658 an optional section, an optional alignment,
659 an optional :ref:`comdat <langref_comdats>`,
660 an optional :ref:`garbage collector name <gc>`, an optional :ref:`prefix <prefixdata>`,
661 an optional :ref:`prologue <prologuedata>`,
662 an optional :ref:`personality <personalityfn>`,
663 an optional list of attached :ref:`metadata <metadata>`,
664 an opening curly brace, a list of basic blocks, and a closing curly brace.
666 LLVM function declarations consist of the "``declare``" keyword, an
667 optional :ref:`linkage type <linkage>`, an optional :ref:`visibility
668 style <visibility>`, an optional :ref:`DLL storage class <dllstorageclass>`,
669 an optional :ref:`calling convention <callingconv>`,
670 an optional ``unnamed_addr`` attribute, a return type, an optional
671 :ref:`parameter attribute <paramattrs>` for the return type, a function
672 name, a possibly empty list of arguments, an optional alignment, an optional
673 :ref:`garbage collector name <gc>`, an optional :ref:`prefix <prefixdata>`,
674 and an optional :ref:`prologue <prologuedata>`.
676 A function definition contains a list of basic blocks, forming the CFG (Control
677 Flow Graph) for the function. Each basic block may optionally start with a label
678 (giving the basic block a symbol table entry), contains a list of instructions,
679 and ends with a :ref:`terminator <terminators>` instruction (such as a branch or
680 function return). If an explicit label is not provided, a block is assigned an
681 implicit numbered label, using the next value from the same counter as used for
682 unnamed temporaries (:ref:`see above<identifiers>`). For example, if a function
683 entry block does not have an explicit label, it will be assigned label "%0",
684 then the first unnamed temporary in that block will be "%1", etc.
686 The first basic block in a function is special in two ways: it is
687 immediately executed on entrance to the function, and it is not allowed
688 to have predecessor basic blocks (i.e. there can not be any branches to
689 the entry block of a function). Because the block can have no
690 predecessors, it also cannot have any :ref:`PHI nodes <i_phi>`.
692 LLVM allows an explicit section to be specified for functions. If the
693 target supports it, it will emit functions to the section specified.
694 Additionally, the function can be placed in a COMDAT.
696 An explicit alignment may be specified for a function. If not present,
697 or if the alignment is set to zero, the alignment of the function is set
698 by the target to whatever it feels convenient. If an explicit alignment
699 is specified, the function is forced to have at least that much
700 alignment. All alignments must be a power of 2.
702 If the ``unnamed_addr`` attribute is given, the address is known to not
703 be significant and two identical functions can be merged.
707 define [linkage] [visibility] [DLLStorageClass]
709 <ResultType> @<FunctionName> ([argument list])
710 [unnamed_addr] [fn Attrs] [section "name"] [comdat [($name)]]
711 [align N] [gc] [prefix Constant] [prologue Constant]
712 [personality Constant] (!name !N)* { ... }
714 The argument list is a comma separated sequence of arguments where each
715 argument is of the following form:
719 <type> [parameter Attrs] [name]
727 Aliases, unlike function or variables, don't create any new data. They
728 are just a new symbol and metadata for an existing position.
730 Aliases have a name and an aliasee that is either a global value or a
733 Aliases may have an optional :ref:`linkage type <linkage>`, an optional
734 :ref:`visibility style <visibility>`, an optional :ref:`DLL storage class
735 <dllstorageclass>` and an optional :ref:`tls model <tls_model>`.
739 @<Name> = [Linkage] [Visibility] [DLLStorageClass] [ThreadLocal] [unnamed_addr] alias <AliaseeTy>, <AliaseeTy>* @<Aliasee>
741 The linkage must be one of ``private``, ``internal``, ``linkonce``, ``weak``,
742 ``linkonce_odr``, ``weak_odr``, ``external``. Note that some system linkers
743 might not correctly handle dropping a weak symbol that is aliased.
745 Aliases that are not ``unnamed_addr`` are guaranteed to have the same address as
746 the aliasee expression. ``unnamed_addr`` ones are only guaranteed to point
749 Since aliases are only a second name, some restrictions apply, of which
750 some can only be checked when producing an object file:
752 * The expression defining the aliasee must be computable at assembly
753 time. Since it is just a name, no relocations can be used.
755 * No alias in the expression can be weak as the possibility of the
756 intermediate alias being overridden cannot be represented in an
759 * No global value in the expression can be a declaration, since that
760 would require a relocation, which is not possible.
767 Comdat IR provides access to COFF and ELF object file COMDAT functionality.
769 Comdats have a name which represents the COMDAT key. All global objects that
770 specify this key will only end up in the final object file if the linker chooses
771 that key over some other key. Aliases are placed in the same COMDAT that their
772 aliasee computes to, if any.
774 Comdats have a selection kind to provide input on how the linker should
775 choose between keys in two different object files.
779 $<Name> = comdat SelectionKind
781 The selection kind must be one of the following:
784 The linker may choose any COMDAT key, the choice is arbitrary.
786 The linker may choose any COMDAT key but the sections must contain the
789 The linker will choose the section containing the largest COMDAT key.
791 The linker requires that only section with this COMDAT key exist.
793 The linker may choose any COMDAT key but the sections must contain the
796 Note that the Mach-O platform doesn't support COMDATs and ELF only supports
797 ``any`` as a selection kind.
799 Here is an example of a COMDAT group where a function will only be selected if
800 the COMDAT key's section is the largest:
804 $foo = comdat largest
805 @foo = global i32 2, comdat($foo)
807 define void @bar() comdat($foo) {
811 As a syntactic sugar the ``$name`` can be omitted if the name is the same as
817 @foo = global i32 2, comdat
820 In a COFF object file, this will create a COMDAT section with selection kind
821 ``IMAGE_COMDAT_SELECT_LARGEST`` containing the contents of the ``@foo`` symbol
822 and another COMDAT section with selection kind
823 ``IMAGE_COMDAT_SELECT_ASSOCIATIVE`` which is associated with the first COMDAT
824 section and contains the contents of the ``@bar`` symbol.
826 There are some restrictions on the properties of the global object.
827 It, or an alias to it, must have the same name as the COMDAT group when
829 The contents and size of this object may be used during link-time to determine
830 which COMDAT groups get selected depending on the selection kind.
831 Because the name of the object must match the name of the COMDAT group, the
832 linkage of the global object must not be local; local symbols can get renamed
833 if a collision occurs in the symbol table.
835 The combined use of COMDATS and section attributes may yield surprising results.
842 @g1 = global i32 42, section "sec", comdat($foo)
843 @g2 = global i32 42, section "sec", comdat($bar)
845 From the object file perspective, this requires the creation of two sections
846 with the same name. This is necessary because both globals belong to different
847 COMDAT groups and COMDATs, at the object file level, are represented by
850 Note that certain IR constructs like global variables and functions may
851 create COMDATs in the object file in addition to any which are specified using
852 COMDAT IR. This arises when the code generator is configured to emit globals
853 in individual sections (e.g. when `-data-sections` or `-function-sections`
854 is supplied to `llc`).
856 .. _namedmetadatastructure:
861 Named metadata is a collection of metadata. :ref:`Metadata
862 nodes <metadata>` (but not metadata strings) are the only valid
863 operands for a named metadata.
865 #. Named metadata are represented as a string of characters with the
866 metadata prefix. The rules for metadata names are the same as for
867 identifiers, but quoted names are not allowed. ``"\xx"`` type escapes
868 are still valid, which allows any character to be part of a name.
872 ; Some unnamed metadata nodes, which are referenced by the named metadata.
877 !name = !{!0, !1, !2}
884 The return type and each parameter of a function type may have a set of
885 *parameter attributes* associated with them. Parameter attributes are
886 used to communicate additional information about the result or
887 parameters of a function. Parameter attributes are considered to be part
888 of the function, not of the function type, so functions with different
889 parameter attributes can have the same function type.
891 Parameter attributes are simple keywords that follow the type specified.
892 If multiple parameter attributes are needed, they are space separated.
897 declare i32 @printf(i8* noalias nocapture, ...)
898 declare i32 @atoi(i8 zeroext)
899 declare signext i8 @returns_signed_char()
901 Note that any attributes for the function result (``nounwind``,
902 ``readonly``) come immediately after the argument list.
904 Currently, only the following parameter attributes are defined:
907 This indicates to the code generator that the parameter or return
908 value should be zero-extended to the extent required by the target's
909 ABI (which is usually 32-bits, but is 8-bits for a i1 on x86-64) by
910 the caller (for a parameter) or the callee (for a return value).
912 This indicates to the code generator that the parameter or return
913 value should be sign-extended to the extent required by the target's
914 ABI (which is usually 32-bits) by the caller (for a parameter) or
915 the callee (for a return value).
917 This indicates that this parameter or return value should be treated
918 in a special target-dependent fashion while emitting code for
919 a function call or return (usually, by putting it in a register as
920 opposed to memory, though some targets use it to distinguish between
921 two different kinds of registers). Use of this attribute is
924 This indicates that the pointer parameter should really be passed by
925 value to the function. The attribute implies that a hidden copy of
926 the pointee is made between the caller and the callee, so the callee
927 is unable to modify the value in the caller. This attribute is only
928 valid on LLVM pointer arguments. It is generally used to pass
929 structs and arrays by value, but is also valid on pointers to
930 scalars. The copy is considered to belong to the caller not the
931 callee (for example, ``readonly`` functions should not write to
932 ``byval`` parameters). This is not a valid attribute for return
935 The byval attribute also supports specifying an alignment with the
936 align attribute. It indicates the alignment of the stack slot to
937 form and the known alignment of the pointer specified to the call
938 site. If the alignment is not specified, then the code generator
939 makes a target-specific assumption.
945 The ``inalloca`` argument attribute allows the caller to take the
946 address of outgoing stack arguments. An ``inalloca`` argument must
947 be a pointer to stack memory produced by an ``alloca`` instruction.
948 The alloca, or argument allocation, must also be tagged with the
949 inalloca keyword. Only the last argument may have the ``inalloca``
950 attribute, and that argument is guaranteed to be passed in memory.
952 An argument allocation may be used by a call at most once because
953 the call may deallocate it. The ``inalloca`` attribute cannot be
954 used in conjunction with other attributes that affect argument
955 storage, like ``inreg``, ``nest``, ``sret``, or ``byval``. The
956 ``inalloca`` attribute also disables LLVM's implicit lowering of
957 large aggregate return values, which means that frontend authors
958 must lower them with ``sret`` pointers.
960 When the call site is reached, the argument allocation must have
961 been the most recent stack allocation that is still live, or the
962 results are undefined. It is possible to allocate additional stack
963 space after an argument allocation and before its call site, but it
964 must be cleared off with :ref:`llvm.stackrestore
967 See :doc:`InAlloca` for more information on how to use this
971 This indicates that the pointer parameter specifies the address of a
972 structure that is the return value of the function in the source
973 program. This pointer must be guaranteed by the caller to be valid:
974 loads and stores to the structure may be assumed by the callee
975 not to trap and to be properly aligned. This may only be applied to
976 the first parameter. This is not a valid attribute for return
980 This indicates that the pointer value may be assumed by the optimizer to
981 have the specified alignment.
983 Note that this attribute has additional semantics when combined with the
989 This indicates that objects accessed via pointer values
990 :ref:`based <pointeraliasing>` on the argument or return value are not also
991 accessed, during the execution of the function, via pointer values not
992 *based* on the argument or return value. The attribute on a return value
993 also has additional semantics described below. The caller shares the
994 responsibility with the callee for ensuring that these requirements are met.
995 For further details, please see the discussion of the NoAlias response in
996 :ref:`alias analysis <Must, May, or No>`.
998 Note that this definition of ``noalias`` is intentionally similar
999 to the definition of ``restrict`` in C99 for function arguments.
1001 For function return values, C99's ``restrict`` is not meaningful,
1002 while LLVM's ``noalias`` is. Furthermore, the semantics of the ``noalias``
1003 attribute on return values are stronger than the semantics of the attribute
1004 when used on function arguments. On function return values, the ``noalias``
1005 attribute indicates that the function acts like a system memory allocation
1006 function, returning a pointer to allocated storage disjoint from the
1007 storage for any other object accessible to the caller.
1010 This indicates that the callee does not make any copies of the
1011 pointer that outlive the callee itself. This is not a valid
1012 attribute for return values.
1017 This indicates that the pointer parameter can be excised using the
1018 :ref:`trampoline intrinsics <int_trampoline>`. This is not a valid
1019 attribute for return values and can only be applied to one parameter.
1022 This indicates that the function always returns the argument as its return
1023 value. This is an optimization hint to the code generator when generating
1024 the caller, allowing tail call optimization and omission of register saves
1025 and restores in some cases; it is not checked or enforced when generating
1026 the callee. The parameter and the function return type must be valid
1027 operands for the :ref:`bitcast instruction <i_bitcast>`. This is not a
1028 valid attribute for return values and can only be applied to one parameter.
1031 This indicates that the parameter or return pointer is not null. This
1032 attribute may only be applied to pointer typed parameters. This is not
1033 checked or enforced by LLVM, the caller must ensure that the pointer
1034 passed in is non-null, or the callee must ensure that the returned pointer
1037 ``dereferenceable(<n>)``
1038 This indicates that the parameter or return pointer is dereferenceable. This
1039 attribute may only be applied to pointer typed parameters. A pointer that
1040 is dereferenceable can be loaded from speculatively without a risk of
1041 trapping. The number of bytes known to be dereferenceable must be provided
1042 in parentheses. It is legal for the number of bytes to be less than the
1043 size of the pointee type. The ``nonnull`` attribute does not imply
1044 dereferenceability (consider a pointer to one element past the end of an
1045 array), however ``dereferenceable(<n>)`` does imply ``nonnull`` in
1046 ``addrspace(0)`` (which is the default address space).
1048 ``dereferenceable_or_null(<n>)``
1049 This indicates that the parameter or return value isn't both
1050 non-null and non-dereferenceable (up to ``<n>`` bytes) at the same
1051 time. All non-null pointers tagged with
1052 ``dereferenceable_or_null(<n>)`` are ``dereferenceable(<n>)``.
1053 For address space 0 ``dereferenceable_or_null(<n>)`` implies that
1054 a pointer is exactly one of ``dereferenceable(<n>)`` or ``null``,
1055 and in other address spaces ``dereferenceable_or_null(<n>)``
1056 implies that a pointer is at least one of ``dereferenceable(<n>)``
1057 or ``null`` (i.e. it may be both ``null`` and
1058 ``dereferenceable(<n>)``). This attribute may only be applied to
1059 pointer typed parameters.
1063 Garbage Collector Strategy Names
1064 --------------------------------
1066 Each function may specify a garbage collector strategy name, which is simply a
1069 .. code-block:: llvm
1071 define void @f() gc "name" { ... }
1073 The supported values of *name* includes those :ref:`built in to LLVM
1074 <builtin-gc-strategies>` and any provided by loaded plugins. Specifying a GC
1075 strategy will cause the compiler to alter its output in order to support the
1076 named garbage collection algorithm. Note that LLVM itself does not contain a
1077 garbage collector, this functionality is restricted to generating machine code
1078 which can interoperate with a collector provided externally.
1085 Prefix data is data associated with a function which the code
1086 generator will emit immediately before the function's entrypoint.
1087 The purpose of this feature is to allow frontends to associate
1088 language-specific runtime metadata with specific functions and make it
1089 available through the function pointer while still allowing the
1090 function pointer to be called.
1092 To access the data for a given function, a program may bitcast the
1093 function pointer to a pointer to the constant's type and dereference
1094 index -1. This implies that the IR symbol points just past the end of
1095 the prefix data. For instance, take the example of a function annotated
1096 with a single ``i32``,
1098 .. code-block:: llvm
1100 define void @f() prefix i32 123 { ... }
1102 The prefix data can be referenced as,
1104 .. code-block:: llvm
1106 %0 = bitcast void* () @f to i32*
1107 %a = getelementptr inbounds i32, i32* %0, i32 -1
1108 %b = load i32, i32* %a
1110 Prefix data is laid out as if it were an initializer for a global variable
1111 of the prefix data's type. The function will be placed such that the
1112 beginning of the prefix data is aligned. This means that if the size
1113 of the prefix data is not a multiple of the alignment size, the
1114 function's entrypoint will not be aligned. If alignment of the
1115 function's entrypoint is desired, padding must be added to the prefix
1118 A function may have prefix data but no body. This has similar semantics
1119 to the ``available_externally`` linkage in that the data may be used by the
1120 optimizers but will not be emitted in the object file.
1127 The ``prologue`` attribute allows arbitrary code (encoded as bytes) to
1128 be inserted prior to the function body. This can be used for enabling
1129 function hot-patching and instrumentation.
1131 To maintain the semantics of ordinary function calls, the prologue data must
1132 have a particular format. Specifically, it must begin with a sequence of
1133 bytes which decode to a sequence of machine instructions, valid for the
1134 module's target, which transfer control to the point immediately succeeding
1135 the prologue data, without performing any other visible action. This allows
1136 the inliner and other passes to reason about the semantics of the function
1137 definition without needing to reason about the prologue data. Obviously this
1138 makes the format of the prologue data highly target dependent.
1140 A trivial example of valid prologue data for the x86 architecture is ``i8 144``,
1141 which encodes the ``nop`` instruction:
1143 .. code-block:: llvm
1145 define void @f() prologue i8 144 { ... }
1147 Generally prologue data can be formed by encoding a relative branch instruction
1148 which skips the metadata, as in this example of valid prologue data for the
1149 x86_64 architecture, where the first two bytes encode ``jmp .+10``:
1151 .. code-block:: llvm
1153 %0 = type <{ i8, i8, i8* }>
1155 define void @f() prologue %0 <{ i8 235, i8 8, i8* @md}> { ... }
1157 A function may have prologue data but no body. This has similar semantics
1158 to the ``available_externally`` linkage in that the data may be used by the
1159 optimizers but will not be emitted in the object file.
1163 Personality Function
1164 --------------------
1166 The ``personality`` attribute permits functions to specify what function
1167 to use for exception handling.
1174 Attribute groups are groups of attributes that are referenced by objects within
1175 the IR. They are important for keeping ``.ll`` files readable, because a lot of
1176 functions will use the same set of attributes. In the degenerative case of a
1177 ``.ll`` file that corresponds to a single ``.c`` file, the single attribute
1178 group will capture the important command line flags used to build that file.
1180 An attribute group is a module-level object. To use an attribute group, an
1181 object references the attribute group's ID (e.g. ``#37``). An object may refer
1182 to more than one attribute group. In that situation, the attributes from the
1183 different groups are merged.
1185 Here is an example of attribute groups for a function that should always be
1186 inlined, has a stack alignment of 4, and which shouldn't use SSE instructions:
1188 .. code-block:: llvm
1190 ; Target-independent attributes:
1191 attributes #0 = { alwaysinline alignstack=4 }
1193 ; Target-dependent attributes:
1194 attributes #1 = { "no-sse" }
1196 ; Function @f has attributes: alwaysinline, alignstack=4, and "no-sse".
1197 define void @f() #0 #1 { ... }
1204 Function attributes are set to communicate additional information about
1205 a function. Function attributes are considered to be part of the
1206 function, not of the function type, so functions with different function
1207 attributes can have the same function type.
1209 Function attributes are simple keywords that follow the type specified.
1210 If multiple attributes are needed, they are space separated. For
1213 .. code-block:: llvm
1215 define void @f() noinline { ... }
1216 define void @f() alwaysinline { ... }
1217 define void @f() alwaysinline optsize { ... }
1218 define void @f() optsize { ... }
1221 This attribute indicates that, when emitting the prologue and
1222 epilogue, the backend should forcibly align the stack pointer.
1223 Specify the desired alignment, which must be a power of two, in
1226 This attribute indicates that the inliner should attempt to inline
1227 this function into callers whenever possible, ignoring any active
1228 inlining size threshold for this caller.
1230 This indicates that the callee function at a call site should be
1231 recognized as a built-in function, even though the function's declaration
1232 uses the ``nobuiltin`` attribute. This is only valid at call sites for
1233 direct calls to functions that are declared with the ``nobuiltin``
1236 This attribute indicates that this function is rarely called. When
1237 computing edge weights, basic blocks post-dominated by a cold
1238 function call are also considered to be cold; and, thus, given low
1241 This attribute indicates that the callee is dependent on a convergent
1242 thread execution pattern under certain parallel execution models.
1243 Transformations that are execution model agnostic may not make the execution
1244 of a convergent operation control dependent on any additional values.
1246 This attribute indicates that the source code contained a hint that
1247 inlining this function is desirable (such as the "inline" keyword in
1248 C/C++). It is just a hint; it imposes no requirements on the
1251 This attribute indicates that the function should be added to a
1252 jump-instruction table at code-generation time, and that all address-taken
1253 references to this function should be replaced with a reference to the
1254 appropriate jump-instruction-table function pointer. Note that this creates
1255 a new pointer for the original function, which means that code that depends
1256 on function-pointer identity can break. So, any function annotated with
1257 ``jumptable`` must also be ``unnamed_addr``.
1259 This attribute suggests that optimization passes and code generator
1260 passes make choices that keep the code size of this function as small
1261 as possible and perform optimizations that may sacrifice runtime
1262 performance in order to minimize the size of the generated code.
1264 This attribute disables prologue / epilogue emission for the
1265 function. This can have very system-specific consequences.
1267 This indicates that the callee function at a call site is not recognized as
1268 a built-in function. LLVM will retain the original call and not replace it
1269 with equivalent code based on the semantics of the built-in function, unless
1270 the call site uses the ``builtin`` attribute. This is valid at call sites
1271 and on function declarations and definitions.
1273 This attribute indicates that calls to the function cannot be
1274 duplicated. A call to a ``noduplicate`` function may be moved
1275 within its parent function, but may not be duplicated within
1276 its parent function.
1278 A function containing a ``noduplicate`` call may still
1279 be an inlining candidate, provided that the call is not
1280 duplicated by inlining. That implies that the function has
1281 internal linkage and only has one call site, so the original
1282 call is dead after inlining.
1284 This attributes disables implicit floating point instructions.
1286 This attribute indicates that the inliner should never inline this
1287 function in any situation. This attribute may not be used together
1288 with the ``alwaysinline`` attribute.
1290 This attribute suppresses lazy symbol binding for the function. This
1291 may make calls to the function faster, at the cost of extra program
1292 startup time if the function is not called during program startup.
1294 This attribute indicates that the code generator should not use a
1295 red zone, even if the target-specific ABI normally permits it.
1297 This function attribute indicates that the function never returns
1298 normally. This produces undefined behavior at runtime if the
1299 function ever does dynamically return.
1301 This function attribute indicates that the function does not call itself
1302 either directly or indirectly down any possible call path. This produces
1303 undefined behavior at runtime if the function ever does recurse.
1305 This function attribute indicates that the function never raises an
1306 exception. If the function does raise an exception, its runtime
1307 behavior is undefined. However, functions marked nounwind may still
1308 trap or generate asynchronous exceptions. Exception handling schemes
1309 that are recognized by LLVM to handle asynchronous exceptions, such
1310 as SEH, will still provide their implementation defined semantics.
1312 This function attribute indicates that most optimization passes will skip
1313 this function, with the exception of interprocedural optimization passes.
1314 Code generation defaults to the "fast" instruction selector.
1315 This attribute cannot be used together with the ``alwaysinline``
1316 attribute; this attribute is also incompatible
1317 with the ``minsize`` attribute and the ``optsize`` attribute.
1319 This attribute requires the ``noinline`` attribute to be specified on
1320 the function as well, so the function is never inlined into any caller.
1321 Only functions with the ``alwaysinline`` attribute are valid
1322 candidates for inlining into the body of this function.
1324 This attribute suggests that optimization passes and code generator
1325 passes make choices that keep the code size of this function low,
1326 and otherwise do optimizations specifically to reduce code size as
1327 long as they do not significantly impact runtime performance.
1329 On a function, this attribute indicates that the function computes its
1330 result (or decides to unwind an exception) based strictly on its arguments,
1331 without dereferencing any pointer arguments or otherwise accessing
1332 any mutable state (e.g. memory, control registers, etc) visible to
1333 caller functions. It does not write through any pointer arguments
1334 (including ``byval`` arguments) and never changes any state visible
1335 to callers. This means that it cannot unwind exceptions by calling
1336 the ``C++`` exception throwing methods.
1338 On an argument, this attribute indicates that the function does not
1339 dereference that pointer argument, even though it may read or write the
1340 memory that the pointer points to if accessed through other pointers.
1342 On a function, this attribute indicates that the function does not write
1343 through any pointer arguments (including ``byval`` arguments) or otherwise
1344 modify any state (e.g. memory, control registers, etc) visible to
1345 caller functions. It may dereference pointer arguments and read
1346 state that may be set in the caller. A readonly function always
1347 returns the same value (or unwinds an exception identically) when
1348 called with the same set of arguments and global state. It cannot
1349 unwind an exception by calling the ``C++`` exception throwing
1352 On an argument, this attribute indicates that the function does not write
1353 through this pointer argument, even though it may write to the memory that
1354 the pointer points to.
1356 This attribute indicates that the only memory accesses inside function are
1357 loads and stores from objects pointed to by its pointer-typed arguments,
1358 with arbitrary offsets. Or in other words, all memory operations in the
1359 function can refer to memory only using pointers based on its function
1361 Note that ``argmemonly`` can be used together with ``readonly`` attribute
1362 in order to specify that function reads only from its arguments.
1364 This attribute indicates that this function can return twice. The C
1365 ``setjmp`` is an example of such a function. The compiler disables
1366 some optimizations (like tail calls) in the caller of these
1369 This attribute indicates that
1370 `SafeStack <http://clang.llvm.org/docs/SafeStack.html>`_
1371 protection is enabled for this function.
1373 If a function that has a ``safestack`` attribute is inlined into a
1374 function that doesn't have a ``safestack`` attribute or which has an
1375 ``ssp``, ``sspstrong`` or ``sspreq`` attribute, then the resulting
1376 function will have a ``safestack`` attribute.
1377 ``sanitize_address``
1378 This attribute indicates that AddressSanitizer checks
1379 (dynamic address safety analysis) are enabled for this function.
1381 This attribute indicates that MemorySanitizer checks (dynamic detection
1382 of accesses to uninitialized memory) are enabled for this function.
1384 This attribute indicates that ThreadSanitizer checks
1385 (dynamic thread safety analysis) are enabled for this function.
1387 This attribute indicates that the function should emit a stack
1388 smashing protector. It is in the form of a "canary" --- a random value
1389 placed on the stack before the local variables that's checked upon
1390 return from the function to see if it has been overwritten. A
1391 heuristic is used to determine if a function needs stack protectors
1392 or not. The heuristic used will enable protectors for functions with:
1394 - Character arrays larger than ``ssp-buffer-size`` (default 8).
1395 - Aggregates containing character arrays larger than ``ssp-buffer-size``.
1396 - Calls to alloca() with variable sizes or constant sizes greater than
1397 ``ssp-buffer-size``.
1399 Variables that are identified as requiring a protector will be arranged
1400 on the stack such that they are adjacent to the stack protector guard.
1402 If a function that has an ``ssp`` attribute is inlined into a
1403 function that doesn't have an ``ssp`` attribute, then the resulting
1404 function will have an ``ssp`` attribute.
1406 This attribute indicates that the function should *always* emit a
1407 stack smashing protector. This overrides the ``ssp`` function
1410 Variables that are identified as requiring a protector will be arranged
1411 on the stack such that they are adjacent to the stack protector guard.
1412 The specific layout rules are:
1414 #. Large arrays and structures containing large arrays
1415 (``>= ssp-buffer-size``) are closest to the stack protector.
1416 #. Small arrays and structures containing small arrays
1417 (``< ssp-buffer-size``) are 2nd closest to the protector.
1418 #. Variables that have had their address taken are 3rd closest to the
1421 If a function that has an ``sspreq`` attribute is inlined into a
1422 function that doesn't have an ``sspreq`` attribute or which has an
1423 ``ssp`` or ``sspstrong`` attribute, then the resulting function will have
1424 an ``sspreq`` attribute.
1426 This attribute indicates that the function should emit a stack smashing
1427 protector. This attribute causes a strong heuristic to be used when
1428 determining if a function needs stack protectors. The strong heuristic
1429 will enable protectors for functions with:
1431 - Arrays of any size and type
1432 - Aggregates containing an array of any size and type.
1433 - Calls to alloca().
1434 - Local variables that have had their address taken.
1436 Variables that are identified as requiring a protector will be arranged
1437 on the stack such that they are adjacent to the stack protector guard.
1438 The specific layout rules are:
1440 #. Large arrays and structures containing large arrays
1441 (``>= ssp-buffer-size``) are closest to the stack protector.
1442 #. Small arrays and structures containing small arrays
1443 (``< ssp-buffer-size``) are 2nd closest to the protector.
1444 #. Variables that have had their address taken are 3rd closest to the
1447 This overrides the ``ssp`` function attribute.
1449 If a function that has an ``sspstrong`` attribute is inlined into a
1450 function that doesn't have an ``sspstrong`` attribute, then the
1451 resulting function will have an ``sspstrong`` attribute.
1453 This attribute indicates that the function will delegate to some other
1454 function with a tail call. The prototype of a thunk should not be used for
1455 optimization purposes. The caller is expected to cast the thunk prototype to
1456 match the thunk target prototype.
1458 This attribute indicates that the ABI being targeted requires that
1459 an unwind table entry be produced for this function even if we can
1460 show that no exceptions passes by it. This is normally the case for
1461 the ELF x86-64 abi, but it can be disabled for some compilation
1470 Note: operand bundles are a work in progress, and they should be
1471 considered experimental at this time.
1473 Operand bundles are tagged sets of SSA values that can be associated
1474 with certain LLVM instructions (currently only ``call`` s and
1475 ``invoke`` s). In a way they are like metadata, but dropping them is
1476 incorrect and will change program semantics.
1480 operand bundle set ::= '[' operand bundle (, operand bundle )* ']'
1481 operand bundle ::= tag '(' [ bundle operand ] (, bundle operand )* ')'
1482 bundle operand ::= SSA value
1483 tag ::= string constant
1485 Operand bundles are **not** part of a function's signature, and a
1486 given function may be called from multiple places with different kinds
1487 of operand bundles. This reflects the fact that the operand bundles
1488 are conceptually a part of the ``call`` (or ``invoke``), not the
1489 callee being dispatched to.
1491 Operand bundles are a generic mechanism intended to support
1492 runtime-introspection-like functionality for managed languages. While
1493 the exact semantics of an operand bundle depend on the bundle tag,
1494 there are certain limitations to how much the presence of an operand
1495 bundle can influence the semantics of a program. These restrictions
1496 are described as the semantics of an "unknown" operand bundle. As
1497 long as the behavior of an operand bundle is describable within these
1498 restrictions, LLVM does not need to have special knowledge of the
1499 operand bundle to not miscompile programs containing it.
1501 - The bundle operands for an unknown operand bundle escape in unknown
1502 ways before control is transferred to the callee or invokee.
1503 - Calls and invokes with operand bundles have unknown read / write
1504 effect on the heap on entry and exit (even if the call target is
1505 ``readnone`` or ``readonly``), unless they're overriden with
1506 callsite specific attributes.
1507 - An operand bundle at a call site cannot change the implementation
1508 of the called function. Inter-procedural optimizations work as
1509 usual as long as they take into account the first two properties.
1511 More specific types of operand bundles are described below.
1513 Deoptimization Operand Bundles
1514 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1516 Deoptimization operand bundles are characterized by the ``"deopt"``
1517 operand bundle tag. These operand bundles represent an alternate
1518 "safe" continuation for the call site they're attached to, and can be
1519 used by a suitable runtime to deoptimize the compiled frame at the
1520 specified call site. There can be at most one ``"deopt"`` operand
1521 bundle attached to a call site. Exact details of deoptimization is
1522 out of scope for the language reference, but it usually involves
1523 rewriting a compiled frame into a set of interpreted frames.
1525 From the compiler's perspective, deoptimization operand bundles make
1526 the call sites they're attached to at least ``readonly``. They read
1527 through all of their pointer typed operands (even if they're not
1528 otherwise escaped) and the entire visible heap. Deoptimization
1529 operand bundles do not capture their operands except during
1530 deoptimization, in which case control will not be returned to the
1533 The inliner knows how to inline through calls that have deoptimization
1534 operand bundles. Just like inlining through a normal call site
1535 involves composing the normal and exceptional continuations, inlining
1536 through a call site with a deoptimization operand bundle needs to
1537 appropriately compose the "safe" deoptimization continuation. The
1538 inliner does this by prepending the parent's deoptimization
1539 continuation to every deoptimization continuation in the inlined body.
1540 E.g. inlining ``@f`` into ``@g`` in the following example
1542 .. code-block:: llvm
1545 call void @x() ;; no deopt state
1546 call void @y() [ "deopt"(i32 10) ]
1547 call void @y() [ "deopt"(i32 10), "unknown"(i8* null) ]
1552 call void @f() [ "deopt"(i32 20) ]
1558 .. code-block:: llvm
1561 call void @x() ;; still no deopt state
1562 call void @y() [ "deopt"(i32 20, i32 10) ]
1563 call void @y() [ "deopt"(i32 20, i32 10), "unknown"(i8* null) ]
1567 It is the frontend's responsibility to structure or encode the
1568 deoptimization state in a way that syntactically prepending the
1569 caller's deoptimization state to the callee's deoptimization state is
1570 semantically equivalent to composing the caller's deoptimization
1571 continuation after the callee's deoptimization continuation.
1575 Module-Level Inline Assembly
1576 ----------------------------
1578 Modules may contain "module-level inline asm" blocks, which corresponds
1579 to the GCC "file scope inline asm" blocks. These blocks are internally
1580 concatenated by LLVM and treated as a single unit, but may be separated
1581 in the ``.ll`` file if desired. The syntax is very simple:
1583 .. code-block:: llvm
1585 module asm "inline asm code goes here"
1586 module asm "more can go here"
1588 The strings can contain any character by escaping non-printable
1589 characters. The escape sequence used is simply "\\xx" where "xx" is the
1590 two digit hex code for the number.
1592 Note that the assembly string *must* be parseable by LLVM's integrated assembler
1593 (unless it is disabled), even when emitting a ``.s`` file.
1595 .. _langref_datalayout:
1600 A module may specify a target specific data layout string that specifies
1601 how data is to be laid out in memory. The syntax for the data layout is
1604 .. code-block:: llvm
1606 target datalayout = "layout specification"
1608 The *layout specification* consists of a list of specifications
1609 separated by the minus sign character ('-'). Each specification starts
1610 with a letter and may include other information after the letter to
1611 define some aspect of the data layout. The specifications accepted are
1615 Specifies that the target lays out data in big-endian form. That is,
1616 the bits with the most significance have the lowest address
1619 Specifies that the target lays out data in little-endian form. That
1620 is, the bits with the least significance have the lowest address
1623 Specifies the natural alignment of the stack in bits. Alignment
1624 promotion of stack variables is limited to the natural stack
1625 alignment to avoid dynamic stack realignment. The stack alignment
1626 must be a multiple of 8-bits. If omitted, the natural stack
1627 alignment defaults to "unspecified", which does not prevent any
1628 alignment promotions.
1629 ``p[n]:<size>:<abi>:<pref>``
1630 This specifies the *size* of a pointer and its ``<abi>`` and
1631 ``<pref>``\erred alignments for address space ``n``. All sizes are in
1632 bits. The address space, ``n``, is optional, and if not specified,
1633 denotes the default address space 0. The value of ``n`` must be
1634 in the range [1,2^23).
1635 ``i<size>:<abi>:<pref>``
1636 This specifies the alignment for an integer type of a given bit
1637 ``<size>``. The value of ``<size>`` must be in the range [1,2^23).
1638 ``v<size>:<abi>:<pref>``
1639 This specifies the alignment for a vector type of a given bit
1641 ``f<size>:<abi>:<pref>``
1642 This specifies the alignment for a floating point type of a given bit
1643 ``<size>``. Only values of ``<size>`` that are supported by the target
1644 will work. 32 (float) and 64 (double) are supported on all targets; 80
1645 or 128 (different flavors of long double) are also supported on some
1648 This specifies the alignment for an object of aggregate type.
1650 If present, specifies that llvm names are mangled in the output. The
1653 * ``e``: ELF mangling: Private symbols get a ``.L`` prefix.
1654 * ``m``: Mips mangling: Private symbols get a ``$`` prefix.
1655 * ``o``: Mach-O mangling: Private symbols get ``L`` prefix. Other
1656 symbols get a ``_`` prefix.
1657 * ``w``: Windows COFF prefix: Similar to Mach-O, but stdcall and fastcall
1658 functions also get a suffix based on the frame size.
1659 * ``x``: Windows x86 COFF prefix: Similar to Windows COFF, but use a ``_``
1660 prefix for ``__cdecl`` functions.
1661 ``n<size1>:<size2>:<size3>...``
1662 This specifies a set of native integer widths for the target CPU in
1663 bits. For example, it might contain ``n32`` for 32-bit PowerPC,
1664 ``n32:64`` for PowerPC 64, or ``n8:16:32:64`` for X86-64. Elements of
1665 this set are considered to support most general arithmetic operations
1668 On every specification that takes a ``<abi>:<pref>``, specifying the
1669 ``<pref>`` alignment is optional. If omitted, the preceding ``:``
1670 should be omitted too and ``<pref>`` will be equal to ``<abi>``.
1672 When constructing the data layout for a given target, LLVM starts with a
1673 default set of specifications which are then (possibly) overridden by
1674 the specifications in the ``datalayout`` keyword. The default
1675 specifications are given in this list:
1677 - ``E`` - big endian
1678 - ``p:64:64:64`` - 64-bit pointers with 64-bit alignment.
1679 - ``p[n]:64:64:64`` - Other address spaces are assumed to be the
1680 same as the default address space.
1681 - ``S0`` - natural stack alignment is unspecified
1682 - ``i1:8:8`` - i1 is 8-bit (byte) aligned
1683 - ``i8:8:8`` - i8 is 8-bit (byte) aligned
1684 - ``i16:16:16`` - i16 is 16-bit aligned
1685 - ``i32:32:32`` - i32 is 32-bit aligned
1686 - ``i64:32:64`` - i64 has ABI alignment of 32-bits but preferred
1687 alignment of 64-bits
1688 - ``f16:16:16`` - half is 16-bit aligned
1689 - ``f32:32:32`` - float is 32-bit aligned
1690 - ``f64:64:64`` - double is 64-bit aligned
1691 - ``f128:128:128`` - quad is 128-bit aligned
1692 - ``v64:64:64`` - 64-bit vector is 64-bit aligned
1693 - ``v128:128:128`` - 128-bit vector is 128-bit aligned
1694 - ``a:0:64`` - aggregates are 64-bit aligned
1696 When LLVM is determining the alignment for a given type, it uses the
1699 #. If the type sought is an exact match for one of the specifications,
1700 that specification is used.
1701 #. If no match is found, and the type sought is an integer type, then
1702 the smallest integer type that is larger than the bitwidth of the
1703 sought type is used. If none of the specifications are larger than
1704 the bitwidth then the largest integer type is used. For example,
1705 given the default specifications above, the i7 type will use the
1706 alignment of i8 (next largest) while both i65 and i256 will use the
1707 alignment of i64 (largest specified).
1708 #. If no match is found, and the type sought is a vector type, then the
1709 largest vector type that is smaller than the sought vector type will
1710 be used as a fall back. This happens because <128 x double> can be
1711 implemented in terms of 64 <2 x double>, for example.
1713 The function of the data layout string may not be what you expect.
1714 Notably, this is not a specification from the frontend of what alignment
1715 the code generator should use.
1717 Instead, if specified, the target data layout is required to match what
1718 the ultimate *code generator* expects. This string is used by the
1719 mid-level optimizers to improve code, and this only works if it matches
1720 what the ultimate code generator uses. There is no way to generate IR
1721 that does not embed this target-specific detail into the IR. If you
1722 don't specify the string, the default specifications will be used to
1723 generate a Data Layout and the optimization phases will operate
1724 accordingly and introduce target specificity into the IR with respect to
1725 these default specifications.
1732 A module may specify a target triple string that describes the target
1733 host. The syntax for the target triple is simply:
1735 .. code-block:: llvm
1737 target triple = "x86_64-apple-macosx10.7.0"
1739 The *target triple* string consists of a series of identifiers delimited
1740 by the minus sign character ('-'). The canonical forms are:
1744 ARCHITECTURE-VENDOR-OPERATING_SYSTEM
1745 ARCHITECTURE-VENDOR-OPERATING_SYSTEM-ENVIRONMENT
1747 This information is passed along to the backend so that it generates
1748 code for the proper architecture. It's possible to override this on the
1749 command line with the ``-mtriple`` command line option.
1751 .. _pointeraliasing:
1753 Pointer Aliasing Rules
1754 ----------------------
1756 Any memory access must be done through a pointer value associated with
1757 an address range of the memory access, otherwise the behavior is
1758 undefined. Pointer values are associated with address ranges according
1759 to the following rules:
1761 - A pointer value is associated with the addresses associated with any
1762 value it is *based* on.
1763 - An address of a global variable is associated with the address range
1764 of the variable's storage.
1765 - The result value of an allocation instruction is associated with the
1766 address range of the allocated storage.
1767 - A null pointer in the default address-space is associated with no
1769 - An integer constant other than zero or a pointer value returned from
1770 a function not defined within LLVM may be associated with address
1771 ranges allocated through mechanisms other than those provided by
1772 LLVM. Such ranges shall not overlap with any ranges of addresses
1773 allocated by mechanisms provided by LLVM.
1775 A pointer value is *based* on another pointer value according to the
1778 - A pointer value formed from a ``getelementptr`` operation is *based*
1779 on the first value operand of the ``getelementptr``.
1780 - The result value of a ``bitcast`` is *based* on the operand of the
1782 - A pointer value formed by an ``inttoptr`` is *based* on all pointer
1783 values that contribute (directly or indirectly) to the computation of
1784 the pointer's value.
1785 - The "*based* on" relationship is transitive.
1787 Note that this definition of *"based"* is intentionally similar to the
1788 definition of *"based"* in C99, though it is slightly weaker.
1790 LLVM IR does not associate types with memory. The result type of a
1791 ``load`` merely indicates the size and alignment of the memory from
1792 which to load, as well as the interpretation of the value. The first
1793 operand type of a ``store`` similarly only indicates the size and
1794 alignment of the store.
1796 Consequently, type-based alias analysis, aka TBAA, aka
1797 ``-fstrict-aliasing``, is not applicable to general unadorned LLVM IR.
1798 :ref:`Metadata <metadata>` may be used to encode additional information
1799 which specialized optimization passes may use to implement type-based
1804 Volatile Memory Accesses
1805 ------------------------
1807 Certain memory accesses, such as :ref:`load <i_load>`'s,
1808 :ref:`store <i_store>`'s, and :ref:`llvm.memcpy <int_memcpy>`'s may be
1809 marked ``volatile``. The optimizers must not change the number of
1810 volatile operations or change their order of execution relative to other
1811 volatile operations. The optimizers *may* change the order of volatile
1812 operations relative to non-volatile operations. This is not Java's
1813 "volatile" and has no cross-thread synchronization behavior.
1815 IR-level volatile loads and stores cannot safely be optimized into
1816 llvm.memcpy or llvm.memmove intrinsics even when those intrinsics are
1817 flagged volatile. Likewise, the backend should never split or merge
1818 target-legal volatile load/store instructions.
1820 .. admonition:: Rationale
1822 Platforms may rely on volatile loads and stores of natively supported
1823 data width to be executed as single instruction. For example, in C
1824 this holds for an l-value of volatile primitive type with native
1825 hardware support, but not necessarily for aggregate types. The
1826 frontend upholds these expectations, which are intentionally
1827 unspecified in the IR. The rules above ensure that IR transformations
1828 do not violate the frontend's contract with the language.
1832 Memory Model for Concurrent Operations
1833 --------------------------------------
1835 The LLVM IR does not define any way to start parallel threads of
1836 execution or to register signal handlers. Nonetheless, there are
1837 platform-specific ways to create them, and we define LLVM IR's behavior
1838 in their presence. This model is inspired by the C++0x memory model.
1840 For a more informal introduction to this model, see the :doc:`Atomics`.
1842 We define a *happens-before* partial order as the least partial order
1845 - Is a superset of single-thread program order, and
1846 - When a *synchronizes-with* ``b``, includes an edge from ``a`` to
1847 ``b``. *Synchronizes-with* pairs are introduced by platform-specific
1848 techniques, like pthread locks, thread creation, thread joining,
1849 etc., and by atomic instructions. (See also :ref:`Atomic Memory Ordering
1850 Constraints <ordering>`).
1852 Note that program order does not introduce *happens-before* edges
1853 between a thread and signals executing inside that thread.
1855 Every (defined) read operation (load instructions, memcpy, atomic
1856 loads/read-modify-writes, etc.) R reads a series of bytes written by
1857 (defined) write operations (store instructions, atomic
1858 stores/read-modify-writes, memcpy, etc.). For the purposes of this
1859 section, initialized globals are considered to have a write of the
1860 initializer which is atomic and happens before any other read or write
1861 of the memory in question. For each byte of a read R, R\ :sub:`byte`
1862 may see any write to the same byte, except:
1864 - If write\ :sub:`1` happens before write\ :sub:`2`, and
1865 write\ :sub:`2` happens before R\ :sub:`byte`, then
1866 R\ :sub:`byte` does not see write\ :sub:`1`.
1867 - If R\ :sub:`byte` happens before write\ :sub:`3`, then
1868 R\ :sub:`byte` does not see write\ :sub:`3`.
1870 Given that definition, R\ :sub:`byte` is defined as follows:
1872 - If R is volatile, the result is target-dependent. (Volatile is
1873 supposed to give guarantees which can support ``sig_atomic_t`` in
1874 C/C++, and may be used for accesses to addresses that do not behave
1875 like normal memory. It does not generally provide cross-thread
1877 - Otherwise, if there is no write to the same byte that happens before
1878 R\ :sub:`byte`, R\ :sub:`byte` returns ``undef`` for that byte.
1879 - Otherwise, if R\ :sub:`byte` may see exactly one write,
1880 R\ :sub:`byte` returns the value written by that write.
1881 - Otherwise, if R is atomic, and all the writes R\ :sub:`byte` may
1882 see are atomic, it chooses one of the values written. See the :ref:`Atomic
1883 Memory Ordering Constraints <ordering>` section for additional
1884 constraints on how the choice is made.
1885 - Otherwise R\ :sub:`byte` returns ``undef``.
1887 R returns the value composed of the series of bytes it read. This
1888 implies that some bytes within the value may be ``undef`` **without**
1889 the entire value being ``undef``. Note that this only defines the
1890 semantics of the operation; it doesn't mean that targets will emit more
1891 than one instruction to read the series of bytes.
1893 Note that in cases where none of the atomic intrinsics are used, this
1894 model places only one restriction on IR transformations on top of what
1895 is required for single-threaded execution: introducing a store to a byte
1896 which might not otherwise be stored is not allowed in general.
1897 (Specifically, in the case where another thread might write to and read
1898 from an address, introducing a store can change a load that may see
1899 exactly one write into a load that may see multiple writes.)
1903 Atomic Memory Ordering Constraints
1904 ----------------------------------
1906 Atomic instructions (:ref:`cmpxchg <i_cmpxchg>`,
1907 :ref:`atomicrmw <i_atomicrmw>`, :ref:`fence <i_fence>`,
1908 :ref:`atomic load <i_load>`, and :ref:`atomic store <i_store>`) take
1909 ordering parameters that determine which other atomic instructions on
1910 the same address they *synchronize with*. These semantics are borrowed
1911 from Java and C++0x, but are somewhat more colloquial. If these
1912 descriptions aren't precise enough, check those specs (see spec
1913 references in the :doc:`atomics guide <Atomics>`).
1914 :ref:`fence <i_fence>` instructions treat these orderings somewhat
1915 differently since they don't take an address. See that instruction's
1916 documentation for details.
1918 For a simpler introduction to the ordering constraints, see the
1922 The set of values that can be read is governed by the happens-before
1923 partial order. A value cannot be read unless some operation wrote
1924 it. This is intended to provide a guarantee strong enough to model
1925 Java's non-volatile shared variables. This ordering cannot be
1926 specified for read-modify-write operations; it is not strong enough
1927 to make them atomic in any interesting way.
1929 In addition to the guarantees of ``unordered``, there is a single
1930 total order for modifications by ``monotonic`` operations on each
1931 address. All modification orders must be compatible with the
1932 happens-before order. There is no guarantee that the modification
1933 orders can be combined to a global total order for the whole program
1934 (and this often will not be possible). The read in an atomic
1935 read-modify-write operation (:ref:`cmpxchg <i_cmpxchg>` and
1936 :ref:`atomicrmw <i_atomicrmw>`) reads the value in the modification
1937 order immediately before the value it writes. If one atomic read
1938 happens before another atomic read of the same address, the later
1939 read must see the same value or a later value in the address's
1940 modification order. This disallows reordering of ``monotonic`` (or
1941 stronger) operations on the same address. If an address is written
1942 ``monotonic``-ally by one thread, and other threads ``monotonic``-ally
1943 read that address repeatedly, the other threads must eventually see
1944 the write. This corresponds to the C++0x/C1x
1945 ``memory_order_relaxed``.
1947 In addition to the guarantees of ``monotonic``, a
1948 *synchronizes-with* edge may be formed with a ``release`` operation.
1949 This is intended to model C++'s ``memory_order_acquire``.
1951 In addition to the guarantees of ``monotonic``, if this operation
1952 writes a value which is subsequently read by an ``acquire``
1953 operation, it *synchronizes-with* that operation. (This isn't a
1954 complete description; see the C++0x definition of a release
1955 sequence.) This corresponds to the C++0x/C1x
1956 ``memory_order_release``.
1957 ``acq_rel`` (acquire+release)
1958 Acts as both an ``acquire`` and ``release`` operation on its
1959 address. This corresponds to the C++0x/C1x ``memory_order_acq_rel``.
1960 ``seq_cst`` (sequentially consistent)
1961 In addition to the guarantees of ``acq_rel`` (``acquire`` for an
1962 operation that only reads, ``release`` for an operation that only
1963 writes), there is a global total order on all
1964 sequentially-consistent operations on all addresses, which is
1965 consistent with the *happens-before* partial order and with the
1966 modification orders of all the affected addresses. Each
1967 sequentially-consistent read sees the last preceding write to the
1968 same address in this global order. This corresponds to the C++0x/C1x
1969 ``memory_order_seq_cst`` and Java volatile.
1973 If an atomic operation is marked ``singlethread``, it only *synchronizes
1974 with* or participates in modification and seq\_cst total orderings with
1975 other operations running in the same thread (for example, in signal
1983 LLVM IR floating-point binary ops (:ref:`fadd <i_fadd>`,
1984 :ref:`fsub <i_fsub>`, :ref:`fmul <i_fmul>`, :ref:`fdiv <i_fdiv>`,
1985 :ref:`frem <i_frem>`, :ref:`fcmp <i_fcmp>`) have the following flags that can
1986 be set to enable otherwise unsafe floating point operations
1989 No NaNs - Allow optimizations to assume the arguments and result are not
1990 NaN. Such optimizations are required to retain defined behavior over
1991 NaNs, but the value of the result is undefined.
1994 No Infs - Allow optimizations to assume the arguments and result are not
1995 +/-Inf. Such optimizations are required to retain defined behavior over
1996 +/-Inf, but the value of the result is undefined.
1999 No Signed Zeros - Allow optimizations to treat the sign of a zero
2000 argument or result as insignificant.
2003 Allow Reciprocal - Allow optimizations to use the reciprocal of an
2004 argument rather than perform division.
2007 Fast - Allow algebraically equivalent transformations that may
2008 dramatically change results in floating point (e.g. reassociate). This
2009 flag implies all the others.
2013 Use-list Order Directives
2014 -------------------------
2016 Use-list directives encode the in-memory order of each use-list, allowing the
2017 order to be recreated. ``<order-indexes>`` is a comma-separated list of
2018 indexes that are assigned to the referenced value's uses. The referenced
2019 value's use-list is immediately sorted by these indexes.
2021 Use-list directives may appear at function scope or global scope. They are not
2022 instructions, and have no effect on the semantics of the IR. When they're at
2023 function scope, they must appear after the terminator of the final basic block.
2025 If basic blocks have their address taken via ``blockaddress()`` expressions,
2026 ``uselistorder_bb`` can be used to reorder their use-lists from outside their
2033 uselistorder <ty> <value>, { <order-indexes> }
2034 uselistorder_bb @function, %block { <order-indexes> }
2040 define void @foo(i32 %arg1, i32 %arg2) {
2042 ; ... instructions ...
2044 ; ... instructions ...
2046 ; At function scope.
2047 uselistorder i32 %arg1, { 1, 0, 2 }
2048 uselistorder label %bb, { 1, 0 }
2052 uselistorder i32* @global, { 1, 2, 0 }
2053 uselistorder i32 7, { 1, 0 }
2054 uselistorder i32 (i32) @bar, { 1, 0 }
2055 uselistorder_bb @foo, %bb, { 5, 1, 3, 2, 0, 4 }
2062 The LLVM type system is one of the most important features of the
2063 intermediate representation. Being typed enables a number of
2064 optimizations to be performed on the intermediate representation
2065 directly, without having to do extra analyses on the side before the
2066 transformation. A strong type system makes it easier to read the
2067 generated code and enables novel analyses and transformations that are
2068 not feasible to perform on normal three address code representations.
2078 The void type does not represent any value and has no size.
2096 The function type can be thought of as a function signature. It consists of a
2097 return type and a list of formal parameter types. The return type of a function
2098 type is a void type or first class type --- except for :ref:`label <t_label>`
2099 and :ref:`metadata <t_metadata>` types.
2105 <returntype> (<parameter list>)
2107 ...where '``<parameter list>``' is a comma-separated list of type
2108 specifiers. Optionally, the parameter list may include a type ``...``, which
2109 indicates that the function takes a variable number of arguments. Variable
2110 argument functions can access their arguments with the :ref:`variable argument
2111 handling intrinsic <int_varargs>` functions. '``<returntype>``' is any type
2112 except :ref:`label <t_label>` and :ref:`metadata <t_metadata>`.
2116 +---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2117 | ``i32 (i32)`` | function taking an ``i32``, returning an ``i32`` |
2118 +---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2119 | ``float (i16, i32 *) *`` | :ref:`Pointer <t_pointer>` to a function that takes an ``i16`` and a :ref:`pointer <t_pointer>` to ``i32``, returning ``float``. |
2120 +---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2121 | ``i32 (i8*, ...)`` | A vararg function that takes at least one :ref:`pointer <t_pointer>` to ``i8`` (char in C), which returns an integer. This is the signature for ``printf`` in LLVM. |
2122 +---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2123 | ``{i32, i32} (i32)`` | A function taking an ``i32``, returning a :ref:`structure <t_struct>` containing two ``i32`` values |
2124 +---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2131 The :ref:`first class <t_firstclass>` types are perhaps the most important.
2132 Values of these types are the only ones which can be produced by
2140 These are the types that are valid in registers from CodeGen's perspective.
2149 The integer type is a very simple type that simply specifies an
2150 arbitrary bit width for the integer type desired. Any bit width from 1
2151 bit to 2\ :sup:`23`\ -1 (about 8 million) can be specified.
2159 The number of bits the integer will occupy is specified by the ``N``
2165 +----------------+------------------------------------------------+
2166 | ``i1`` | a single-bit integer. |
2167 +----------------+------------------------------------------------+
2168 | ``i32`` | a 32-bit integer. |
2169 +----------------+------------------------------------------------+
2170 | ``i1942652`` | a really big integer of over 1 million bits. |
2171 +----------------+------------------------------------------------+
2175 Floating Point Types
2176 """"""""""""""""""""
2185 - 16-bit floating point value
2188 - 32-bit floating point value
2191 - 64-bit floating point value
2194 - 128-bit floating point value (112-bit mantissa)
2197 - 80-bit floating point value (X87)
2200 - 128-bit floating point value (two 64-bits)
2207 The x86_mmx type represents a value held in an MMX register on an x86
2208 machine. The operations allowed on it are quite limited: parameters and
2209 return values, load and store, and bitcast. User-specified MMX
2210 instructions are represented as intrinsic or asm calls with arguments
2211 and/or results of this type. There are no arrays, vectors or constants
2228 The pointer type is used to specify memory locations. Pointers are
2229 commonly used to reference objects in memory.
2231 Pointer types may have an optional address space attribute defining the
2232 numbered address space where the pointed-to object resides. The default
2233 address space is number zero. The semantics of non-zero address spaces
2234 are target-specific.
2236 Note that LLVM does not permit pointers to void (``void*``) nor does it
2237 permit pointers to labels (``label*``). Use ``i8*`` instead.
2247 +-------------------------+--------------------------------------------------------------------------------------------------------------+
2248 | ``[4 x i32]*`` | A :ref:`pointer <t_pointer>` to :ref:`array <t_array>` of four ``i32`` values. |
2249 +-------------------------+--------------------------------------------------------------------------------------------------------------+
2250 | ``i32 (i32*) *`` | A :ref:`pointer <t_pointer>` to a :ref:`function <t_function>` that takes an ``i32*``, returning an ``i32``. |
2251 +-------------------------+--------------------------------------------------------------------------------------------------------------+
2252 | ``i32 addrspace(5)*`` | A :ref:`pointer <t_pointer>` to an ``i32`` value that resides in address space #5. |
2253 +-------------------------+--------------------------------------------------------------------------------------------------------------+
2262 A vector type is a simple derived type that represents a vector of
2263 elements. Vector types are used when multiple primitive data are
2264 operated in parallel using a single instruction (SIMD). A vector type
2265 requires a size (number of elements) and an underlying primitive data
2266 type. Vector types are considered :ref:`first class <t_firstclass>`.
2272 < <# elements> x <elementtype> >
2274 The number of elements is a constant integer value larger than 0;
2275 elementtype may be any integer, floating point or pointer type. Vectors
2276 of size zero are not allowed.
2280 +-------------------+--------------------------------------------------+
2281 | ``<4 x i32>`` | Vector of 4 32-bit integer values. |
2282 +-------------------+--------------------------------------------------+
2283 | ``<8 x float>`` | Vector of 8 32-bit floating-point values. |
2284 +-------------------+--------------------------------------------------+
2285 | ``<2 x i64>`` | Vector of 2 64-bit integer values. |
2286 +-------------------+--------------------------------------------------+
2287 | ``<4 x i64*>`` | Vector of 4 pointers to 64-bit integer values. |
2288 +-------------------+--------------------------------------------------+
2297 The label type represents code labels.
2312 The token type is used when a value is associated with an instruction
2313 but all uses of the value must not attempt to introspect or obscure it.
2314 As such, it is not appropriate to have a :ref:`phi <i_phi>` or
2315 :ref:`select <i_select>` of type token.
2332 The metadata type represents embedded metadata. No derived types may be
2333 created from metadata except for :ref:`function <t_function>` arguments.
2346 Aggregate Types are a subset of derived types that can contain multiple
2347 member types. :ref:`Arrays <t_array>` and :ref:`structs <t_struct>` are
2348 aggregate types. :ref:`Vectors <t_vector>` are not considered to be
2358 The array type is a very simple derived type that arranges elements
2359 sequentially in memory. The array type requires a size (number of
2360 elements) and an underlying data type.
2366 [<# elements> x <elementtype>]
2368 The number of elements is a constant integer value; ``elementtype`` may
2369 be any type with a size.
2373 +------------------+--------------------------------------+
2374 | ``[40 x i32]`` | Array of 40 32-bit integer values. |
2375 +------------------+--------------------------------------+
2376 | ``[41 x i32]`` | Array of 41 32-bit integer values. |
2377 +------------------+--------------------------------------+
2378 | ``[4 x i8]`` | Array of 4 8-bit integer values. |
2379 +------------------+--------------------------------------+
2381 Here are some examples of multidimensional arrays:
2383 +-----------------------------+----------------------------------------------------------+
2384 | ``[3 x [4 x i32]]`` | 3x4 array of 32-bit integer values. |
2385 +-----------------------------+----------------------------------------------------------+
2386 | ``[12 x [10 x float]]`` | 12x10 array of single precision floating point values. |
2387 +-----------------------------+----------------------------------------------------------+
2388 | ``[2 x [3 x [4 x i16]]]`` | 2x3x4 array of 16-bit integer values. |
2389 +-----------------------------+----------------------------------------------------------+
2391 There is no restriction on indexing beyond the end of the array implied
2392 by a static type (though there are restrictions on indexing beyond the
2393 bounds of an allocated object in some cases). This means that
2394 single-dimension 'variable sized array' addressing can be implemented in
2395 LLVM with a zero length array type. An implementation of 'pascal style
2396 arrays' in LLVM could use the type "``{ i32, [0 x float]}``", for
2406 The structure type is used to represent a collection of data members
2407 together in memory. The elements of a structure may be any type that has
2410 Structures in memory are accessed using '``load``' and '``store``' by
2411 getting a pointer to a field with the '``getelementptr``' instruction.
2412 Structures in registers are accessed using the '``extractvalue``' and
2413 '``insertvalue``' instructions.
2415 Structures may optionally be "packed" structures, which indicate that
2416 the alignment of the struct is one byte, and that there is no padding
2417 between the elements. In non-packed structs, padding between field types
2418 is inserted as defined by the DataLayout string in the module, which is
2419 required to match what the underlying code generator expects.
2421 Structures can either be "literal" or "identified". A literal structure
2422 is defined inline with other types (e.g. ``{i32, i32}*``) whereas
2423 identified types are always defined at the top level with a name.
2424 Literal types are uniqued by their contents and can never be recursive
2425 or opaque since there is no way to write one. Identified types can be
2426 recursive, can be opaqued, and are never uniqued.
2432 %T1 = type { <type list> } ; Identified normal struct type
2433 %T2 = type <{ <type list> }> ; Identified packed struct type
2437 +------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2438 | ``{ i32, i32, i32 }`` | A triple of three ``i32`` values |
2439 +------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2440 | ``{ float, i32 (i32) * }`` | A pair, where the first element is a ``float`` and the second element is a :ref:`pointer <t_pointer>` to a :ref:`function <t_function>` that takes an ``i32``, returning an ``i32``. |
2441 +------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2442 | ``<{ i8, i32 }>`` | A packed struct known to be 5 bytes in size. |
2443 +------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
2447 Opaque Structure Types
2448 """"""""""""""""""""""
2452 Opaque structure types are used to represent named structure types that
2453 do not have a body specified. This corresponds (for example) to the C
2454 notion of a forward declared structure.
2465 +--------------+-------------------+
2466 | ``opaque`` | An opaque type. |
2467 +--------------+-------------------+
2474 LLVM has several different basic types of constants. This section
2475 describes them all and their syntax.
2480 **Boolean constants**
2481 The two strings '``true``' and '``false``' are both valid constants
2483 **Integer constants**
2484 Standard integers (such as '4') are constants of the
2485 :ref:`integer <t_integer>` type. Negative numbers may be used with
2487 **Floating point constants**
2488 Floating point constants use standard decimal notation (e.g.
2489 123.421), exponential notation (e.g. 1.23421e+2), or a more precise
2490 hexadecimal notation (see below). The assembler requires the exact
2491 decimal value of a floating-point constant. For example, the
2492 assembler accepts 1.25 but rejects 1.3 because 1.3 is a repeating
2493 decimal in binary. Floating point constants must have a :ref:`floating
2494 point <t_floating>` type.
2495 **Null pointer constants**
2496 The identifier '``null``' is recognized as a null pointer constant
2497 and must be of :ref:`pointer type <t_pointer>`.
2499 The identifier '``none``' is recognized as an empty token constant
2500 and must be of :ref:`token type <t_token>`.
2502 The one non-intuitive notation for constants is the hexadecimal form of
2503 floating point constants. For example, the form
2504 '``double 0x432ff973cafa8000``' is equivalent to (but harder to read
2505 than) '``double 4.5e+15``'. The only time hexadecimal floating point
2506 constants are required (and the only time that they are generated by the
2507 disassembler) is when a floating point constant must be emitted but it
2508 cannot be represented as a decimal floating point number in a reasonable
2509 number of digits. For example, NaN's, infinities, and other special
2510 values are represented in their IEEE hexadecimal format so that assembly
2511 and disassembly do not cause any bits to change in the constants.
2513 When using the hexadecimal form, constants of types half, float, and
2514 double are represented using the 16-digit form shown above (which
2515 matches the IEEE754 representation for double); half and float values
2516 must, however, be exactly representable as IEEE 754 half and single
2517 precision, respectively. Hexadecimal format is always used for long
2518 double, and there are three forms of long double. The 80-bit format used
2519 by x86 is represented as ``0xK`` followed by 20 hexadecimal digits. The
2520 128-bit format used by PowerPC (two adjacent doubles) is represented by
2521 ``0xM`` followed by 32 hexadecimal digits. The IEEE 128-bit format is
2522 represented by ``0xL`` followed by 32 hexadecimal digits. Long doubles
2523 will only work if they match the long double format on your target.
2524 The IEEE 16-bit format (half precision) is represented by ``0xH``
2525 followed by 4 hexadecimal digits. All hexadecimal formats are big-endian
2526 (sign bit at the left).
2528 There are no constants of type x86_mmx.
2530 .. _complexconstants:
2535 Complex constants are a (potentially recursive) combination of simple
2536 constants and smaller complex constants.
2538 **Structure constants**
2539 Structure constants are represented with notation similar to
2540 structure type definitions (a comma separated list of elements,
2541 surrounded by braces (``{}``)). For example:
2542 "``{ i32 4, float 17.0, i32* @G }``", where "``@G``" is declared as
2543 "``@G = external global i32``". Structure constants must have
2544 :ref:`structure type <t_struct>`, and the number and types of elements
2545 must match those specified by the type.
2547 Array constants are represented with notation similar to array type
2548 definitions (a comma separated list of elements, surrounded by
2549 square brackets (``[]``)). For example:
2550 "``[ i32 42, i32 11, i32 74 ]``". Array constants must have
2551 :ref:`array type <t_array>`, and the number and types of elements must
2552 match those specified by the type. As a special case, character array
2553 constants may also be represented as a double-quoted string using the ``c``
2554 prefix. For example: "``c"Hello World\0A\00"``".
2555 **Vector constants**
2556 Vector constants are represented with notation similar to vector
2557 type definitions (a comma separated list of elements, surrounded by
2558 less-than/greater-than's (``<>``)). For example:
2559 "``< i32 42, i32 11, i32 74, i32 100 >``". Vector constants
2560 must have :ref:`vector type <t_vector>`, and the number and types of
2561 elements must match those specified by the type.
2562 **Zero initialization**
2563 The string '``zeroinitializer``' can be used to zero initialize a
2564 value to zero of *any* type, including scalar and
2565 :ref:`aggregate <t_aggregate>` types. This is often used to avoid
2566 having to print large zero initializers (e.g. for large arrays) and
2567 is always exactly equivalent to using explicit zero initializers.
2569 A metadata node is a constant tuple without types. For example:
2570 "``!{!0, !{!2, !0}, !"test"}``". Metadata can reference constant values,
2571 for example: "``!{!0, i32 0, i8* @global, i64 (i64)* @function, !"str"}``".
2572 Unlike other typed constants that are meant to be interpreted as part of
2573 the instruction stream, metadata is a place to attach additional
2574 information such as debug info.
2576 Global Variable and Function Addresses
2577 --------------------------------------
2579 The addresses of :ref:`global variables <globalvars>` and
2580 :ref:`functions <functionstructure>` are always implicitly valid
2581 (link-time) constants. These constants are explicitly referenced when
2582 the :ref:`identifier for the global <identifiers>` is used and always have
2583 :ref:`pointer <t_pointer>` type. For example, the following is a legal LLVM
2586 .. code-block:: llvm
2590 @Z = global [2 x i32*] [ i32* @X, i32* @Y ]
2597 The string '``undef``' can be used anywhere a constant is expected, and
2598 indicates that the user of the value may receive an unspecified
2599 bit-pattern. Undefined values may be of any type (other than '``label``'
2600 or '``void``') and be used anywhere a constant is permitted.
2602 Undefined values are useful because they indicate to the compiler that
2603 the program is well defined no matter what value is used. This gives the
2604 compiler more freedom to optimize. Here are some examples of
2605 (potentially surprising) transformations that are valid (in pseudo IR):
2607 .. code-block:: llvm
2617 This is safe because all of the output bits are affected by the undef
2618 bits. Any output bit can have a zero or one depending on the input bits.
2620 .. code-block:: llvm
2631 These logical operations have bits that are not always affected by the
2632 input. For example, if ``%X`` has a zero bit, then the output of the
2633 '``and``' operation will always be a zero for that bit, no matter what
2634 the corresponding bit from the '``undef``' is. As such, it is unsafe to
2635 optimize or assume that the result of the '``and``' is '``undef``'.
2636 However, it is safe to assume that all bits of the '``undef``' could be
2637 0, and optimize the '``and``' to 0. Likewise, it is safe to assume that
2638 all the bits of the '``undef``' operand to the '``or``' could be set,
2639 allowing the '``or``' to be folded to -1.
2641 .. code-block:: llvm
2643 %A = select undef, %X, %Y
2644 %B = select undef, 42, %Y
2645 %C = select %X, %Y, undef
2655 This set of examples shows that undefined '``select``' (and conditional
2656 branch) conditions can go *either way*, but they have to come from one
2657 of the two operands. In the ``%A`` example, if ``%X`` and ``%Y`` were
2658 both known to have a clear low bit, then ``%A`` would have to have a
2659 cleared low bit. However, in the ``%C`` example, the optimizer is
2660 allowed to assume that the '``undef``' operand could be the same as
2661 ``%Y``, allowing the whole '``select``' to be eliminated.
2663 .. code-block:: llvm
2665 %A = xor undef, undef
2682 This example points out that two '``undef``' operands are not
2683 necessarily the same. This can be surprising to people (and also matches
2684 C semantics) where they assume that "``X^X``" is always zero, even if
2685 ``X`` is undefined. This isn't true for a number of reasons, but the
2686 short answer is that an '``undef``' "variable" can arbitrarily change
2687 its value over its "live range". This is true because the variable
2688 doesn't actually *have a live range*. Instead, the value is logically
2689 read from arbitrary registers that happen to be around when needed, so
2690 the value is not necessarily consistent over time. In fact, ``%A`` and
2691 ``%C`` need to have the same semantics or the core LLVM "replace all
2692 uses with" concept would not hold.
2694 .. code-block:: llvm
2702 These examples show the crucial difference between an *undefined value*
2703 and *undefined behavior*. An undefined value (like '``undef``') is
2704 allowed to have an arbitrary bit-pattern. This means that the ``%A``
2705 operation can be constant folded to '``undef``', because the '``undef``'
2706 could be an SNaN, and ``fdiv`` is not (currently) defined on SNaN's.
2707 However, in the second example, we can make a more aggressive
2708 assumption: because the ``undef`` is allowed to be an arbitrary value,
2709 we are allowed to assume that it could be zero. Since a divide by zero
2710 has *undefined behavior*, we are allowed to assume that the operation
2711 does not execute at all. This allows us to delete the divide and all
2712 code after it. Because the undefined operation "can't happen", the
2713 optimizer can assume that it occurs in dead code.
2715 .. code-block:: llvm
2717 a: store undef -> %X
2718 b: store %X -> undef
2723 These examples reiterate the ``fdiv`` example: a store *of* an undefined
2724 value can be assumed to not have any effect; we can assume that the
2725 value is overwritten with bits that happen to match what was already
2726 there. However, a store *to* an undefined location could clobber
2727 arbitrary memory, therefore, it has undefined behavior.
2734 Poison values are similar to :ref:`undef values <undefvalues>`, however
2735 they also represent the fact that an instruction or constant expression
2736 that cannot evoke side effects has nevertheless detected a condition
2737 that results in undefined behavior.
2739 There is currently no way of representing a poison value in the IR; they
2740 only exist when produced by operations such as :ref:`add <i_add>` with
2743 Poison value behavior is defined in terms of value *dependence*:
2745 - Values other than :ref:`phi <i_phi>` nodes depend on their operands.
2746 - :ref:`Phi <i_phi>` nodes depend on the operand corresponding to
2747 their dynamic predecessor basic block.
2748 - Function arguments depend on the corresponding actual argument values
2749 in the dynamic callers of their functions.
2750 - :ref:`Call <i_call>` instructions depend on the :ref:`ret <i_ret>`
2751 instructions that dynamically transfer control back to them.
2752 - :ref:`Invoke <i_invoke>` instructions depend on the
2753 :ref:`ret <i_ret>`, :ref:`resume <i_resume>`, or exception-throwing
2754 call instructions that dynamically transfer control back to them.
2755 - Non-volatile loads and stores depend on the most recent stores to all
2756 of the referenced memory addresses, following the order in the IR
2757 (including loads and stores implied by intrinsics such as
2758 :ref:`@llvm.memcpy <int_memcpy>`.)
2759 - An instruction with externally visible side effects depends on the
2760 most recent preceding instruction with externally visible side
2761 effects, following the order in the IR. (This includes :ref:`volatile
2762 operations <volatile>`.)
2763 - An instruction *control-depends* on a :ref:`terminator
2764 instruction <terminators>` if the terminator instruction has
2765 multiple successors and the instruction is always executed when
2766 control transfers to one of the successors, and may not be executed
2767 when control is transferred to another.
2768 - Additionally, an instruction also *control-depends* on a terminator
2769 instruction if the set of instructions it otherwise depends on would
2770 be different if the terminator had transferred control to a different
2772 - Dependence is transitive.
2774 Poison values have the same behavior as :ref:`undef values <undefvalues>`,
2775 with the additional effect that any instruction that has a *dependence*
2776 on a poison value has undefined behavior.
2778 Here are some examples:
2780 .. code-block:: llvm
2783 %poison = sub nuw i32 0, 1 ; Results in a poison value.
2784 %still_poison = and i32 %poison, 0 ; 0, but also poison.
2785 %poison_yet_again = getelementptr i32, i32* @h, i32 %still_poison
2786 store i32 0, i32* %poison_yet_again ; memory at @h[0] is poisoned
2788 store i32 %poison, i32* @g ; Poison value stored to memory.
2789 %poison2 = load i32, i32* @g ; Poison value loaded back from memory.
2791 store volatile i32 %poison, i32* @g ; External observation; undefined behavior.
2793 %narrowaddr = bitcast i32* @g to i16*
2794 %wideaddr = bitcast i32* @g to i64*
2795 %poison3 = load i16, i16* %narrowaddr ; Returns a poison value.
2796 %poison4 = load i64, i64* %wideaddr ; Returns a poison value.
2798 %cmp = icmp slt i32 %poison, 0 ; Returns a poison value.
2799 br i1 %cmp, label %true, label %end ; Branch to either destination.
2802 store volatile i32 0, i32* @g ; This is control-dependent on %cmp, so
2803 ; it has undefined behavior.
2807 %p = phi i32 [ 0, %entry ], [ 1, %true ]
2808 ; Both edges into this PHI are
2809 ; control-dependent on %cmp, so this
2810 ; always results in a poison value.
2812 store volatile i32 0, i32* @g ; This would depend on the store in %true
2813 ; if %cmp is true, or the store in %entry
2814 ; otherwise, so this is undefined behavior.
2816 br i1 %cmp, label %second_true, label %second_end
2817 ; The same branch again, but this time the
2818 ; true block doesn't have side effects.
2825 store volatile i32 0, i32* @g ; This time, the instruction always depends
2826 ; on the store in %end. Also, it is
2827 ; control-equivalent to %end, so this is
2828 ; well-defined (ignoring earlier undefined
2829 ; behavior in this example).
2833 Addresses of Basic Blocks
2834 -------------------------
2836 ``blockaddress(@function, %block)``
2838 The '``blockaddress``' constant computes the address of the specified
2839 basic block in the specified function, and always has an ``i8*`` type.
2840 Taking the address of the entry block is illegal.
2842 This value only has defined behavior when used as an operand to the
2843 ':ref:`indirectbr <i_indirectbr>`' instruction, or for comparisons
2844 against null. Pointer equality tests between labels addresses results in
2845 undefined behavior --- though, again, comparison against null is ok, and
2846 no label is equal to the null pointer. This may be passed around as an
2847 opaque pointer sized value as long as the bits are not inspected. This
2848 allows ``ptrtoint`` and arithmetic to be performed on these values so
2849 long as the original value is reconstituted before the ``indirectbr``
2852 Finally, some targets may provide defined semantics when using the value
2853 as the operand to an inline assembly, but that is target specific.
2857 Constant Expressions
2858 --------------------
2860 Constant expressions are used to allow expressions involving other
2861 constants to be used as constants. Constant expressions may be of any
2862 :ref:`first class <t_firstclass>` type and may involve any LLVM operation
2863 that does not have side effects (e.g. load and call are not supported).
2864 The following is the syntax for constant expressions:
2866 ``trunc (CST to TYPE)``
2867 Truncate a constant to another type. The bit size of CST must be
2868 larger than the bit size of TYPE. Both types must be integers.
2869 ``zext (CST to TYPE)``
2870 Zero extend a constant to another type. The bit size of CST must be
2871 smaller than the bit size of TYPE. Both types must be integers.
2872 ``sext (CST to TYPE)``
2873 Sign extend a constant to another type. The bit size of CST must be
2874 smaller than the bit size of TYPE. Both types must be integers.
2875 ``fptrunc (CST to TYPE)``
2876 Truncate a floating point constant to another floating point type.
2877 The size of CST must be larger than the size of TYPE. Both types
2878 must be floating point.
2879 ``fpext (CST to TYPE)``
2880 Floating point extend a constant to another type. The size of CST
2881 must be smaller or equal to the size of TYPE. Both types must be
2883 ``fptoui (CST to TYPE)``
2884 Convert a floating point constant to the corresponding unsigned
2885 integer constant. TYPE must be a scalar or vector integer type. CST
2886 must be of scalar or vector floating point type. Both CST and TYPE
2887 must be scalars, or vectors of the same number of elements. If the
2888 value won't fit in the integer type, the results are undefined.
2889 ``fptosi (CST to TYPE)``
2890 Convert a floating point constant to the corresponding signed
2891 integer constant. TYPE must be a scalar or vector integer type. CST
2892 must be of scalar or vector floating point type. Both CST and TYPE
2893 must be scalars, or vectors of the same number of elements. If the
2894 value won't fit in the integer type, the results are undefined.
2895 ``uitofp (CST to TYPE)``
2896 Convert an unsigned integer constant to the corresponding floating
2897 point constant. TYPE must be a scalar or vector floating point type.
2898 CST must be of scalar or vector integer type. Both CST and TYPE must
2899 be scalars, or vectors of the same number of elements. If the value
2900 won't fit in the floating point type, the results are undefined.
2901 ``sitofp (CST to TYPE)``
2902 Convert a signed integer constant to the corresponding floating
2903 point constant. TYPE must be a scalar or vector floating point type.
2904 CST must be of scalar or vector integer type. Both CST and TYPE must
2905 be scalars, or vectors of the same number of elements. If the value
2906 won't fit in the floating point type, the results are undefined.
2907 ``ptrtoint (CST to TYPE)``
2908 Convert a pointer typed constant to the corresponding integer
2909 constant. ``TYPE`` must be an integer type. ``CST`` must be of
2910 pointer type. The ``CST`` value is zero extended, truncated, or
2911 unchanged to make it fit in ``TYPE``.
2912 ``inttoptr (CST to TYPE)``
2913 Convert an integer constant to a pointer constant. TYPE must be a
2914 pointer type. CST must be of integer type. The CST value is zero
2915 extended, truncated, or unchanged to make it fit in a pointer size.
2916 This one is *really* dangerous!
2917 ``bitcast (CST to TYPE)``
2918 Convert a constant, CST, to another TYPE. The constraints of the
2919 operands are the same as those for the :ref:`bitcast
2920 instruction <i_bitcast>`.
2921 ``addrspacecast (CST to TYPE)``
2922 Convert a constant pointer or constant vector of pointer, CST, to another
2923 TYPE in a different address space. The constraints of the operands are the
2924 same as those for the :ref:`addrspacecast instruction <i_addrspacecast>`.
2925 ``getelementptr (TY, CSTPTR, IDX0, IDX1, ...)``, ``getelementptr inbounds (TY, CSTPTR, IDX0, IDX1, ...)``
2926 Perform the :ref:`getelementptr operation <i_getelementptr>` on
2927 constants. As with the :ref:`getelementptr <i_getelementptr>`
2928 instruction, the index list may have zero or more indexes, which are
2929 required to make sense for the type of "pointer to TY".
2930 ``select (COND, VAL1, VAL2)``
2931 Perform the :ref:`select operation <i_select>` on constants.
2932 ``icmp COND (VAL1, VAL2)``
2933 Performs the :ref:`icmp operation <i_icmp>` on constants.
2934 ``fcmp COND (VAL1, VAL2)``
2935 Performs the :ref:`fcmp operation <i_fcmp>` on constants.
2936 ``extractelement (VAL, IDX)``
2937 Perform the :ref:`extractelement operation <i_extractelement>` on
2939 ``insertelement (VAL, ELT, IDX)``
2940 Perform the :ref:`insertelement operation <i_insertelement>` on
2942 ``shufflevector (VEC1, VEC2, IDXMASK)``
2943 Perform the :ref:`shufflevector operation <i_shufflevector>` on
2945 ``extractvalue (VAL, IDX0, IDX1, ...)``
2946 Perform the :ref:`extractvalue operation <i_extractvalue>` on
2947 constants. The index list is interpreted in a similar manner as
2948 indices in a ':ref:`getelementptr <i_getelementptr>`' operation. At
2949 least one index value must be specified.
2950 ``insertvalue (VAL, ELT, IDX0, IDX1, ...)``
2951 Perform the :ref:`insertvalue operation <i_insertvalue>` on constants.
2952 The index list is interpreted in a similar manner as indices in a
2953 ':ref:`getelementptr <i_getelementptr>`' operation. At least one index
2954 value must be specified.
2955 ``OPCODE (LHS, RHS)``
2956 Perform the specified operation of the LHS and RHS constants. OPCODE
2957 may be any of the :ref:`binary <binaryops>` or :ref:`bitwise
2958 binary <bitwiseops>` operations. The constraints on operands are
2959 the same as those for the corresponding instruction (e.g. no bitwise
2960 operations on floating point values are allowed).
2967 Inline Assembler Expressions
2968 ----------------------------
2970 LLVM supports inline assembler expressions (as opposed to :ref:`Module-Level
2971 Inline Assembly <moduleasm>`) through the use of a special value. This value
2972 represents the inline assembler as a template string (containing the
2973 instructions to emit), a list of operand constraints (stored as a string), a
2974 flag that indicates whether or not the inline asm expression has side effects,
2975 and a flag indicating whether the function containing the asm needs to align its
2976 stack conservatively.
2978 The template string supports argument substitution of the operands using "``$``"
2979 followed by a number, to indicate substitution of the given register/memory
2980 location, as specified by the constraint string. "``${NUM:MODIFIER}``" may also
2981 be used, where ``MODIFIER`` is a target-specific annotation for how to print the
2982 operand (See :ref:`inline-asm-modifiers`).
2984 A literal "``$``" may be included by using "``$$``" in the template. To include
2985 other special characters into the output, the usual "``\XX``" escapes may be
2986 used, just as in other strings. Note that after template substitution, the
2987 resulting assembly string is parsed by LLVM's integrated assembler unless it is
2988 disabled -- even when emitting a ``.s`` file -- and thus must contain assembly
2989 syntax known to LLVM.
2991 LLVM's support for inline asm is modeled closely on the requirements of Clang's
2992 GCC-compatible inline-asm support. Thus, the feature-set and the constraint and
2993 modifier codes listed here are similar or identical to those in GCC's inline asm
2994 support. However, to be clear, the syntax of the template and constraint strings
2995 described here is *not* the same as the syntax accepted by GCC and Clang, and,
2996 while most constraint letters are passed through as-is by Clang, some get
2997 translated to other codes when converting from the C source to the LLVM
3000 An example inline assembler expression is:
3002 .. code-block:: llvm
3004 i32 (i32) asm "bswap $0", "=r,r"
3006 Inline assembler expressions may **only** be used as the callee operand
3007 of a :ref:`call <i_call>` or an :ref:`invoke <i_invoke>` instruction.
3008 Thus, typically we have:
3010 .. code-block:: llvm
3012 %X = call i32 asm "bswap $0", "=r,r"(i32 %Y)
3014 Inline asms with side effects not visible in the constraint list must be
3015 marked as having side effects. This is done through the use of the
3016 '``sideeffect``' keyword, like so:
3018 .. code-block:: llvm
3020 call void asm sideeffect "eieio", ""()
3022 In some cases inline asms will contain code that will not work unless
3023 the stack is aligned in some way, such as calls or SSE instructions on
3024 x86, yet will not contain code that does that alignment within the asm.
3025 The compiler should make conservative assumptions about what the asm
3026 might contain and should generate its usual stack alignment code in the
3027 prologue if the '``alignstack``' keyword is present:
3029 .. code-block:: llvm
3031 call void asm alignstack "eieio", ""()
3033 Inline asms also support using non-standard assembly dialects. The
3034 assumed dialect is ATT. When the '``inteldialect``' keyword is present,
3035 the inline asm is using the Intel dialect. Currently, ATT and Intel are
3036 the only supported dialects. An example is:
3038 .. code-block:: llvm
3040 call void asm inteldialect "eieio", ""()
3042 If multiple keywords appear the '``sideeffect``' keyword must come
3043 first, the '``alignstack``' keyword second and the '``inteldialect``'
3046 Inline Asm Constraint String
3047 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3049 The constraint list is a comma-separated string, each element containing one or
3050 more constraint codes.
3052 For each element in the constraint list an appropriate register or memory
3053 operand will be chosen, and it will be made available to assembly template
3054 string expansion as ``$0`` for the first constraint in the list, ``$1`` for the
3057 There are three different types of constraints, which are distinguished by a
3058 prefix symbol in front of the constraint code: Output, Input, and Clobber. The
3059 constraints must always be given in that order: outputs first, then inputs, then
3060 clobbers. They cannot be intermingled.
3062 There are also three different categories of constraint codes:
3064 - Register constraint. This is either a register class, or a fixed physical
3065 register. This kind of constraint will allocate a register, and if necessary,
3066 bitcast the argument or result to the appropriate type.
3067 - Memory constraint. This kind of constraint is for use with an instruction
3068 taking a memory operand. Different constraints allow for different addressing
3069 modes used by the target.
3070 - Immediate value constraint. This kind of constraint is for an integer or other
3071 immediate value which can be rendered directly into an instruction. The
3072 various target-specific constraints allow the selection of a value in the
3073 proper range for the instruction you wish to use it with.
3078 Output constraints are specified by an "``=``" prefix (e.g. "``=r``"). This
3079 indicates that the assembly will write to this operand, and the operand will
3080 then be made available as a return value of the ``asm`` expression. Output
3081 constraints do not consume an argument from the call instruction. (Except, see
3082 below about indirect outputs).
3084 Normally, it is expected that no output locations are written to by the assembly
3085 expression until *all* of the inputs have been read. As such, LLVM may assign
3086 the same register to an output and an input. If this is not safe (e.g. if the
3087 assembly contains two instructions, where the first writes to one output, and
3088 the second reads an input and writes to a second output), then the "``&``"
3089 modifier must be used (e.g. "``=&r``") to specify that the output is an
3090 "early-clobber" output. Marking an ouput as "early-clobber" ensures that LLVM
3091 will not use the same register for any inputs (other than an input tied to this
3097 Input constraints do not have a prefix -- just the constraint codes. Each input
3098 constraint will consume one argument from the call instruction. It is not
3099 permitted for the asm to write to any input register or memory location (unless
3100 that input is tied to an output). Note also that multiple inputs may all be
3101 assigned to the same register, if LLVM can determine that they necessarily all
3102 contain the same value.
3104 Instead of providing a Constraint Code, input constraints may also "tie"
3105 themselves to an output constraint, by providing an integer as the constraint
3106 string. Tied inputs still consume an argument from the call instruction, and
3107 take up a position in the asm template numbering as is usual -- they will simply
3108 be constrained to always use the same register as the output they've been tied
3109 to. For example, a constraint string of "``=r,0``" says to assign a register for
3110 output, and use that register as an input as well (it being the 0'th
3113 It is permitted to tie an input to an "early-clobber" output. In that case, no
3114 *other* input may share the same register as the input tied to the early-clobber
3115 (even when the other input has the same value).
3117 You may only tie an input to an output which has a register constraint, not a
3118 memory constraint. Only a single input may be tied to an output.
3120 There is also an "interesting" feature which deserves a bit of explanation: if a
3121 register class constraint allocates a register which is too small for the value
3122 type operand provided as input, the input value will be split into multiple
3123 registers, and all of them passed to the inline asm.
3125 However, this feature is often not as useful as you might think.
3127 Firstly, the registers are *not* guaranteed to be consecutive. So, on those
3128 architectures that have instructions which operate on multiple consecutive
3129 instructions, this is not an appropriate way to support them. (e.g. the 32-bit
3130 SparcV8 has a 64-bit load, which instruction takes a single 32-bit register. The
3131 hardware then loads into both the named register, and the next register. This
3132 feature of inline asm would not be useful to support that.)
3134 A few of the targets provide a template string modifier allowing explicit access
3135 to the second register of a two-register operand (e.g. MIPS ``L``, ``M``, and
3136 ``D``). On such an architecture, you can actually access the second allocated
3137 register (yet, still, not any subsequent ones). But, in that case, you're still
3138 probably better off simply splitting the value into two separate operands, for
3139 clarity. (e.g. see the description of the ``A`` constraint on X86, which,
3140 despite existing only for use with this feature, is not really a good idea to
3143 Indirect inputs and outputs
3144 """""""""""""""""""""""""""
3146 Indirect output or input constraints can be specified by the "``*``" modifier
3147 (which goes after the "``=``" in case of an output). This indicates that the asm
3148 will write to or read from the contents of an *address* provided as an input
3149 argument. (Note that in this way, indirect outputs act more like an *input* than
3150 an output: just like an input, they consume an argument of the call expression,
3151 rather than producing a return value. An indirect output constraint is an
3152 "output" only in that the asm is expected to write to the contents of the input
3153 memory location, instead of just read from it).
3155 This is most typically used for memory constraint, e.g. "``=*m``", to pass the
3156 address of a variable as a value.
3158 It is also possible to use an indirect *register* constraint, but only on output
3159 (e.g. "``=*r``"). This will cause LLVM to allocate a register for an output
3160 value normally, and then, separately emit a store to the address provided as
3161 input, after the provided inline asm. (It's not clear what value this
3162 functionality provides, compared to writing the store explicitly after the asm
3163 statement, and it can only produce worse code, since it bypasses many
3164 optimization passes. I would recommend not using it.)
3170 A clobber constraint is indicated by a "``~``" prefix. A clobber does not
3171 consume an input operand, nor generate an output. Clobbers cannot use any of the
3172 general constraint code letters -- they may use only explicit register
3173 constraints, e.g. "``~{eax}``". The one exception is that a clobber string of
3174 "``~{memory}``" indicates that the assembly writes to arbitrary undeclared
3175 memory locations -- not only the memory pointed to by a declared indirect
3181 After a potential prefix comes constraint code, or codes.
3183 A Constraint Code is either a single letter (e.g. "``r``"), a "``^``" character
3184 followed by two letters (e.g. "``^wc``"), or "``{``" register-name "``}``"
3187 The one and two letter constraint codes are typically chosen to be the same as
3188 GCC's constraint codes.
3190 A single constraint may include one or more than constraint code in it, leaving
3191 it up to LLVM to choose which one to use. This is included mainly for
3192 compatibility with the translation of GCC inline asm coming from clang.
3194 There are two ways to specify alternatives, and either or both may be used in an
3195 inline asm constraint list:
3197 1) Append the codes to each other, making a constraint code set. E.g. "``im``"
3198 or "``{eax}m``". This means "choose any of the options in the set". The
3199 choice of constraint is made independently for each constraint in the
3202 2) Use "``|``" between constraint code sets, creating alternatives. Every
3203 constraint in the constraint list must have the same number of alternative
3204 sets. With this syntax, the same alternative in *all* of the items in the
3205 constraint list will be chosen together.
3207 Putting those together, you might have a two operand constraint string like
3208 ``"rm|r,ri|rm"``. This indicates that if operand 0 is ``r`` or ``m``, then
3209 operand 1 may be one of ``r`` or ``i``. If operand 0 is ``r``, then operand 1
3210 may be one of ``r`` or ``m``. But, operand 0 and 1 cannot both be of type m.
3212 However, the use of either of the alternatives features is *NOT* recommended, as
3213 LLVM is not able to make an intelligent choice about which one to use. (At the
3214 point it currently needs to choose, not enough information is available to do so
3215 in a smart way.) Thus, it simply tries to make a choice that's most likely to
3216 compile, not one that will be optimal performance. (e.g., given "``rm``", it'll
3217 always choose to use memory, not registers). And, if given multiple registers,
3218 or multiple register classes, it will simply choose the first one. (In fact, it
3219 doesn't currently even ensure explicitly specified physical registers are
3220 unique, so specifying multiple physical registers as alternatives, like
3221 ``{r11}{r12},{r11}{r12}``, will assign r11 to both operands, not at all what was
3224 Supported Constraint Code List
3225 """"""""""""""""""""""""""""""
3227 The constraint codes are, in general, expected to behave the same way they do in
3228 GCC. LLVM's support is often implemented on an 'as-needed' basis, to support C
3229 inline asm code which was supported by GCC. A mismatch in behavior between LLVM
3230 and GCC likely indicates a bug in LLVM.
3232 Some constraint codes are typically supported by all targets:
3234 - ``r``: A register in the target's general purpose register class.
3235 - ``m``: A memory address operand. It is target-specific what addressing modes
3236 are supported, typical examples are register, or register + register offset,
3237 or register + immediate offset (of some target-specific size).
3238 - ``i``: An integer constant (of target-specific width). Allows either a simple
3239 immediate, or a relocatable value.
3240 - ``n``: An integer constant -- *not* including relocatable values.
3241 - ``s``: An integer constant, but allowing *only* relocatable values.
3242 - ``X``: Allows an operand of any kind, no constraint whatsoever. Typically
3243 useful to pass a label for an asm branch or call.
3245 .. FIXME: but that surely isn't actually okay to jump out of an asm
3246 block without telling llvm about the control transfer???)
3248 - ``{register-name}``: Requires exactly the named physical register.
3250 Other constraints are target-specific:
3254 - ``z``: An immediate integer 0. Outputs ``WZR`` or ``XZR``, as appropriate.
3255 - ``I``: An immediate integer valid for an ``ADD`` or ``SUB`` instruction,
3256 i.e. 0 to 4095 with optional shift by 12.
3257 - ``J``: An immediate integer that, when negated, is valid for an ``ADD`` or
3258 ``SUB`` instruction, i.e. -1 to -4095 with optional left shift by 12.
3259 - ``K``: An immediate integer that is valid for the 'bitmask immediate 32' of a
3260 logical instruction like ``AND``, ``EOR``, or ``ORR`` with a 32-bit register.
3261 - ``L``: An immediate integer that is valid for the 'bitmask immediate 64' of a
3262 logical instruction like ``AND``, ``EOR``, or ``ORR`` with a 64-bit register.
3263 - ``M``: An immediate integer for use with the ``MOV`` assembly alias on a
3264 32-bit register. This is a superset of ``K``: in addition to the bitmask
3265 immediate, also allows immediate integers which can be loaded with a single
3266 ``MOVZ`` or ``MOVL`` instruction.
3267 - ``N``: An immediate integer for use with the ``MOV`` assembly alias on a
3268 64-bit register. This is a superset of ``L``.
3269 - ``Q``: Memory address operand must be in a single register (no
3270 offsets). (However, LLVM currently does this for the ``m`` constraint as
3272 - ``r``: A 32 or 64-bit integer register (W* or X*).
3273 - ``w``: A 32, 64, or 128-bit floating-point/SIMD register.
3274 - ``x``: A lower 128-bit floating-point/SIMD register (``V0`` to ``V15``).
3278 - ``r``: A 32 or 64-bit integer register.
3279 - ``[0-9]v``: The 32-bit VGPR register, number 0-9.
3280 - ``[0-9]s``: The 32-bit SGPR register, number 0-9.
3285 - ``Q``, ``Um``, ``Un``, ``Uq``, ``Us``, ``Ut``, ``Uv``, ``Uy``: Memory address
3286 operand. Treated the same as operand ``m``, at the moment.
3288 ARM and ARM's Thumb2 mode:
3290 - ``j``: An immediate integer between 0 and 65535 (valid for ``MOVW``)
3291 - ``I``: An immediate integer valid for a data-processing instruction.
3292 - ``J``: An immediate integer between -4095 and 4095.
3293 - ``K``: An immediate integer whose bitwise inverse is valid for a
3294 data-processing instruction. (Can be used with template modifier "``B``" to
3295 print the inverted value).
3296 - ``L``: An immediate integer whose negation is valid for a data-processing
3297 instruction. (Can be used with template modifier "``n``" to print the negated
3299 - ``M``: A power of two or a integer between 0 and 32.
3300 - ``N``: Invalid immediate constraint.
3301 - ``O``: Invalid immediate constraint.
3302 - ``r``: A general-purpose 32-bit integer register (``r0-r15``).
3303 - ``l``: In Thumb2 mode, low 32-bit GPR registers (``r0-r7``). In ARM mode, same
3305 - ``h``: In Thumb2 mode, a high 32-bit GPR register (``r8-r15``). In ARM mode,
3307 - ``w``: A 32, 64, or 128-bit floating-point/SIMD register: ``s0-s31``,
3308 ``d0-d31``, or ``q0-q15``.
3309 - ``x``: A 32, 64, or 128-bit floating-point/SIMD register: ``s0-s15``,
3310 ``d0-d7``, or ``q0-q3``.
3311 - ``t``: A floating-point/SIMD register, only supports 32-bit values:
3316 - ``I``: An immediate integer between 0 and 255.
3317 - ``J``: An immediate integer between -255 and -1.
3318 - ``K``: An immediate integer between 0 and 255, with optional left-shift by
3320 - ``L``: An immediate integer between -7 and 7.
3321 - ``M``: An immediate integer which is a multiple of 4 between 0 and 1020.
3322 - ``N``: An immediate integer between 0 and 31.
3323 - ``O``: An immediate integer which is a multiple of 4 between -508 and 508.
3324 - ``r``: A low 32-bit GPR register (``r0-r7``).
3325 - ``l``: A low 32-bit GPR register (``r0-r7``).
3326 - ``h``: A high GPR register (``r0-r7``).
3327 - ``w``: A 32, 64, or 128-bit floating-point/SIMD register: ``s0-s31``,
3328 ``d0-d31``, or ``q0-q15``.
3329 - ``x``: A 32, 64, or 128-bit floating-point/SIMD register: ``s0-s15``,
3330 ``d0-d7``, or ``q0-q3``.
3331 - ``t``: A floating-point/SIMD register, only supports 32-bit values:
3337 - ``o``, ``v``: A memory address operand, treated the same as constraint ``m``,
3339 - ``r``: A 32 or 64-bit register.
3343 - ``r``: An 8 or 16-bit register.
3347 - ``I``: An immediate signed 16-bit integer.
3348 - ``J``: An immediate integer zero.
3349 - ``K``: An immediate unsigned 16-bit integer.
3350 - ``L``: An immediate 32-bit integer, where the lower 16 bits are 0.
3351 - ``N``: An immediate integer between -65535 and -1.
3352 - ``O``: An immediate signed 15-bit integer.
3353 - ``P``: An immediate integer between 1 and 65535.
3354 - ``m``: A memory address operand. In MIPS-SE mode, allows a base address
3355 register plus 16-bit immediate offset. In MIPS mode, just a base register.
3356 - ``R``: A memory address operand. In MIPS-SE mode, allows a base address
3357 register plus a 9-bit signed offset. In MIPS mode, the same as constraint
3359 - ``ZC``: A memory address operand, suitable for use in a ``pref``, ``ll``, or
3360 ``sc`` instruction on the given subtarget (details vary).
3361 - ``r``, ``d``, ``y``: A 32 or 64-bit GPR register.
3362 - ``f``: A 32 or 64-bit FPU register (``F0-F31``), or a 128-bit MSA register
3363 (``W0-W31``). In the case of MSA registers, it is recommended to use the ``w``
3364 argument modifier for compatibility with GCC.
3365 - ``c``: A 32-bit or 64-bit GPR register suitable for indirect jump (always
3367 - ``l``: The ``lo`` register, 32 or 64-bit.
3372 - ``b``: A 1-bit integer register.
3373 - ``c`` or ``h``: A 16-bit integer register.
3374 - ``r``: A 32-bit integer register.
3375 - ``l`` or ``N``: A 64-bit integer register.
3376 - ``f``: A 32-bit float register.
3377 - ``d``: A 64-bit float register.
3382 - ``I``: An immediate signed 16-bit integer.
3383 - ``J``: An immediate unsigned 16-bit integer, shifted left 16 bits.
3384 - ``K``: An immediate unsigned 16-bit integer.
3385 - ``L``: An immediate signed 16-bit integer, shifted left 16 bits.
3386 - ``M``: An immediate integer greater than 31.
3387 - ``N``: An immediate integer that is an exact power of 2.
3388 - ``O``: The immediate integer constant 0.
3389 - ``P``: An immediate integer constant whose negation is a signed 16-bit
3391 - ``es``, ``o``, ``Q``, ``Z``, ``Zy``: A memory address operand, currently
3392 treated the same as ``m``.
3393 - ``r``: A 32 or 64-bit integer register.
3394 - ``b``: A 32 or 64-bit integer register, excluding ``R0`` (that is:
3396 - ``f``: A 32 or 64-bit float register (``F0-F31``), or when QPX is enabled, a
3397 128 or 256-bit QPX register (``Q0-Q31``; aliases the ``F`` registers).
3398 - ``v``: For ``4 x f32`` or ``4 x f64`` types, when QPX is enabled, a
3399 128 or 256-bit QPX register (``Q0-Q31``), otherwise a 128-bit
3400 altivec vector register (``V0-V31``).
3402 .. FIXME: is this a bug that v accepts QPX registers? I think this
3403 is supposed to only use the altivec vector registers?
3405 - ``y``: Condition register (``CR0-CR7``).
3406 - ``wc``: An individual CR bit in a CR register.
3407 - ``wa``, ``wd``, ``wf``: Any 128-bit VSX vector register, from the full VSX
3408 register set (overlapping both the floating-point and vector register files).
3409 - ``ws``: A 32 or 64-bit floating point register, from the full VSX register
3414 - ``I``: An immediate 13-bit signed integer.
3415 - ``r``: A 32-bit integer register.
3419 - ``I``: An immediate unsigned 8-bit integer.
3420 - ``J``: An immediate unsigned 12-bit integer.
3421 - ``K``: An immediate signed 16-bit integer.
3422 - ``L``: An immediate signed 20-bit integer.
3423 - ``M``: An immediate integer 0x7fffffff.
3424 - ``Q``, ``R``, ``S``, ``T``: A memory address operand, treated the same as
3425 ``m``, at the moment.
3426 - ``r`` or ``d``: A 32, 64, or 128-bit integer register.
3427 - ``a``: A 32, 64, or 128-bit integer address register (excludes R0, which in an
3428 address context evaluates as zero).
3429 - ``h``: A 32-bit value in the high part of a 64bit data register
3431 - ``f``: A 32, 64, or 128-bit floating point register.
3435 - ``I``: An immediate integer between 0 and 31.
3436 - ``J``: An immediate integer between 0 and 64.
3437 - ``K``: An immediate signed 8-bit integer.
3438 - ``L``: An immediate integer, 0xff or 0xffff or (in 64-bit mode only)
3440 - ``M``: An immediate integer between 0 and 3.
3441 - ``N``: An immediate unsigned 8-bit integer.
3442 - ``O``: An immediate integer between 0 and 127.
3443 - ``e``: An immediate 32-bit signed integer.
3444 - ``Z``: An immediate 32-bit unsigned integer.
3445 - ``o``, ``v``: Treated the same as ``m``, at the moment.
3446 - ``q``: An 8, 16, 32, or 64-bit register which can be accessed as an 8-bit
3447 ``l`` integer register. On X86-32, this is the ``a``, ``b``, ``c``, and ``d``
3448 registers, and on X86-64, it is all of the integer registers.
3449 - ``Q``: An 8, 16, 32, or 64-bit register which can be accessed as an 8-bit
3450 ``h`` integer register. This is the ``a``, ``b``, ``c``, and ``d`` registers.
3451 - ``r`` or ``l``: An 8, 16, 32, or 64-bit integer register.
3452 - ``R``: An 8, 16, 32, or 64-bit "legacy" integer register -- one which has
3453 existed since i386, and can be accessed without the REX prefix.
3454 - ``f``: A 32, 64, or 80-bit '387 FPU stack pseudo-register.
3455 - ``y``: A 64-bit MMX register, if MMX is enabled.
3456 - ``x``: If SSE is enabled: a 32 or 64-bit scalar operand, or 128-bit vector
3457 operand in a SSE register. If AVX is also enabled, can also be a 256-bit
3458 vector operand in an AVX register. If AVX-512 is also enabled, can also be a
3459 512-bit vector operand in an AVX512 register, Otherwise, an error.
3460 - ``Y``: The same as ``x``, if *SSE2* is enabled, otherwise an error.
3461 - ``A``: Special case: allocates EAX first, then EDX, for a single operand (in
3462 32-bit mode, a 64-bit integer operand will get split into two registers). It
3463 is not recommended to use this constraint, as in 64-bit mode, the 64-bit
3464 operand will get allocated only to RAX -- if two 32-bit operands are needed,
3465 you're better off splitting it yourself, before passing it to the asm
3470 - ``r``: A 32-bit integer register.
3473 .. _inline-asm-modifiers:
3475 Asm template argument modifiers
3476 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3478 In the asm template string, modifiers can be used on the operand reference, like
3481 The modifiers are, in general, expected to behave the same way they do in
3482 GCC. LLVM's support is often implemented on an 'as-needed' basis, to support C
3483 inline asm code which was supported by GCC. A mismatch in behavior between LLVM
3484 and GCC likely indicates a bug in LLVM.
3488 - ``c``: Print an immediate integer constant unadorned, without
3489 the target-specific immediate punctuation (e.g. no ``$`` prefix).
3490 - ``n``: Negate and print immediate integer constant unadorned, without the
3491 target-specific immediate punctuation (e.g. no ``$`` prefix).
3492 - ``l``: Print as an unadorned label, without the target-specific label
3493 punctuation (e.g. no ``$`` prefix).
3497 - ``w``: Print a GPR register with a ``w*`` name instead of ``x*`` name. E.g.,
3498 instead of ``x30``, print ``w30``.
3499 - ``x``: Print a GPR register with a ``x*`` name. (this is the default, anyhow).
3500 - ``b``, ``h``, ``s``, ``d``, ``q``: Print a floating-point/SIMD register with a
3501 ``b*``, ``h*``, ``s*``, ``d*``, or ``q*`` name, rather than the default of
3510 - ``a``: Print an operand as an address (with ``[`` and ``]`` surrounding a
3514 - ``y``: Print a VFP single-precision register as an indexed double (e.g. print
3515 as ``d4[1]`` instead of ``s9``)
3516 - ``B``: Bitwise invert and print an immediate integer constant without ``#``
3518 - ``L``: Print the low 16-bits of an immediate integer constant.
3519 - ``M``: Print as a register set suitable for ldm/stm. Also prints *all*
3520 register operands subsequent to the specified one (!), so use carefully.
3521 - ``Q``: Print the low-order register of a register-pair, or the low-order
3522 register of a two-register operand.
3523 - ``R``: Print the high-order register of a register-pair, or the high-order
3524 register of a two-register operand.
3525 - ``H``: Print the second register of a register-pair. (On a big-endian system,
3526 ``H`` is equivalent to ``Q``, and on little-endian system, ``H`` is equivalent
3529 .. FIXME: H doesn't currently support printing the second register
3530 of a two-register operand.
3532 - ``e``: Print the low doubleword register of a NEON quad register.
3533 - ``f``: Print the high doubleword register of a NEON quad register.
3534 - ``m``: Print the base register of a memory operand without the ``[`` and ``]``
3539 - ``L``: Print the second register of a two-register operand. Requires that it
3540 has been allocated consecutively to the first.
3542 .. FIXME: why is it restricted to consecutive ones? And there's
3543 nothing that ensures that happens, is there?
3545 - ``I``: Print the letter 'i' if the operand is an integer constant, otherwise
3546 nothing. Used to print 'addi' vs 'add' instructions.
3550 No additional modifiers.
3554 - ``X``: Print an immediate integer as hexadecimal
3555 - ``x``: Print the low 16 bits of an immediate integer as hexadecimal.
3556 - ``d``: Print an immediate integer as decimal.
3557 - ``m``: Subtract one and print an immediate integer as decimal.
3558 - ``z``: Print $0 if an immediate zero, otherwise print normally.
3559 - ``L``: Print the low-order register of a two-register operand, or prints the
3560 address of the low-order word of a double-word memory operand.
3562 .. FIXME: L seems to be missing memory operand support.
3564 - ``M``: Print the high-order register of a two-register operand, or prints the
3565 address of the high-order word of a double-word memory operand.
3567 .. FIXME: M seems to be missing memory operand support.
3569 - ``D``: Print the second register of a two-register operand, or prints the
3570 second word of a double-word memory operand. (On a big-endian system, ``D`` is
3571 equivalent to ``L``, and on little-endian system, ``D`` is equivalent to
3573 - ``w``: No effect. Provided for compatibility with GCC which requires this
3574 modifier in order to print MSA registers (``W0-W31``) with the ``f``
3583 - ``L``: Print the second register of a two-register operand. Requires that it
3584 has been allocated consecutively to the first.
3586 .. FIXME: why is it restricted to consecutive ones? And there's
3587 nothing that ensures that happens, is there?
3589 - ``I``: Print the letter 'i' if the operand is an integer constant, otherwise
3590 nothing. Used to print 'addi' vs 'add' instructions.
3591 - ``y``: For a memory operand, prints formatter for a two-register X-form
3592 instruction. (Currently always prints ``r0,OPERAND``).
3593 - ``U``: Prints 'u' if the memory operand is an update form, and nothing
3594 otherwise. (NOTE: LLVM does not support update form, so this will currently
3595 always print nothing)
3596 - ``X``: Prints 'x' if the memory operand is an indexed form. (NOTE: LLVM does
3597 not support indexed form, so this will currently always print nothing)
3605 SystemZ implements only ``n``, and does *not* support any of the other
3606 target-independent modifiers.
3610 - ``c``: Print an unadorned integer or symbol name. (The latter is
3611 target-specific behavior for this typically target-independent modifier).
3612 - ``A``: Print a register name with a '``*``' before it.
3613 - ``b``: Print an 8-bit register name (e.g. ``al``); do nothing on a memory
3615 - ``h``: Print the upper 8-bit register name (e.g. ``ah``); do nothing on a
3617 - ``w``: Print the 16-bit register name (e.g. ``ax``); do nothing on a memory
3619 - ``k``: Print the 32-bit register name (e.g. ``eax``); do nothing on a memory
3621 - ``q``: Print the 64-bit register name (e.g. ``rax``), if 64-bit registers are
3622 available, otherwise the 32-bit register name; do nothing on a memory operand.
3623 - ``n``: Negate and print an unadorned integer, or, for operands other than an
3624 immediate integer (e.g. a relocatable symbol expression), print a '-' before
3625 the operand. (The behavior for relocatable symbol expressions is a
3626 target-specific behavior for this typically target-independent modifier)
3627 - ``H``: Print a memory reference with additional offset +8.
3628 - ``P``: Print a memory reference or operand for use as the argument of a call
3629 instruction. (E.g. omit ``(rip)``, even though it's PC-relative.)
3633 No additional modifiers.
3639 The call instructions that wrap inline asm nodes may have a
3640 "``!srcloc``" MDNode attached to it that contains a list of constant
3641 integers. If present, the code generator will use the integer as the
3642 location cookie value when report errors through the ``LLVMContext``
3643 error reporting mechanisms. This allows a front-end to correlate backend
3644 errors that occur with inline asm back to the source code that produced
3647 .. code-block:: llvm
3649 call void asm sideeffect "something bad", ""(), !srcloc !42
3651 !42 = !{ i32 1234567 }
3653 It is up to the front-end to make sense of the magic numbers it places
3654 in the IR. If the MDNode contains multiple constants, the code generator
3655 will use the one that corresponds to the line of the asm that the error
3663 LLVM IR allows metadata to be attached to instructions in the program
3664 that can convey extra information about the code to the optimizers and
3665 code generator. One example application of metadata is source-level
3666 debug information. There are two metadata primitives: strings and nodes.
3668 Metadata does not have a type, and is not a value. If referenced from a
3669 ``call`` instruction, it uses the ``metadata`` type.
3671 All metadata are identified in syntax by a exclamation point ('``!``').
3673 .. _metadata-string:
3675 Metadata Nodes and Metadata Strings
3676 -----------------------------------
3678 A metadata string is a string surrounded by double quotes. It can
3679 contain any character by escaping non-printable characters with
3680 "``\xx``" where "``xx``" is the two digit hex code. For example:
3683 Metadata nodes are represented with notation similar to structure
3684 constants (a comma separated list of elements, surrounded by braces and
3685 preceded by an exclamation point). Metadata nodes can have any values as
3686 their operand. For example:
3688 .. code-block:: llvm
3690 !{ !"test\00", i32 10}
3692 Metadata nodes that aren't uniqued use the ``distinct`` keyword. For example:
3694 .. code-block:: llvm
3696 !0 = distinct !{!"test\00", i32 10}
3698 ``distinct`` nodes are useful when nodes shouldn't be merged based on their
3699 content. They can also occur when transformations cause uniquing collisions
3700 when metadata operands change.
3702 A :ref:`named metadata <namedmetadatastructure>` is a collection of
3703 metadata nodes, which can be looked up in the module symbol table. For
3706 .. code-block:: llvm
3710 Metadata can be used as function arguments. Here ``llvm.dbg.value``
3711 function is using two metadata arguments:
3713 .. code-block:: llvm
3715 call void @llvm.dbg.value(metadata !24, i64 0, metadata !25)
3717 Metadata can be attached to an instruction. Here metadata ``!21`` is attached
3718 to the ``add`` instruction using the ``!dbg`` identifier:
3720 .. code-block:: llvm
3722 %indvar.next = add i64 %indvar, 1, !dbg !21
3724 Metadata can also be attached to a function definition. Here metadata ``!22``
3725 is attached to the ``foo`` function using the ``!dbg`` identifier:
3727 .. code-block:: llvm
3729 define void @foo() !dbg !22 {
3733 More information about specific metadata nodes recognized by the
3734 optimizers and code generator is found below.
3736 .. _specialized-metadata:
3738 Specialized Metadata Nodes
3739 ^^^^^^^^^^^^^^^^^^^^^^^^^^
3741 Specialized metadata nodes are custom data structures in metadata (as opposed
3742 to generic tuples). Their fields are labelled, and can be specified in any
3745 These aren't inherently debug info centric, but currently all the specialized
3746 metadata nodes are related to debug info.
3753 ``DICompileUnit`` nodes represent a compile unit. The ``enums:``,
3754 ``retainedTypes:``, ``subprograms:``, ``globals:``, ``imports:`` and ``macros:``
3755 fields are tuples containing the debug info to be emitted along with the compile
3756 unit, regardless of code optimizations (some nodes are only emitted if there are
3757 references to them from instructions).
3759 .. code-block:: llvm
3761 !0 = !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang",
3762 isOptimized: true, flags: "-O2", runtimeVersion: 2,
3763 splitDebugFilename: "abc.debug", emissionKind: 1,
3764 enums: !2, retainedTypes: !3, subprograms: !4,
3765 globals: !5, imports: !6, macros: !7, dwoId: 0x0abcd)
3767 Compile unit descriptors provide the root scope for objects declared in a
3768 specific compilation unit. File descriptors are defined using this scope.
3769 These descriptors are collected by a named metadata ``!llvm.dbg.cu``. They
3770 keep track of subprograms, global variables, type information, and imported
3771 entities (declarations and namespaces).
3778 ``DIFile`` nodes represent files. The ``filename:`` can include slashes.
3780 .. code-block:: llvm
3782 !0 = !DIFile(filename: "path/to/file", directory: "/path/to/dir")
3784 Files are sometimes used in ``scope:`` fields, and are the only valid target
3785 for ``file:`` fields.
3792 ``DIBasicType`` nodes represent primitive types, such as ``int``, ``bool`` and
3793 ``float``. ``tag:`` defaults to ``DW_TAG_base_type``.
3795 .. code-block:: llvm
3797 !0 = !DIBasicType(name: "unsigned char", size: 8, align: 8,
3798 encoding: DW_ATE_unsigned_char)
3799 !1 = !DIBasicType(tag: DW_TAG_unspecified_type, name: "decltype(nullptr)")
3801 The ``encoding:`` describes the details of the type. Usually it's one of the
3804 .. code-block:: llvm
3810 DW_ATE_signed_char = 6
3812 DW_ATE_unsigned_char = 8
3814 .. _DISubroutineType:
3819 ``DISubroutineType`` nodes represent subroutine types. Their ``types:`` field
3820 refers to a tuple; the first operand is the return type, while the rest are the
3821 types of the formal arguments in order. If the first operand is ``null``, that
3822 represents a function with no return value (such as ``void foo() {}`` in C++).
3824 .. code-block:: llvm
3826 !0 = !BasicType(name: "int", size: 32, align: 32, DW_ATE_signed)
3827 !1 = !BasicType(name: "char", size: 8, align: 8, DW_ATE_signed_char)
3828 !2 = !DISubroutineType(types: !{null, !0, !1}) ; void (int, char)
3835 ``DIDerivedType`` nodes represent types derived from other types, such as
3838 .. code-block:: llvm
3840 !0 = !DIBasicType(name: "unsigned char", size: 8, align: 8,
3841 encoding: DW_ATE_unsigned_char)
3842 !1 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !0, size: 32,
3845 The following ``tag:`` values are valid:
3847 .. code-block:: llvm
3849 DW_TAG_formal_parameter = 5
3851 DW_TAG_pointer_type = 15
3852 DW_TAG_reference_type = 16
3854 DW_TAG_ptr_to_member_type = 31
3855 DW_TAG_const_type = 38
3856 DW_TAG_volatile_type = 53
3857 DW_TAG_restrict_type = 55
3859 ``DW_TAG_member`` is used to define a member of a :ref:`composite type
3860 <DICompositeType>` or :ref:`subprogram <DISubprogram>`. The type of the member
3861 is the ``baseType:``. The ``offset:`` is the member's bit offset.
3862 ``DW_TAG_formal_parameter`` is used to define a member which is a formal
3863 argument of a subprogram.
3865 ``DW_TAG_typedef`` is used to provide a name for the ``baseType:``.
3867 ``DW_TAG_pointer_type``, ``DW_TAG_reference_type``, ``DW_TAG_const_type``,
3868 ``DW_TAG_volatile_type`` and ``DW_TAG_restrict_type`` are used to qualify the
3871 Note that the ``void *`` type is expressed as a type derived from NULL.
3873 .. _DICompositeType:
3878 ``DICompositeType`` nodes represent types composed of other types, like
3879 structures and unions. ``elements:`` points to a tuple of the composed types.
3881 If the source language supports ODR, the ``identifier:`` field gives the unique
3882 identifier used for type merging between modules. When specified, other types
3883 can refer to composite types indirectly via a :ref:`metadata string
3884 <metadata-string>` that matches their identifier.
3886 .. code-block:: llvm
3888 !0 = !DIEnumerator(name: "SixKind", value: 7)
3889 !1 = !DIEnumerator(name: "SevenKind", value: 7)
3890 !2 = !DIEnumerator(name: "NegEightKind", value: -8)
3891 !3 = !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum", file: !12,
3892 line: 2, size: 32, align: 32, identifier: "_M4Enum",
3893 elements: !{!0, !1, !2})
3895 The following ``tag:`` values are valid:
3897 .. code-block:: llvm
3899 DW_TAG_array_type = 1
3900 DW_TAG_class_type = 2
3901 DW_TAG_enumeration_type = 4
3902 DW_TAG_structure_type = 19
3903 DW_TAG_union_type = 23
3904 DW_TAG_subroutine_type = 21
3905 DW_TAG_inheritance = 28
3908 For ``DW_TAG_array_type``, the ``elements:`` should be :ref:`subrange
3909 descriptors <DISubrange>`, each representing the range of subscripts at that
3910 level of indexing. The ``DIFlagVector`` flag to ``flags:`` indicates that an
3911 array type is a native packed vector.
3913 For ``DW_TAG_enumeration_type``, the ``elements:`` should be :ref:`enumerator
3914 descriptors <DIEnumerator>`, each representing the definition of an enumeration
3915 value for the set. All enumeration type descriptors are collected in the
3916 ``enums:`` field of the :ref:`compile unit <DICompileUnit>`.
3918 For ``DW_TAG_structure_type``, ``DW_TAG_class_type``, and
3919 ``DW_TAG_union_type``, the ``elements:`` should be :ref:`derived types
3920 <DIDerivedType>` with ``tag: DW_TAG_member`` or ``tag: DW_TAG_inheritance``.
3927 ``DISubrange`` nodes are the elements for ``DW_TAG_array_type`` variants of
3928 :ref:`DICompositeType`. ``count: -1`` indicates an empty array.
3930 .. code-block:: llvm
3932 !0 = !DISubrange(count: 5, lowerBound: 0) ; array counting from 0
3933 !1 = !DISubrange(count: 5, lowerBound: 1) ; array counting from 1
3934 !2 = !DISubrange(count: -1) ; empty array.
3941 ``DIEnumerator`` nodes are the elements for ``DW_TAG_enumeration_type``
3942 variants of :ref:`DICompositeType`.
3944 .. code-block:: llvm
3946 !0 = !DIEnumerator(name: "SixKind", value: 7)
3947 !1 = !DIEnumerator(name: "SevenKind", value: 7)
3948 !2 = !DIEnumerator(name: "NegEightKind", value: -8)
3950 DITemplateTypeParameter
3951 """""""""""""""""""""""
3953 ``DITemplateTypeParameter`` nodes represent type parameters to generic source
3954 language constructs. They are used (optionally) in :ref:`DICompositeType` and
3955 :ref:`DISubprogram` ``templateParams:`` fields.
3957 .. code-block:: llvm
3959 !0 = !DITemplateTypeParameter(name: "Ty", type: !1)
3961 DITemplateValueParameter
3962 """"""""""""""""""""""""
3964 ``DITemplateValueParameter`` nodes represent value parameters to generic source
3965 language constructs. ``tag:`` defaults to ``DW_TAG_template_value_parameter``,
3966 but if specified can also be set to ``DW_TAG_GNU_template_template_param`` or
3967 ``DW_TAG_GNU_template_param_pack``. They are used (optionally) in
3968 :ref:`DICompositeType` and :ref:`DISubprogram` ``templateParams:`` fields.
3970 .. code-block:: llvm
3972 !0 = !DITemplateValueParameter(name: "Ty", type: !1, value: i32 7)
3977 ``DINamespace`` nodes represent namespaces in the source language.
3979 .. code-block:: llvm
3981 !0 = !DINamespace(name: "myawesomeproject", scope: !1, file: !2, line: 7)
3986 ``DIGlobalVariable`` nodes represent global variables in the source language.
3988 .. code-block:: llvm
3990 !0 = !DIGlobalVariable(name: "foo", linkageName: "foo", scope: !1,
3991 file: !2, line: 7, type: !3, isLocal: true,
3992 isDefinition: false, variable: i32* @foo,
3995 All global variables should be referenced by the `globals:` field of a
3996 :ref:`compile unit <DICompileUnit>`.
4003 ``DISubprogram`` nodes represent functions from the source language. A
4004 ``DISubprogram`` may be attached to a function definition using ``!dbg``
4005 metadata. The ``variables:`` field points at :ref:`variables <DILocalVariable>`
4006 that must be retained, even if their IR counterparts are optimized out of
4007 the IR. The ``type:`` field must point at an :ref:`DISubroutineType`.
4009 .. code-block:: llvm
4011 define void @_Z3foov() !dbg !0 {
4015 !0 = distinct !DISubprogram(name: "foo", linkageName: "_Zfoov", scope: !1,
4016 file: !2, line: 7, type: !3, isLocal: true,
4017 isDefinition: false, scopeLine: 8,
4019 virtuality: DW_VIRTUALITY_pure_virtual,
4020 virtualIndex: 10, flags: DIFlagPrototyped,
4021 isOptimized: true, templateParams: !5,
4022 declaration: !6, variables: !7)
4029 ``DILexicalBlock`` nodes describe nested blocks within a :ref:`subprogram
4030 <DISubprogram>`. The line number and column numbers are used to distinguish
4031 two lexical blocks at same depth. They are valid targets for ``scope:``
4034 .. code-block:: llvm
4036 !0 = distinct !DILexicalBlock(scope: !1, file: !2, line: 7, column: 35)
4038 Usually lexical blocks are ``distinct`` to prevent node merging based on
4041 .. _DILexicalBlockFile:
4046 ``DILexicalBlockFile`` nodes are used to discriminate between sections of a
4047 :ref:`lexical block <DILexicalBlock>`. The ``file:`` field can be changed to
4048 indicate textual inclusion, or the ``discriminator:`` field can be used to
4049 discriminate between control flow within a single block in the source language.
4051 .. code-block:: llvm
4053 !0 = !DILexicalBlock(scope: !3, file: !4, line: 7, column: 35)
4054 !1 = !DILexicalBlockFile(scope: !0, file: !4, discriminator: 0)
4055 !2 = !DILexicalBlockFile(scope: !0, file: !4, discriminator: 1)
4062 ``DILocation`` nodes represent source debug locations. The ``scope:`` field is
4063 mandatory, and points at an :ref:`DILexicalBlockFile`, an
4064 :ref:`DILexicalBlock`, or an :ref:`DISubprogram`.
4066 .. code-block:: llvm
4068 !0 = !DILocation(line: 2900, column: 42, scope: !1, inlinedAt: !2)
4070 .. _DILocalVariable:
4075 ``DILocalVariable`` nodes represent local variables in the source language. If
4076 the ``arg:`` field is set to non-zero, then this variable is a subprogram
4077 parameter, and it will be included in the ``variables:`` field of its
4078 :ref:`DISubprogram`.
4080 .. code-block:: llvm
4082 !0 = !DILocalVariable(name: "this", arg: 1, scope: !3, file: !2, line: 7,
4083 type: !3, flags: DIFlagArtificial)
4084 !1 = !DILocalVariable(name: "x", arg: 2, scope: !4, file: !2, line: 7,
4086 !2 = !DILocalVariable(name: "y", scope: !5, file: !2, line: 7, type: !3)
4091 ``DIExpression`` nodes represent DWARF expression sequences. They are used in
4092 :ref:`debug intrinsics<dbg_intrinsics>` (such as ``llvm.dbg.declare``) to
4093 describe how the referenced LLVM variable relates to the source language
4096 The current supported vocabulary is limited:
4098 - ``DW_OP_deref`` dereferences the working expression.
4099 - ``DW_OP_plus, 93`` adds ``93`` to the working expression.
4100 - ``DW_OP_bit_piece, 16, 8`` specifies the offset and size (``16`` and ``8``
4101 here, respectively) of the variable piece from the working expression.
4103 .. code-block:: llvm
4105 !0 = !DIExpression(DW_OP_deref)
4106 !1 = !DIExpression(DW_OP_plus, 3)
4107 !2 = !DIExpression(DW_OP_bit_piece, 3, 7)
4108 !3 = !DIExpression(DW_OP_deref, DW_OP_plus, 3, DW_OP_bit_piece, 3, 7)
4113 ``DIObjCProperty`` nodes represent Objective-C property nodes.
4115 .. code-block:: llvm
4117 !3 = !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4118 getter: "getFoo", attributes: 7, type: !2)
4123 ``DIImportedEntity`` nodes represent entities (such as modules) imported into a
4126 .. code-block:: llvm
4128 !2 = !DIImportedEntity(tag: DW_TAG_imported_module, name: "foo", scope: !0,
4129 entity: !1, line: 7)
4134 ``DIMacro`` nodes represent definition or undefinition of a macro identifiers.
4135 The ``name:`` field is the macro identifier, followed by macro parameters when
4136 definining a function-like macro, and the ``value`` field is the token-string
4137 used to expand the macro identifier.
4139 .. code-block:: llvm
4141 !2 = !DIMacro(macinfo: DW_MACINFO_define, line: 7, name: "foo(x)",
4143 !3 = !DIMacro(macinfo: DW_MACINFO_undef, line: 30, name: "foo")
4148 ``DIMacroFile`` nodes represent inclusion of source files.
4149 The ``nodes:`` field is a list of ``DIMacro`` and ``DIMacroFile`` nodes that
4150 appear in the included source file.
4152 .. code-block:: llvm
4154 !2 = !DIMacroFile(macinfo: DW_MACINFO_start_file, line: 7, file: !2,
4160 In LLVM IR, memory does not have types, so LLVM's own type system is not
4161 suitable for doing TBAA. Instead, metadata is added to the IR to
4162 describe a type system of a higher level language. This can be used to
4163 implement typical C/C++ TBAA, but it can also be used to implement
4164 custom alias analysis behavior for other languages.
4166 The current metadata format is very simple. TBAA metadata nodes have up
4167 to three fields, e.g.:
4169 .. code-block:: llvm
4171 !0 = !{ !"an example type tree" }
4172 !1 = !{ !"int", !0 }
4173 !2 = !{ !"float", !0 }
4174 !3 = !{ !"const float", !2, i64 1 }
4176 The first field is an identity field. It can be any value, usually a
4177 metadata string, which uniquely identifies the type. The most important
4178 name in the tree is the name of the root node. Two trees with different
4179 root node names are entirely disjoint, even if they have leaves with
4182 The second field identifies the type's parent node in the tree, or is
4183 null or omitted for a root node. A type is considered to alias all of
4184 its descendants and all of its ancestors in the tree. Also, a type is
4185 considered to alias all types in other trees, so that bitcode produced
4186 from multiple front-ends is handled conservatively.
4188 If the third field is present, it's an integer which if equal to 1
4189 indicates that the type is "constant" (meaning
4190 ``pointsToConstantMemory`` should return true; see `other useful
4191 AliasAnalysis methods <AliasAnalysis.html#OtherItfs>`_).
4193 '``tbaa.struct``' Metadata
4194 ^^^^^^^^^^^^^^^^^^^^^^^^^^
4196 The :ref:`llvm.memcpy <int_memcpy>` is often used to implement
4197 aggregate assignment operations in C and similar languages, however it
4198 is defined to copy a contiguous region of memory, which is more than
4199 strictly necessary for aggregate types which contain holes due to
4200 padding. Also, it doesn't contain any TBAA information about the fields
4203 ``!tbaa.struct`` metadata can describe which memory subregions in a
4204 memcpy are padding and what the TBAA tags of the struct are.
4206 The current metadata format is very simple. ``!tbaa.struct`` metadata
4207 nodes are a list of operands which are in conceptual groups of three.
4208 For each group of three, the first operand gives the byte offset of a
4209 field in bytes, the second gives its size in bytes, and the third gives
4212 .. code-block:: llvm
4214 !4 = !{ i64 0, i64 4, !1, i64 8, i64 4, !2 }
4216 This describes a struct with two fields. The first is at offset 0 bytes
4217 with size 4 bytes, and has tbaa tag !1. The second is at offset 8 bytes
4218 and has size 4 bytes and has tbaa tag !2.
4220 Note that the fields need not be contiguous. In this example, there is a
4221 4 byte gap between the two fields. This gap represents padding which
4222 does not carry useful data and need not be preserved.
4224 '``noalias``' and '``alias.scope``' Metadata
4225 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4227 ``noalias`` and ``alias.scope`` metadata provide the ability to specify generic
4228 noalias memory-access sets. This means that some collection of memory access
4229 instructions (loads, stores, memory-accessing calls, etc.) that carry
4230 ``noalias`` metadata can specifically be specified not to alias with some other
4231 collection of memory access instructions that carry ``alias.scope`` metadata.
4232 Each type of metadata specifies a list of scopes where each scope has an id and
4233 a domain. When evaluating an aliasing query, if for some domain, the set
4234 of scopes with that domain in one instruction's ``alias.scope`` list is a
4235 subset of (or equal to) the set of scopes for that domain in another
4236 instruction's ``noalias`` list, then the two memory accesses are assumed not to
4239 The metadata identifying each domain is itself a list containing one or two
4240 entries. The first entry is the name of the domain. Note that if the name is a
4241 string then it can be combined across functions and translation units. A
4242 self-reference can be used to create globally unique domain names. A
4243 descriptive string may optionally be provided as a second list entry.
4245 The metadata identifying each scope is also itself a list containing two or
4246 three entries. The first entry is the name of the scope. Note that if the name
4247 is a string then it can be combined across functions and translation units. A
4248 self-reference can be used to create globally unique scope names. A metadata
4249 reference to the scope's domain is the second entry. A descriptive string may
4250 optionally be provided as a third list entry.
4254 .. code-block:: llvm
4256 ; Two scope domains:
4260 ; Some scopes in these domains:
4266 !5 = !{!4} ; A list containing only scope !4
4270 ; These two instructions don't alias:
4271 %0 = load float, float* %c, align 4, !alias.scope !5
4272 store float %0, float* %arrayidx.i, align 4, !noalias !5
4274 ; These two instructions also don't alias (for domain !1, the set of scopes
4275 ; in the !alias.scope equals that in the !noalias list):
4276 %2 = load float, float* %c, align 4, !alias.scope !5
4277 store float %2, float* %arrayidx.i2, align 4, !noalias !6
4279 ; These two instructions may alias (for domain !0, the set of scopes in
4280 ; the !noalias list is not a superset of, or equal to, the scopes in the
4281 ; !alias.scope list):
4282 %2 = load float, float* %c, align 4, !alias.scope !6
4283 store float %0, float* %arrayidx.i, align 4, !noalias !7
4285 '``fpmath``' Metadata