blob: c08cee1dbd85e6e340a345dd0d25c77d870cee9d [file] [log] [blame]
Sean Silvaf722b002012-12-07 10:36:55 +00001==============================
2LLVM Language Reference Manual
3==============================
4
5.. contents::
6 :local:
7 :depth: 3
8
Sean Silvaf722b002012-12-07 10:36:55 +00009Abstract
10========
11
12This document is a reference manual for the LLVM assembly language. LLVM
13is a Static Single Assignment (SSA) based representation that provides
14type safety, low-level operations, flexibility, and the capability of
15representing 'all' high-level languages cleanly. It is the common code
16representation used throughout all phases of the LLVM compilation
17strategy.
18
19Introduction
20============
21
22The LLVM code representation is designed to be used in three different
23forms: 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
25readable assembly language representation. This allows LLVM to provide a
26powerful intermediate representation for efficient compiler
27transformations and analysis, while providing a natural means to debug
28and visualize the transformations. The three different forms of LLVM are
29all equivalent. This document describes the human readable
30representation and notation.
31
32The LLVM representation aims to be light-weight and low-level while
33being expressive, typed, and extensible at the same time. It aims to be
34a "universal IR" of sorts, by being at a low enough level that
35high-level ideas may be cleanly mapped to it (similar to how
36microprocessors are "universal IR's", allowing many source languages to
37be mapped to them). By providing type information, LLVM can be used as
38the target of optimizations: for example, through pointer analysis, it
39can be proven that a C automatic variable is never accessed outside of
40the current function, allowing it to be promoted to a simple SSA value
41instead of a memory location.
42
43.. _wellformed:
44
45Well-Formedness
46---------------
47
48It is important to note that this document describes 'well formed' LLVM
49assembly language. There is a difference between what the parser accepts
50and what is considered 'well formed'. For example, the following
51instruction is syntactically okay, but not well formed:
52
53.. code-block:: llvm
54
55 %x = add i32 1, %x
56
57because the definition of ``%x`` does not dominate all of its uses. The
58LLVM infrastructure provides a verification pass that may be used to
59verify that an LLVM module is well formed. This pass is automatically
60run by the parser after parsing input assembly and by the optimizer
61before it outputs bitcode. The violations pointed out by the verifier
62pass indicate bugs in transformation passes or input to the parser.
63
64.. _identifiers:
65
66Identifiers
67===========
68
69LLVM identifiers come in two basic types: global and local. Global
70identifiers (functions, global variables) begin with the ``'@'``
71character. Local identifiers (register names, types) begin with the
72``'%'`` character. Additionally, there are three different formats for
73identifiers, for different purposes:
74
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 which 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.
83#. Unnamed values are represented as an unsigned numeric value with
84 their prefix. For example, ``%12``, ``@2``, ``%44``.
85#. Constants, which are described in the section Constants_ below.
86
87LLVM requires that values start with a prefix for two reasons: Compilers
88don't need to worry about name clashes with reserved words, and the set
89of reserved words may be expanded in the future without penalty.
90Additionally, unnamed identifiers allow a compiler to quickly come up
91with a temporary variable without having to avoid symbol table
92conflicts.
93
94Reserved words in LLVM are very similar to reserved words in other
95languages. There are keywords for different opcodes ('``add``',
96'``bitcast``', '``ret``', etc...), for primitive type names ('``void``',
97'``i32``', etc...), and others. These reserved words cannot conflict
98with variable names, because none of them start with a prefix character
99(``'%'`` or ``'@'``).
100
101Here is an example of LLVM code to multiply the integer variable
102'``%X``' by 8:
103
104The easy way:
105
106.. code-block:: llvm
107
108 %result = mul i32 %X, 8
109
110After strength reduction:
111
112.. code-block:: llvm
113
Dmitri Gribenko126fde52013-01-26 13:30:13 +0000114 %result = shl i32 %X, 3
Sean Silvaf722b002012-12-07 10:36:55 +0000115
116And the hard way:
117
118.. code-block:: llvm
119
120 %0 = add i32 %X, %X ; yields {i32}:%0
121 %1 = add i32 %0, %0 ; yields {i32}:%1
122 %result = add i32 %1, %1
123
124This last way of multiplying ``%X`` by 8 illustrates several important
125lexical features of LLVM:
126
127#. Comments are delimited with a '``;``' and go until the end of line.
128#. Unnamed temporaries are created when the result of a computation is
129 not assigned to a named value.
130#. Unnamed temporaries are numbered sequentially
131
132It also shows a convention that we follow in this document. When
133demonstrating instructions, we will follow an instruction with a comment
134that defines the type and name of value produced.
135
136High Level Structure
137====================
138
139Module Structure
140----------------
141
142LLVM programs are composed of ``Module``'s, each of which is a
143translation unit of the input programs. Each module consists of
144functions, global variables, and symbol table entries. Modules may be
145combined together with the LLVM linker, which merges function (and
146global variable) definitions, resolves forward declarations, and merges
147symbol table entries. Here is an example of the "hello world" module:
148
149.. code-block:: llvm
150
Daniel Dunbar3389dbc2013-01-17 18:57:32 +0000151 ; Declare the string constant as a global constant.
152 @.str = private unnamed_addr constant [13 x i8] c"hello world\0A\00"
Sean Silvaf722b002012-12-07 10:36:55 +0000153
Daniel Dunbar3389dbc2013-01-17 18:57:32 +0000154 ; External declaration of the puts function
155 declare i32 @puts(i8* nocapture) nounwind
Sean Silvaf722b002012-12-07 10:36:55 +0000156
157 ; Definition of main function
Daniel Dunbar3389dbc2013-01-17 18:57:32 +0000158 define i32 @main() { ; i32()*
159 ; Convert [13 x i8]* to i8 *...
Sean Silvaf722b002012-12-07 10:36:55 +0000160 %cast210 = getelementptr [13 x i8]* @.str, i64 0, i64 0
161
Daniel Dunbar3389dbc2013-01-17 18:57:32 +0000162 ; Call puts function to write out the string to stdout.
Sean Silvaf722b002012-12-07 10:36:55 +0000163 call i32 @puts(i8* %cast210)
Daniel Dunbar3389dbc2013-01-17 18:57:32 +0000164 ret i32 0
Sean Silvaf722b002012-12-07 10:36:55 +0000165 }
166
167 ; Named metadata
168 !1 = metadata !{i32 42}
169 !foo = !{!1, null}
170
171This example is made up of a :ref:`global variable <globalvars>` named
172"``.str``", an external declaration of the "``puts``" function, a
173:ref:`function definition <functionstructure>` for "``main``" and
174:ref:`named metadata <namedmetadatastructure>` "``foo``".
175
176In general, a module is made up of a list of global values (where both
177functions and global variables are global values). Global values are
178represented by a pointer to a memory location (in this case, a pointer
179to an array of char, and a pointer to a function), and have one of the
180following :ref:`linkage types <linkage>`.
181
182.. _linkage:
183
184Linkage Types
185-------------
186
187All Global Variables and Functions have one of the following types of
188linkage:
189
190``private``
191 Global values with "``private``" linkage are only directly
192 accessible by objects in the current module. In particular, linking
193 code into a module with an private global value may cause the
194 private to be renamed as necessary to avoid collisions. Because the
195 symbol is private to the module, all references can be updated. This
196 doesn't show up in any symbol table in the object file.
197``linker_private``
198 Similar to ``private``, but the symbol is passed through the
199 assembler and evaluated by the linker. Unlike normal strong symbols,
200 they are removed by the linker from the final linked image
201 (executable or dynamic library).
202``linker_private_weak``
203 Similar to "``linker_private``", but the symbol is weak. Note that
204 ``linker_private_weak`` symbols are subject to coalescing by the
205 linker. The symbols are removed by the linker from the final linked
206 image (executable or dynamic library).
207``internal``
208 Similar to private, but the value shows as a local symbol
209 (``STB_LOCAL`` in the case of ELF) in the object file. This
210 corresponds to the notion of the '``static``' keyword in C.
211``available_externally``
212 Globals with "``available_externally``" linkage are never emitted
213 into the object file corresponding to the LLVM module. They exist to
214 allow inlining and other optimizations to take place given knowledge
215 of the definition of the global, which is known to be somewhere
216 outside the module. Globals with ``available_externally`` linkage
217 are allowed to be discarded at will, and are otherwise the same as
218 ``linkonce_odr``. This linkage type is only allowed on definitions,
219 not declarations.
220``linkonce``
221 Globals with "``linkonce``" linkage are merged with other globals of
222 the same name when linkage occurs. This can be used to implement
223 some forms of inline functions, templates, or other code which must
224 be generated in each translation unit that uses it, but where the
225 body may be overridden with a more definitive definition later.
226 Unreferenced ``linkonce`` globals are allowed to be discarded. Note
227 that ``linkonce`` linkage does not actually allow the optimizer to
228 inline the body of this function into callers because it doesn't
229 know if this definition of the function is the definitive definition
230 within the program or whether it will be overridden by a stronger
231 definition. To enable inlining and other optimizations, use
232 "``linkonce_odr``" linkage.
233``weak``
234 "``weak``" linkage has the same merging semantics as ``linkonce``
235 linkage, except that unreferenced globals with ``weak`` linkage may
236 not be discarded. This is used for globals that are declared "weak"
237 in C source code.
238``common``
239 "``common``" linkage is most similar to "``weak``" linkage, but they
240 are used for tentative definitions in C, such as "``int X;``" at
241 global scope. Symbols with "``common``" linkage are merged in the
242 same way as ``weak symbols``, and they may not be deleted if
243 unreferenced. ``common`` symbols may not have an explicit section,
244 must have a zero initializer, and may not be marked
245 ':ref:`constant <globalvars>`'. Functions and aliases may not have
246 common linkage.
247
248.. _linkage_appending:
249
250``appending``
251 "``appending``" linkage may only be applied to global variables of
252 pointer to array type. When two global variables with appending
253 linkage are linked together, the two global arrays are appended
254 together. This is the LLVM, typesafe, equivalent of having the
255 system linker append together "sections" with identical names when
256 .o files are linked.
257``extern_weak``
258 The semantics of this linkage follow the ELF object file model: the
259 symbol is weak until linked, if not linked, the symbol becomes null
260 instead of being an undefined reference.
261``linkonce_odr``, ``weak_odr``
262 Some languages allow differing globals to be merged, such as two
263 functions with different semantics. Other languages, such as
264 ``C++``, ensure that only equivalent globals are ever merged (the
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +0000265 "one definition rule" --- "ODR"). Such languages can use the
Sean Silvaf722b002012-12-07 10:36:55 +0000266 ``linkonce_odr`` and ``weak_odr`` linkage types to indicate that the
267 global will only be merged with equivalent globals. These linkage
268 types are otherwise the same as their non-``odr`` versions.
269``linkonce_odr_auto_hide``
270 Similar to "``linkonce_odr``", but nothing in the translation unit
271 takes the address of this definition. For instance, functions that
272 had an inline definition, but the compiler decided not to inline it.
273 ``linkonce_odr_auto_hide`` may have only ``default`` visibility. The
274 symbols are removed by the linker from the final linked image
275 (executable or dynamic library).
276``external``
277 If none of the above identifiers are used, the global is externally
278 visible, meaning that it participates in linkage and can be used to
279 resolve external symbol references.
280
281The next two types of linkage are targeted for Microsoft Windows
282platform only. They are designed to support importing (exporting)
283symbols from (to) DLLs (Dynamic Link Libraries).
284
285``dllimport``
286 "``dllimport``" linkage causes the compiler to reference a function
287 or variable via a global pointer to a pointer that is set up by the
288 DLL exporting the symbol. On Microsoft Windows targets, the pointer
289 name is formed by combining ``__imp_`` and the function or variable
290 name.
291``dllexport``
292 "``dllexport``" linkage causes the compiler to provide a global
293 pointer to a pointer in a DLL, so that it can be referenced with the
294 ``dllimport`` attribute. On Microsoft Windows targets, the pointer
295 name is formed by combining ``__imp_`` and the function or variable
296 name.
297
298For example, since the "``.LC0``" variable is defined to be internal, if
299another module defined a "``.LC0``" variable and was linked with this
300one, one of the two would be renamed, preventing a collision. Since
301"``main``" and "``puts``" are external (i.e., lacking any linkage
302declarations), they are accessible outside of the current module.
303
304It is illegal for a function *declaration* to have any linkage type
305other than ``external``, ``dllimport`` or ``extern_weak``.
306
307Aliases can have only ``external``, ``internal``, ``weak`` or
308``weak_odr`` linkages.
309
310.. _callingconv:
311
312Calling Conventions
313-------------------
314
315LLVM :ref:`functions <functionstructure>`, :ref:`calls <i_call>` and
316:ref:`invokes <i_invoke>` can all have an optional calling convention
317specified for the call. The calling convention of any pair of dynamic
318caller/callee must match, or the behavior of the program is undefined.
319The following calling conventions are supported by LLVM, and more may be
320added in the future:
321
322"``ccc``" - The C calling convention
323 This calling convention (the default if no other calling convention
324 is specified) matches the target C calling conventions. This calling
325 convention supports varargs function calls and tolerates some
326 mismatch in the declared prototype and implemented declaration of
327 the function (as does normal C).
328"``fastcc``" - The fast calling convention
329 This calling convention attempts to make calls as fast as possible
330 (e.g. by passing things in registers). This calling convention
331 allows the target to use whatever tricks it wants to produce fast
332 code for the target, without having to conform to an externally
333 specified ABI (Application Binary Interface). `Tail calls can only
334 be optimized when this, the GHC or the HiPE convention is
335 used. <CodeGenerator.html#id80>`_ This calling convention does not
336 support varargs and requires the prototype of all callees to exactly
337 match the prototype of the function definition.
338"``coldcc``" - The cold calling convention
339 This calling convention attempts to make code in the caller as
340 efficient as possible under the assumption that the call is not
341 commonly executed. As such, these calls often preserve all registers
342 so that the call does not break any live ranges in the caller side.
343 This calling convention does not support varargs and requires the
344 prototype of all callees to exactly match the prototype of the
345 function definition.
346"``cc 10``" - GHC convention
347 This calling convention has been implemented specifically for use by
348 the `Glasgow Haskell Compiler (GHC) <http://www.haskell.org/ghc>`_.
349 It passes everything in registers, going to extremes to achieve this
350 by disabling callee save registers. This calling convention should
351 not be used lightly but only for specific situations such as an
352 alternative to the *register pinning* performance technique often
353 used when implementing functional programming languages. At the
354 moment only X86 supports this convention and it has the following
355 limitations:
356
357 - On *X86-32* only supports up to 4 bit type parameters. No
358 floating point types are supported.
359 - On *X86-64* only supports up to 10 bit type parameters and 6
360 floating point parameters.
361
362 This calling convention supports `tail call
363 optimization <CodeGenerator.html#id80>`_ but requires both the
364 caller and callee are using it.
365"``cc 11``" - The HiPE calling convention
366 This calling convention has been implemented specifically for use by
367 the `High-Performance Erlang
368 (HiPE) <http://www.it.uu.se/research/group/hipe/>`_ compiler, *the*
369 native code compiler of the `Ericsson's Open Source Erlang/OTP
370 system <http://www.erlang.org/download.shtml>`_. It uses more
371 registers for argument passing than the ordinary C calling
372 convention and defines no callee-saved registers. The calling
373 convention properly supports `tail call
374 optimization <CodeGenerator.html#id80>`_ but requires that both the
375 caller and the callee use it. It uses a *register pinning*
376 mechanism, similar to GHC's convention, for keeping frequently
377 accessed runtime components pinned to specific hardware registers.
378 At the moment only X86 supports this convention (both 32 and 64
379 bit).
380"``cc <n>``" - Numbered convention
381 Any calling convention may be specified by number, allowing
382 target-specific calling conventions to be used. Target specific
383 calling conventions start at 64.
384
385More calling conventions can be added/defined on an as-needed basis, to
386support Pascal conventions or any other well-known target-independent
387convention.
388
389Visibility Styles
390-----------------
391
392All Global Variables and Functions have one of the following visibility
393styles:
394
395"``default``" - Default style
396 On targets that use the ELF object file format, default visibility
397 means that the declaration is visible to other modules and, in
398 shared libraries, means that the declared entity may be overridden.
399 On Darwin, default visibility means that the declaration is visible
400 to other modules. Default visibility corresponds to "external
401 linkage" in the language.
402"``hidden``" - Hidden style
403 Two declarations of an object with hidden visibility refer to the
404 same object if they are in the same shared object. Usually, hidden
405 visibility indicates that the symbol will not be placed into the
406 dynamic symbol table, so no other module (executable or shared
407 library) can reference it directly.
408"``protected``" - Protected style
409 On ELF, protected visibility indicates that the symbol will be
410 placed in the dynamic symbol table, but that references within the
411 defining module will bind to the local symbol. That is, the symbol
412 cannot be overridden by another module.
413
414Named Types
415-----------
416
417LLVM IR allows you to specify name aliases for certain types. This can
418make it easier to read the IR and make the IR more condensed
419(particularly when recursive types are involved). An example of a name
420specification is:
421
422.. code-block:: llvm
423
424 %mytype = type { %mytype*, i32 }
425
426You may give a name to any :ref:`type <typesystem>` except
427":ref:`void <t_void>`". Type name aliases may be used anywhere a type is
428expected with the syntax "%mytype".
429
430Note that type names are aliases for the structural type that they
431indicate, and that you can therefore specify multiple names for the same
432type. This often leads to confusing behavior when dumping out a .ll
433file. Since LLVM IR uses structural typing, the name is not part of the
434type. When printing out LLVM IR, the printer will pick *one name* to
435render all types of a particular shape. This means that if you have code
436where two different source types end up having the same LLVM type, that
437the dumper will sometimes print the "wrong" or unexpected type. This is
438an important design point and isn't going to change.
439
440.. _globalvars:
441
442Global Variables
443----------------
444
445Global variables define regions of memory allocated at compilation time
446instead of run-time. Global variables may optionally be initialized, may
447have an explicit section to be placed in, and may have an optional
448explicit alignment specified.
449
450A variable may be defined as ``thread_local``, which means that it will
451not be shared by threads (each thread will have a separated copy of the
452variable). Not all targets support thread-local variables. Optionally, a
453TLS model may be specified:
454
455``localdynamic``
456 For variables that are only used within the current shared library.
457``initialexec``
458 For variables in modules that will not be loaded dynamically.
459``localexec``
460 For variables defined in the executable and only used within it.
461
462The models correspond to the ELF TLS models; see `ELF Handling For
463Thread-Local Storage <http://people.redhat.com/drepper/tls.pdf>`_ for
464more information on under which circumstances the different models may
465be used. The target may choose a different TLS model if the specified
466model is not supported, or if a better choice of model can be made.
467
Michael Gottesmanf5735882013-01-31 05:48:48 +0000468A variable may be defined as a global ``constant``, which indicates that
Sean Silvaf722b002012-12-07 10:36:55 +0000469the contents of the variable will **never** be modified (enabling better
470optimization, allowing the global data to be placed in the read-only
471section of an executable, etc). Note that variables that need runtime
Michael Gottesman34804872013-01-31 05:44:04 +0000472initialization cannot be marked ``constant`` as there is a store to the
Sean Silvaf722b002012-12-07 10:36:55 +0000473variable.
474
475LLVM explicitly allows *declarations* of global variables to be marked
476constant, even if the final definition of the global is not. This
477capability can be used to enable slightly better optimization of the
478program, but requires the language definition to guarantee that
479optimizations based on the 'constantness' are valid for the translation
480units that do not include the definition.
481
482As SSA values, global variables define pointer values that are in scope
483(i.e. they dominate) all basic blocks in the program. Global variables
484always define a pointer to their "content" type because they describe a
485region of memory, and all memory objects in LLVM are accessed through
486pointers.
487
488Global variables can be marked with ``unnamed_addr`` which indicates
489that the address is not significant, only the content. Constants marked
490like this can be merged with other constants if they have the same
491initializer. Note that a constant with significant address *can* be
492merged with a ``unnamed_addr`` constant, the result being a constant
493whose address is significant.
494
495A global variable may be declared to reside in a target-specific
496numbered address space. For targets that support them, address spaces
497may affect how optimizations are performed and/or what target
498instructions are used to access the variable. The default address space
499is zero. The address space qualifier must precede any other attributes.
500
501LLVM allows an explicit section to be specified for globals. If the
502target supports it, it will emit globals to the section specified.
503
Michael Gottesman6c355ee2013-02-04 03:22:00 +0000504By default, global initializers are optimized by assuming that global
Michael Gottesman42834992013-02-03 09:57:15 +0000505variables defined within the module are not modified from their
506initial values before the start of the global initializer. This is
507true even for variables potentially accessible from outside the
508module, including those with external linkage or appearing in
Michael Gottesmanfa987f02013-02-03 09:57:18 +0000509``@llvm.used``. This assumption may be suppressed by marking the
510variable with ``externally_initialized``.
Michael Gottesman42834992013-02-03 09:57:15 +0000511
Sean Silvaf722b002012-12-07 10:36:55 +0000512An explicit alignment may be specified for a global, which must be a
513power of 2. If not present, or if the alignment is set to zero, the
514alignment of the global is set by the target to whatever it feels
515convenient. If an explicit alignment is specified, the global is forced
516to have exactly that alignment. Targets and optimizers are not allowed
517to over-align the global if the global has an assigned section. In this
518case, the extra alignment could be observable: for example, code could
519assume that the globals are densely packed in their section and try to
520iterate over them as an array, alignment padding would break this
521iteration.
522
523For example, the following defines a global in a numbered address space
524with an initializer, section, and alignment:
525
526.. code-block:: llvm
527
528 @G = addrspace(5) constant float 1.0, section "foo", align 4
529
530The following example defines a thread-local global with the
531``initialexec`` TLS model:
532
533.. code-block:: llvm
534
535 @G = thread_local(initialexec) global i32 0, align 4
536
537.. _functionstructure:
538
539Functions
540---------
541
542LLVM function definitions consist of the "``define``" keyword, an
543optional :ref:`linkage type <linkage>`, an optional :ref:`visibility
544style <visibility>`, an optional :ref:`calling convention <callingconv>`,
545an optional ``unnamed_addr`` attribute, a return type, an optional
546:ref:`parameter attribute <paramattrs>` for the return type, a function
547name, a (possibly empty) argument list (each with optional :ref:`parameter
548attributes <paramattrs>`), optional :ref:`function attributes <fnattrs>`,
549an optional section, an optional alignment, an optional :ref:`garbage
550collector name <gc>`, an opening curly brace, a list of basic blocks,
551and a closing curly brace.
552
553LLVM function declarations consist of the "``declare``" keyword, an
554optional :ref:`linkage type <linkage>`, an optional :ref:`visibility
555style <visibility>`, an optional :ref:`calling convention <callingconv>`,
556an optional ``unnamed_addr`` attribute, a return type, an optional
557:ref:`parameter attribute <paramattrs>` for the return type, a function
558name, a possibly empty list of arguments, an optional alignment, and an
559optional :ref:`garbage collector name <gc>`.
560
561A function definition contains a list of basic blocks, forming the CFG
562(Control Flow Graph) for the function. Each basic block may optionally
563start with a label (giving the basic block a symbol table entry),
564contains a list of instructions, and ends with a
565:ref:`terminator <terminators>` instruction (such as a branch or function
566return).
567
568The first basic block in a function is special in two ways: it is
569immediately executed on entrance to the function, and it is not allowed
570to have predecessor basic blocks (i.e. there can not be any branches to
571the entry block of a function). Because the block can have no
572predecessors, it also cannot have any :ref:`PHI nodes <i_phi>`.
573
574LLVM allows an explicit section to be specified for functions. If the
575target supports it, it will emit functions to the section specified.
576
577An explicit alignment may be specified for a function. If not present,
578or if the alignment is set to zero, the alignment of the function is set
579by the target to whatever it feels convenient. If an explicit alignment
580is specified, the function is forced to have at least that much
581alignment. All alignments must be a power of 2.
582
583If the ``unnamed_addr`` attribute is given, the address is know to not
584be significant and two identical functions can be merged.
585
586Syntax::
587
588 define [linkage] [visibility]
589 [cconv] [ret attrs]
590 <ResultType> @<FunctionName> ([argument list])
591 [fn Attrs] [section "name"] [align N]
592 [gc] { ... }
593
594Aliases
595-------
596
597Aliases act as "second name" for the aliasee value (which can be either
598function, global variable, another alias or bitcast of global value).
599Aliases may have an optional :ref:`linkage type <linkage>`, and an optional
600:ref:`visibility style <visibility>`.
601
602Syntax::
603
604 @<Name> = alias [Linkage] [Visibility] <AliaseeTy> @<Aliasee>
605
606.. _namedmetadatastructure:
607
608Named Metadata
609--------------
610
611Named metadata is a collection of metadata. :ref:`Metadata
612nodes <metadata>` (but not metadata strings) are the only valid
613operands for a named metadata.
614
615Syntax::
616
617 ; Some unnamed metadata nodes, which are referenced by the named metadata.
618 !0 = metadata !{metadata !"zero"}
619 !1 = metadata !{metadata !"one"}
620 !2 = metadata !{metadata !"two"}
621 ; A named metadata.
622 !name = !{!0, !1, !2}
623
624.. _paramattrs:
625
626Parameter Attributes
627--------------------
628
629The return type and each parameter of a function type may have a set of
630*parameter attributes* associated with them. Parameter attributes are
631used to communicate additional information about the result or
632parameters of a function. Parameter attributes are considered to be part
633of the function, not of the function type, so functions with different
634parameter attributes can have the same function type.
635
636Parameter attributes are simple keywords that follow the type specified.
637If multiple parameter attributes are needed, they are space separated.
638For example:
639
640.. code-block:: llvm
641
642 declare i32 @printf(i8* noalias nocapture, ...)
643 declare i32 @atoi(i8 zeroext)
644 declare signext i8 @returns_signed_char()
645
646Note that any attributes for the function result (``nounwind``,
647``readonly``) come immediately after the argument list.
648
649Currently, only the following parameter attributes are defined:
650
651``zeroext``
652 This indicates to the code generator that the parameter or return
653 value should be zero-extended to the extent required by the target's
654 ABI (which is usually 32-bits, but is 8-bits for a i1 on x86-64) by
655 the caller (for a parameter) or the callee (for a return value).
656``signext``
657 This indicates to the code generator that the parameter or return
658 value should be sign-extended to the extent required by the target's
659 ABI (which is usually 32-bits) by the caller (for a parameter) or
660 the callee (for a return value).
661``inreg``
662 This indicates that this parameter or return value should be treated
663 in a special target-dependent fashion during while emitting code for
664 a function call or return (usually, by putting it in a register as
665 opposed to memory, though some targets use it to distinguish between
666 two different kinds of registers). Use of this attribute is
667 target-specific.
668``byval``
669 This indicates that the pointer parameter should really be passed by
670 value to the function. The attribute implies that a hidden copy of
671 the pointee is made between the caller and the callee, so the callee
672 is unable to modify the value in the caller. This attribute is only
673 valid on LLVM pointer arguments. It is generally used to pass
674 structs and arrays by value, but is also valid on pointers to
675 scalars. The copy is considered to belong to the caller not the
676 callee (for example, ``readonly`` functions should not write to
677 ``byval`` parameters). This is not a valid attribute for return
678 values.
679
680 The byval attribute also supports specifying an alignment with the
681 align attribute. It indicates the alignment of the stack slot to
682 form and the known alignment of the pointer specified to the call
683 site. If the alignment is not specified, then the code generator
684 makes a target-specific assumption.
685
686``sret``
687 This indicates that the pointer parameter specifies the address of a
688 structure that is the return value of the function in the source
689 program. This pointer must be guaranteed by the caller to be valid:
Eli Bendersky98202c02013-01-23 22:05:19 +0000690 loads and stores to the structure may be assumed by the callee
Sean Silvaf722b002012-12-07 10:36:55 +0000691 not to trap and to be properly aligned. This may only be applied to
692 the first parameter. This is not a valid attribute for return
693 values.
694``noalias``
695 This indicates that pointer values `*based* <pointeraliasing>` on
696 the argument or return value do not alias pointer values which are
697 not *based* on it, ignoring certain "irrelevant" dependencies. For a
698 call to the parent function, dependencies between memory references
699 from before or after the call and from those during the call are
700 "irrelevant" to the ``noalias`` keyword for the arguments and return
701 value used in that call. The caller shares the responsibility with
702 the callee for ensuring that these requirements are met. For further
703 details, please see the discussion of the NoAlias response in `alias
704 analysis <AliasAnalysis.html#MustMayNo>`_.
705
706 Note that this definition of ``noalias`` is intentionally similar
707 to the definition of ``restrict`` in C99 for function arguments,
708 though it is slightly weaker.
709
710 For function return values, C99's ``restrict`` is not meaningful,
711 while LLVM's ``noalias`` is.
712``nocapture``
713 This indicates that the callee does not make any copies of the
714 pointer that outlive the callee itself. This is not a valid
715 attribute for return values.
716
717.. _nest:
718
719``nest``
720 This indicates that the pointer parameter can be excised using the
721 :ref:`trampoline intrinsics <int_trampoline>`. This is not a valid
722 attribute for return values.
Bill Wendling143d4642013-02-22 00:12:35 +0000723``nobuiltin``
724 This indicates that the callee function at a call site is not
725 recognized as a built-in function. LLVM will retain the original call
726 and not replace it with equivalent code based on the semantics of the
727 built-in function.
Sean Silvaf722b002012-12-07 10:36:55 +0000728
729.. _gc:
730
731Garbage Collector Names
732-----------------------
733
734Each function may specify a garbage collector name, which is simply a
735string:
736
737.. code-block:: llvm
738
739 define void @f() gc "name" { ... }
740
741The compiler declares the supported values of *name*. Specifying a
742collector which will cause the compiler to alter its output in order to
743support the named garbage collection algorithm.
744
Bill Wendling95ce4c22013-02-06 06:52:58 +0000745.. _attrgrp:
746
747Attribute Groups
748----------------
749
750Attribute groups are groups of attributes that are referenced by objects within
751the IR. They are important for keeping ``.ll`` files readable, because a lot of
752functions will use the same set of attributes. In the degenerative case of a
753``.ll`` file that corresponds to a single ``.c`` file, the single attribute
754group will capture the important command line flags used to build that file.
755
756An attribute group is a module-level object. To use an attribute group, an
757object references the attribute group's ID (e.g. ``#37``). An object may refer
758to more than one attribute group. In that situation, the attributes from the
759different groups are merged.
760
761Here is an example of attribute groups for a function that should always be
762inlined, has a stack alignment of 4, and which shouldn't use SSE instructions:
763
764.. code-block:: llvm
765
766 ; Target-independent attributes:
767 #0 = attributes { alwaysinline alignstack=4 }
768
769 ; Target-dependent attributes:
770 #1 = attributes { "no-sse" }
771
772 ; Function @f has attributes: alwaysinline, alignstack=4, and "no-sse".
773 define void @f() #0 #1 { ... }
774
Sean Silvaf722b002012-12-07 10:36:55 +0000775.. _fnattrs:
776
777Function Attributes
778-------------------
779
780Function attributes are set to communicate additional information about
781a function. Function attributes are considered to be part of the
782function, not of the function type, so functions with different function
783attributes can have the same function type.
784
785Function attributes are simple keywords that follow the type specified.
786If multiple attributes are needed, they are space separated. For
787example:
788
789.. code-block:: llvm
790
791 define void @f() noinline { ... }
792 define void @f() alwaysinline { ... }
793 define void @f() alwaysinline optsize { ... }
794 define void @f() optsize { ... }
795
Sean Silvaf722b002012-12-07 10:36:55 +0000796``alignstack(<n>)``
797 This attribute indicates that, when emitting the prologue and
798 epilogue, the backend should forcibly align the stack pointer.
799 Specify the desired alignment, which must be a power of two, in
800 parentheses.
801``alwaysinline``
802 This attribute indicates that the inliner should attempt to inline
803 this function into callers whenever possible, ignoring any active
804 inlining size threshold for this caller.
805``nonlazybind``
806 This attribute suppresses lazy symbol binding for the function. This
807 may make calls to the function faster, at the cost of extra program
808 startup time if the function is not called during program startup.
809``inlinehint``
810 This attribute indicates that the source code contained a hint that
811 inlining this function is desirable (such as the "inline" keyword in
812 C/C++). It is just a hint; it imposes no requirements on the
813 inliner.
814``naked``
815 This attribute disables prologue / epilogue emission for the
816 function. This can have very system-specific consequences.
Bill Wendlingbe5d7472013-02-06 06:22:58 +0000817``noduplicate``
818 This attribute indicates that calls to the function cannot be
819 duplicated. A call to a ``noduplicate`` function may be moved
820 within its parent function, but may not be duplicated within
821 its parent function.
822
823 A function containing a ``noduplicate`` call may still
824 be an inlining candidate, provided that the call is not
825 duplicated by inlining. That implies that the function has
826 internal linkage and only has one call site, so the original
827 call is dead after inlining.
Sean Silvaf722b002012-12-07 10:36:55 +0000828``noimplicitfloat``
829 This attributes disables implicit floating point instructions.
830``noinline``
831 This attribute indicates that the inliner should never inline this
832 function in any situation. This attribute may not be used together
833 with the ``alwaysinline`` attribute.
834``noredzone``
835 This attribute indicates that the code generator should not use a
836 red zone, even if the target-specific ABI normally permits it.
837``noreturn``
838 This function attribute indicates that the function never returns
839 normally. This produces undefined behavior at runtime if the
840 function ever does dynamically return.
841``nounwind``
842 This function attribute indicates that the function never returns
843 with an unwind or exceptional control flow. If the function does
844 unwind, its runtime behavior is undefined.
845``optsize``
846 This attribute suggests that optimization passes and code generator
847 passes make choices that keep the code size of this function low,
848 and otherwise do optimizations specifically to reduce code size.
849``readnone``
850 This attribute indicates that the function computes its result (or
851 decides to unwind an exception) based strictly on its arguments,
852 without dereferencing any pointer arguments or otherwise accessing
853 any mutable state (e.g. memory, control registers, etc) visible to
854 caller functions. It does not write through any pointer arguments
855 (including ``byval`` arguments) and never changes any state visible
856 to callers. This means that it cannot unwind exceptions by calling
857 the ``C++`` exception throwing methods.
858``readonly``
859 This attribute indicates that the function does not write through
860 any pointer arguments (including ``byval`` arguments) or otherwise
861 modify any state (e.g. memory, control registers, etc) visible to
862 caller functions. It may dereference pointer arguments and read
863 state that may be set in the caller. A readonly function always
864 returns the same value (or unwinds an exception identically) when
865 called with the same set of arguments and global state. It cannot
866 unwind an exception by calling the ``C++`` exception throwing
867 methods.
868``returns_twice``
869 This attribute indicates that this function can return twice. The C
870 ``setjmp`` is an example of such a function. The compiler disables
871 some optimizations (like tail calls) in the caller of these
872 functions.
Kostya Serebryany8eec41f2013-02-26 06:58:09 +0000873``sanitize_address``
874 This attribute indicates that AddressSanitizer checks
875 (dynamic address safety analysis) are enabled for this function.
876``sanitize_memory``
877 This attribute indicates that MemorySanitizer checks (dynamic detection
878 of accesses to uninitialized memory) are enabled for this function.
879``sanitize_thread``
880 This attribute indicates that ThreadSanitizer checks
881 (dynamic thread safety analysis) are enabled for this function.
Sean Silvaf722b002012-12-07 10:36:55 +0000882``ssp``
883 This attribute indicates that the function should emit a stack
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +0000884 smashing protector. It is in the form of a "canary" --- a random value
Sean Silvaf722b002012-12-07 10:36:55 +0000885 placed on the stack before the local variables that's checked upon
886 return from the function to see if it has been overwritten. A
887 heuristic is used to determine if a function needs stack protectors
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000888 or not. The heuristic used will enable protectors for functions with:
Dmitri Gribenkod8acb282013-01-29 23:14:41 +0000889
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000890 - Character arrays larger than ``ssp-buffer-size`` (default 8).
891 - Aggregates containing character arrays larger than ``ssp-buffer-size``.
892 - Calls to alloca() with variable sizes or constant sizes greater than
893 ``ssp-buffer-size``.
Sean Silvaf722b002012-12-07 10:36:55 +0000894
895 If a function that has an ``ssp`` attribute is inlined into a
896 function that doesn't have an ``ssp`` attribute, then the resulting
897 function will have an ``ssp`` attribute.
898``sspreq``
899 This attribute indicates that the function should *always* emit a
900 stack smashing protector. This overrides the ``ssp`` function
901 attribute.
902
903 If a function that has an ``sspreq`` attribute is inlined into a
904 function that doesn't have an ``sspreq`` attribute or which has an
Bill Wendling114baee2013-01-23 06:41:41 +0000905 ``ssp`` or ``sspstrong`` attribute, then the resulting function will have
906 an ``sspreq`` attribute.
907``sspstrong``
908 This attribute indicates that the function should emit a stack smashing
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000909 protector. This attribute causes a strong heuristic to be used when
910 determining if a function needs stack protectors. The strong heuristic
911 will enable protectors for functions with:
Dmitri Gribenkod8acb282013-01-29 23:14:41 +0000912
Bill Wendlinge4957fb2013-01-23 06:43:53 +0000913 - Arrays of any size and type
914 - Aggregates containing an array of any size and type.
915 - Calls to alloca().
916 - Local variables that have had their address taken.
917
918 This overrides the ``ssp`` function attribute.
Bill Wendling114baee2013-01-23 06:41:41 +0000919
920 If a function that has an ``sspstrong`` attribute is inlined into a
921 function that doesn't have an ``sspstrong`` attribute, then the
922 resulting function will have an ``sspstrong`` attribute.
Sean Silvaf722b002012-12-07 10:36:55 +0000923``uwtable``
924 This attribute indicates that the ABI being targeted requires that
925 an unwind table entry be produce for this function even if we can
926 show that no exceptions passes by it. This is normally the case for
927 the ELF x86-64 abi, but it can be disabled for some compilation
928 units.
Sean Silvaf722b002012-12-07 10:36:55 +0000929
930.. _moduleasm:
931
932Module-Level Inline Assembly
933----------------------------
934
935Modules may contain "module-level inline asm" blocks, which corresponds
936to the GCC "file scope inline asm" blocks. These blocks are internally
937concatenated by LLVM and treated as a single unit, but may be separated
938in the ``.ll`` file if desired. The syntax is very simple:
939
940.. code-block:: llvm
941
942 module asm "inline asm code goes here"
943 module asm "more can go here"
944
945The strings can contain any character by escaping non-printable
946characters. The escape sequence used is simply "\\xx" where "xx" is the
947two digit hex code for the number.
948
949The inline asm code is simply printed to the machine code .s file when
950assembly code is generated.
951
952Data Layout
953-----------
954
955A module may specify a target specific data layout string that specifies
956how data is to be laid out in memory. The syntax for the data layout is
957simply:
958
959.. code-block:: llvm
960
961 target datalayout = "layout specification"
962
963The *layout specification* consists of a list of specifications
964separated by the minus sign character ('-'). Each specification starts
965with a letter and may include other information after the letter to
966define some aspect of the data layout. The specifications accepted are
967as follows:
968
969``E``
970 Specifies that the target lays out data in big-endian form. That is,
971 the bits with the most significance have the lowest address
972 location.
973``e``
974 Specifies that the target lays out data in little-endian form. That
975 is, the bits with the least significance have the lowest address
976 location.
977``S<size>``
978 Specifies the natural alignment of the stack in bits. Alignment
979 promotion of stack variables is limited to the natural stack
980 alignment to avoid dynamic stack realignment. The stack alignment
981 must be a multiple of 8-bits. If omitted, the natural stack
982 alignment defaults to "unspecified", which does not prevent any
983 alignment promotions.
984``p[n]:<size>:<abi>:<pref>``
985 This specifies the *size* of a pointer and its ``<abi>`` and
986 ``<pref>``\erred alignments for address space ``n``. All sizes are in
987 bits. Specifying the ``<pref>`` alignment is optional. If omitted, the
988 preceding ``:`` should be omitted too. The address space, ``n`` is
989 optional, and if not specified, denotes the default address space 0.
990 The value of ``n`` must be in the range [1,2^23).
991``i<size>:<abi>:<pref>``
992 This specifies the alignment for an integer type of a given bit
993 ``<size>``. The value of ``<size>`` must be in the range [1,2^23).
994``v<size>:<abi>:<pref>``
995 This specifies the alignment for a vector type of a given bit
996 ``<size>``.
997``f<size>:<abi>:<pref>``
998 This specifies the alignment for a floating point type of a given bit
999 ``<size>``. Only values of ``<size>`` that are supported by the target
1000 will work. 32 (float) and 64 (double) are supported on all targets; 80
1001 or 128 (different flavors of long double) are also supported on some
1002 targets.
1003``a<size>:<abi>:<pref>``
1004 This specifies the alignment for an aggregate type of a given bit
1005 ``<size>``.
1006``s<size>:<abi>:<pref>``
1007 This specifies the alignment for a stack object of a given bit
1008 ``<size>``.
1009``n<size1>:<size2>:<size3>...``
1010 This specifies a set of native integer widths for the target CPU in
1011 bits. For example, it might contain ``n32`` for 32-bit PowerPC,
1012 ``n32:64`` for PowerPC 64, or ``n8:16:32:64`` for X86-64. Elements of
1013 this set are considered to support most general arithmetic operations
1014 efficiently.
1015
1016When constructing the data layout for a given target, LLVM starts with a
1017default set of specifications which are then (possibly) overridden by
1018the specifications in the ``datalayout`` keyword. The default
1019specifications are given in this list:
1020
1021- ``E`` - big endian
1022- ``p:64:64:64`` - 64-bit pointers with 64-bit alignment
Patrik Hagglund3b5f0b02013-01-30 09:02:06 +00001023- ``S0`` - natural stack alignment is unspecified
Sean Silvaf722b002012-12-07 10:36:55 +00001024- ``i1:8:8`` - i1 is 8-bit (byte) aligned
1025- ``i8:8:8`` - i8 is 8-bit (byte) aligned
1026- ``i16:16:16`` - i16 is 16-bit aligned
1027- ``i32:32:32`` - i32 is 32-bit aligned
1028- ``i64:32:64`` - i64 has ABI alignment of 32-bits but preferred
1029 alignment of 64-bits
Patrik Hagglund3b5f0b02013-01-30 09:02:06 +00001030- ``f16:16:16`` - half is 16-bit aligned
Sean Silvaf722b002012-12-07 10:36:55 +00001031- ``f32:32:32`` - float is 32-bit aligned
1032- ``f64:64:64`` - double is 64-bit aligned
Patrik Hagglund3b5f0b02013-01-30 09:02:06 +00001033- ``f128:128:128`` - quad is 128-bit aligned
Sean Silvaf722b002012-12-07 10:36:55 +00001034- ``v64:64:64`` - 64-bit vector is 64-bit aligned
1035- ``v128:128:128`` - 128-bit vector is 128-bit aligned
Patrik Hagglund3b5f0b02013-01-30 09:02:06 +00001036- ``a0:0:64`` - aggregates are 64-bit aligned
Sean Silvaf722b002012-12-07 10:36:55 +00001037
1038When LLVM is determining the alignment for a given type, it uses the
1039following rules:
1040
1041#. If the type sought is an exact match for one of the specifications,
1042 that specification is used.
1043#. If no match is found, and the type sought is an integer type, then
1044 the smallest integer type that is larger than the bitwidth of the
1045 sought type is used. If none of the specifications are larger than
1046 the bitwidth then the largest integer type is used. For example,
1047 given the default specifications above, the i7 type will use the
1048 alignment of i8 (next largest) while both i65 and i256 will use the
1049 alignment of i64 (largest specified).
1050#. If no match is found, and the type sought is a vector type, then the
1051 largest vector type that is smaller than the sought vector type will
1052 be used as a fall back. This happens because <128 x double> can be
1053 implemented in terms of 64 <2 x double>, for example.
1054
1055The function of the data layout string may not be what you expect.
1056Notably, this is not a specification from the frontend of what alignment
1057the code generator should use.
1058
1059Instead, if specified, the target data layout is required to match what
1060the ultimate *code generator* expects. This string is used by the
1061mid-level optimizers to improve code, and this only works if it matches
1062what the ultimate code generator uses. If you would like to generate IR
1063that does not embed this target-specific detail into the IR, then you
1064don't have to specify the string. This will disable some optimizations
1065that require precise layout information, but this also prevents those
1066optimizations from introducing target specificity into the IR.
1067
1068.. _pointeraliasing:
1069
1070Pointer Aliasing Rules
1071----------------------
1072
1073Any memory access must be done through a pointer value associated with
1074an address range of the memory access, otherwise the behavior is
1075undefined. Pointer values are associated with address ranges according
1076to the following rules:
1077
1078- A pointer value is associated with the addresses associated with any
1079 value it is *based* on.
1080- An address of a global variable is associated with the address range
1081 of the variable's storage.
1082- The result value of an allocation instruction is associated with the
1083 address range of the allocated storage.
1084- A null pointer in the default address-space is associated with no
1085 address.
1086- An integer constant other than zero or a pointer value returned from
1087 a function not defined within LLVM may be associated with address
1088 ranges allocated through mechanisms other than those provided by
1089 LLVM. Such ranges shall not overlap with any ranges of addresses
1090 allocated by mechanisms provided by LLVM.
1091
1092A pointer value is *based* on another pointer value according to the
1093following rules:
1094
1095- A pointer value formed from a ``getelementptr`` operation is *based*
1096 on the first operand of the ``getelementptr``.
1097- The result value of a ``bitcast`` is *based* on the operand of the
1098 ``bitcast``.
1099- A pointer value formed by an ``inttoptr`` is *based* on all pointer
1100 values that contribute (directly or indirectly) to the computation of
1101 the pointer's value.
1102- The "*based* on" relationship is transitive.
1103
1104Note that this definition of *"based"* is intentionally similar to the
1105definition of *"based"* in C99, though it is slightly weaker.
1106
1107LLVM IR does not associate types with memory. The result type of a
1108``load`` merely indicates the size and alignment of the memory from
1109which to load, as well as the interpretation of the value. The first
1110operand type of a ``store`` similarly only indicates the size and
1111alignment of the store.
1112
1113Consequently, type-based alias analysis, aka TBAA, aka
1114``-fstrict-aliasing``, is not applicable to general unadorned LLVM IR.
1115:ref:`Metadata <metadata>` may be used to encode additional information
1116which specialized optimization passes may use to implement type-based
1117alias analysis.
1118
1119.. _volatile:
1120
1121Volatile Memory Accesses
1122------------------------
1123
1124Certain memory accesses, such as :ref:`load <i_load>`'s,
1125:ref:`store <i_store>`'s, and :ref:`llvm.memcpy <int_memcpy>`'s may be
1126marked ``volatile``. The optimizers must not change the number of
1127volatile operations or change their order of execution relative to other
1128volatile operations. The optimizers *may* change the order of volatile
1129operations relative to non-volatile operations. This is not Java's
1130"volatile" and has no cross-thread synchronization behavior.
1131
Andrew Trick9a6dd022013-01-30 21:19:35 +00001132IR-level volatile loads and stores cannot safely be optimized into
1133llvm.memcpy or llvm.memmove intrinsics even when those intrinsics are
1134flagged volatile. Likewise, the backend should never split or merge
1135target-legal volatile load/store instructions.
1136
Andrew Trick946317d2013-01-31 00:49:39 +00001137.. admonition:: Rationale
1138
1139 Platforms may rely on volatile loads and stores of natively supported
1140 data width to be executed as single instruction. For example, in C
1141 this holds for an l-value of volatile primitive type with native
1142 hardware support, but not necessarily for aggregate types. The
1143 frontend upholds these expectations, which are intentionally
1144 unspecified in the IR. The rules above ensure that IR transformation
1145 do not violate the frontend's contract with the language.
1146
Sean Silvaf722b002012-12-07 10:36:55 +00001147.. _memmodel:
1148
1149Memory Model for Concurrent Operations
1150--------------------------------------
1151
1152The LLVM IR does not define any way to start parallel threads of
1153execution or to register signal handlers. Nonetheless, there are
1154platform-specific ways to create them, and we define LLVM IR's behavior
1155in their presence. This model is inspired by the C++0x memory model.
1156
1157For a more informal introduction to this model, see the :doc:`Atomics`.
1158
1159We define a *happens-before* partial order as the least partial order
1160that
1161
1162- Is a superset of single-thread program order, and
1163- When a *synchronizes-with* ``b``, includes an edge from ``a`` to
1164 ``b``. *Synchronizes-with* pairs are introduced by platform-specific
1165 techniques, like pthread locks, thread creation, thread joining,
1166 etc., and by atomic instructions. (See also :ref:`Atomic Memory Ordering
1167 Constraints <ordering>`).
1168
1169Note that program order does not introduce *happens-before* edges
1170between a thread and signals executing inside that thread.
1171
1172Every (defined) read operation (load instructions, memcpy, atomic
1173loads/read-modify-writes, etc.) R reads a series of bytes written by
1174(defined) write operations (store instructions, atomic
1175stores/read-modify-writes, memcpy, etc.). For the purposes of this
1176section, initialized globals are considered to have a write of the
1177initializer which is atomic and happens before any other read or write
1178of the memory in question. For each byte of a read R, R\ :sub:`byte`
1179may see any write to the same byte, except:
1180
1181- If write\ :sub:`1` happens before write\ :sub:`2`, and
1182 write\ :sub:`2` happens before R\ :sub:`byte`, then
1183 R\ :sub:`byte` does not see write\ :sub:`1`.
1184- If R\ :sub:`byte` happens before write\ :sub:`3`, then
1185 R\ :sub:`byte` does not see write\ :sub:`3`.
1186
1187Given that definition, R\ :sub:`byte` is defined as follows:
1188
1189- If R is volatile, the result is target-dependent. (Volatile is
1190 supposed to give guarantees which can support ``sig_atomic_t`` in
1191 C/C++, and may be used for accesses to addresses which do not behave
1192 like normal memory. It does not generally provide cross-thread
1193 synchronization.)
1194- Otherwise, if there is no write to the same byte that happens before
1195 R\ :sub:`byte`, R\ :sub:`byte` returns ``undef`` for that byte.
1196- Otherwise, if R\ :sub:`byte` may see exactly one write,
1197 R\ :sub:`byte` returns the value written by that write.
1198- Otherwise, if R is atomic, and all the writes R\ :sub:`byte` may
1199 see are atomic, it chooses one of the values written. See the :ref:`Atomic
1200 Memory Ordering Constraints <ordering>` section for additional
1201 constraints on how the choice is made.
1202- Otherwise R\ :sub:`byte` returns ``undef``.
1203
1204R returns the value composed of the series of bytes it read. This
1205implies that some bytes within the value may be ``undef`` **without**
1206the entire value being ``undef``. Note that this only defines the
1207semantics of the operation; it doesn't mean that targets will emit more
1208than one instruction to read the series of bytes.
1209
1210Note that in cases where none of the atomic intrinsics are used, this
1211model places only one restriction on IR transformations on top of what
1212is required for single-threaded execution: introducing a store to a byte
1213which might not otherwise be stored is not allowed in general.
1214(Specifically, in the case where another thread might write to and read
1215from an address, introducing a store can change a load that may see
1216exactly one write into a load that may see multiple writes.)
1217
1218.. _ordering:
1219
1220Atomic Memory Ordering Constraints
1221----------------------------------
1222
1223Atomic instructions (:ref:`cmpxchg <i_cmpxchg>`,
1224:ref:`atomicrmw <i_atomicrmw>`, :ref:`fence <i_fence>`,
1225:ref:`atomic load <i_load>`, and :ref:`atomic store <i_store>`) take
1226an ordering parameter that determines which other atomic instructions on
1227the same address they *synchronize with*. These semantics are borrowed
1228from Java and C++0x, but are somewhat more colloquial. If these
1229descriptions aren't precise enough, check those specs (see spec
1230references in the :doc:`atomics guide <Atomics>`).
1231:ref:`fence <i_fence>` instructions treat these orderings somewhat
1232differently since they don't take an address. See that instruction's
1233documentation for details.
1234
1235For a simpler introduction to the ordering constraints, see the
1236:doc:`Atomics`.
1237
1238``unordered``
1239 The set of values that can be read is governed by the happens-before
1240 partial order. A value cannot be read unless some operation wrote
1241 it. This is intended to provide a guarantee strong enough to model
1242 Java's non-volatile shared variables. This ordering cannot be
1243 specified for read-modify-write operations; it is not strong enough
1244 to make them atomic in any interesting way.
1245``monotonic``
1246 In addition to the guarantees of ``unordered``, there is a single
1247 total order for modifications by ``monotonic`` operations on each
1248 address. All modification orders must be compatible with the
1249 happens-before order. There is no guarantee that the modification
1250 orders can be combined to a global total order for the whole program
1251 (and this often will not be possible). The read in an atomic
1252 read-modify-write operation (:ref:`cmpxchg <i_cmpxchg>` and
1253 :ref:`atomicrmw <i_atomicrmw>`) reads the value in the modification
1254 order immediately before the value it writes. If one atomic read
1255 happens before another atomic read of the same address, the later
1256 read must see the same value or a later value in the address's
1257 modification order. This disallows reordering of ``monotonic`` (or
1258 stronger) operations on the same address. If an address is written
1259 ``monotonic``-ally by one thread, and other threads ``monotonic``-ally
1260 read that address repeatedly, the other threads must eventually see
1261 the write. This corresponds to the C++0x/C1x
1262 ``memory_order_relaxed``.
1263``acquire``
1264 In addition to the guarantees of ``monotonic``, a
1265 *synchronizes-with* edge may be formed with a ``release`` operation.
1266 This is intended to model C++'s ``memory_order_acquire``.
1267``release``
1268 In addition to the guarantees of ``monotonic``, if this operation
1269 writes a value which is subsequently read by an ``acquire``
1270 operation, it *synchronizes-with* that operation. (This isn't a
1271 complete description; see the C++0x definition of a release
1272 sequence.) This corresponds to the C++0x/C1x
1273 ``memory_order_release``.
1274``acq_rel`` (acquire+release)
1275 Acts as both an ``acquire`` and ``release`` operation on its
1276 address. This corresponds to the C++0x/C1x ``memory_order_acq_rel``.
1277``seq_cst`` (sequentially consistent)
1278 In addition to the guarantees of ``acq_rel`` (``acquire`` for an
1279 operation which only reads, ``release`` for an operation which only
1280 writes), there is a global total order on all
1281 sequentially-consistent operations on all addresses, which is
1282 consistent with the *happens-before* partial order and with the
1283 modification orders of all the affected addresses. Each
1284 sequentially-consistent read sees the last preceding write to the
1285 same address in this global order. This corresponds to the C++0x/C1x
1286 ``memory_order_seq_cst`` and Java volatile.
1287
1288.. _singlethread:
1289
1290If an atomic operation is marked ``singlethread``, it only *synchronizes
1291with* or participates in modification and seq\_cst total orderings with
1292other operations running in the same thread (for example, in signal
1293handlers).
1294
1295.. _fastmath:
1296
1297Fast-Math Flags
1298---------------
1299
1300LLVM IR floating-point binary ops (:ref:`fadd <i_fadd>`,
1301:ref:`fsub <i_fsub>`, :ref:`fmul <i_fmul>`, :ref:`fdiv <i_fdiv>`,
1302:ref:`frem <i_frem>`) have the following flags that can set to enable
1303otherwise unsafe floating point operations
1304
1305``nnan``
1306 No NaNs - Allow optimizations to assume the arguments and result are not
1307 NaN. Such optimizations are required to retain defined behavior over
1308 NaNs, but the value of the result is undefined.
1309
1310``ninf``
1311 No Infs - Allow optimizations to assume the arguments and result are not
1312 +/-Inf. Such optimizations are required to retain defined behavior over
1313 +/-Inf, but the value of the result is undefined.
1314
1315``nsz``
1316 No Signed Zeros - Allow optimizations to treat the sign of a zero
1317 argument or result as insignificant.
1318
1319``arcp``
1320 Allow Reciprocal - Allow optimizations to use the reciprocal of an
1321 argument rather than perform division.
1322
1323``fast``
1324 Fast - Allow algebraically equivalent transformations that may
1325 dramatically change results in floating point (e.g. reassociate). This
1326 flag implies all the others.
1327
1328.. _typesystem:
1329
1330Type System
1331===========
1332
1333The LLVM type system is one of the most important features of the
1334intermediate representation. Being typed enables a number of
1335optimizations to be performed on the intermediate representation
1336directly, without having to do extra analyses on the side before the
1337transformation. A strong type system makes it easier to read the
1338generated code and enables novel analyses and transformations that are
1339not feasible to perform on normal three address code representations.
1340
1341Type Classifications
1342--------------------
1343
1344The types fall into a few useful classifications:
1345
1346
1347.. list-table::
1348 :header-rows: 1
1349
1350 * - Classification
1351 - Types
1352
1353 * - :ref:`integer <t_integer>`
1354 - ``i1``, ``i2``, ``i3``, ... ``i8``, ... ``i16``, ... ``i32``, ...
1355 ``i64``, ...
1356
1357 * - :ref:`floating point <t_floating>`
1358 - ``half``, ``float``, ``double``, ``x86_fp80``, ``fp128``,
1359 ``ppc_fp128``
1360
1361
1362 * - first class
1363
1364 .. _t_firstclass:
1365
1366 - :ref:`integer <t_integer>`, :ref:`floating point <t_floating>`,
1367 :ref:`pointer <t_pointer>`, :ref:`vector <t_vector>`,
1368 :ref:`structure <t_struct>`, :ref:`array <t_array>`,
1369 :ref:`label <t_label>`, :ref:`metadata <t_metadata>`.
1370
1371 * - :ref:`primitive <t_primitive>`
1372 - :ref:`label <t_label>`,
1373 :ref:`void <t_void>`,
1374 :ref:`integer <t_integer>`,
1375 :ref:`floating point <t_floating>`,
1376 :ref:`x86mmx <t_x86mmx>`,
1377 :ref:`metadata <t_metadata>`.
1378
1379 * - :ref:`derived <t_derived>`
1380 - :ref:`array <t_array>`,
1381 :ref:`function <t_function>`,
1382 :ref:`pointer <t_pointer>`,
1383 :ref:`structure <t_struct>`,
1384 :ref:`vector <t_vector>`,
1385 :ref:`opaque <t_opaque>`.
1386
1387The :ref:`first class <t_firstclass>` types are perhaps the most important.
1388Values of these types are the only ones which can be produced by
1389instructions.
1390
1391.. _t_primitive:
1392
1393Primitive Types
1394---------------
1395
1396The primitive types are the fundamental building blocks of the LLVM
1397system.
1398
1399.. _t_integer:
1400
1401Integer Type
1402^^^^^^^^^^^^
1403
1404Overview:
1405"""""""""
1406
1407The integer type is a very simple type that simply specifies an
1408arbitrary bit width for the integer type desired. Any bit width from 1
1409bit to 2\ :sup:`23`\ -1 (about 8 million) can be specified.
1410
1411Syntax:
1412"""""""
1413
1414::
1415
1416 iN
1417
1418The number of bits the integer will occupy is specified by the ``N``
1419value.
1420
1421Examples:
1422"""""""""
1423
1424+----------------+------------------------------------------------+
1425| ``i1`` | a single-bit integer. |
1426+----------------+------------------------------------------------+
1427| ``i32`` | a 32-bit integer. |
1428+----------------+------------------------------------------------+
1429| ``i1942652`` | a really big integer of over 1 million bits. |
1430+----------------+------------------------------------------------+
1431
1432.. _t_floating:
1433
1434Floating Point Types
1435^^^^^^^^^^^^^^^^^^^^
1436
1437.. list-table::
1438 :header-rows: 1
1439
1440 * - Type
1441 - Description
1442
1443 * - ``half``
1444 - 16-bit floating point value
1445
1446 * - ``float``
1447 - 32-bit floating point value
1448
1449 * - ``double``
1450 - 64-bit floating point value
1451
1452 * - ``fp128``
1453 - 128-bit floating point value (112-bit mantissa)
1454
1455 * - ``x86_fp80``
1456 - 80-bit floating point value (X87)
1457
1458 * - ``ppc_fp128``
1459 - 128-bit floating point value (two 64-bits)
1460
1461.. _t_x86mmx:
1462
1463X86mmx Type
1464^^^^^^^^^^^
1465
1466Overview:
1467"""""""""
1468
1469The x86mmx type represents a value held in an MMX register on an x86
1470machine. The operations allowed on it are quite limited: parameters and
1471return values, load and store, and bitcast. User-specified MMX
1472instructions are represented as intrinsic or asm calls with arguments
1473and/or results of this type. There are no arrays, vectors or constants
1474of this type.
1475
1476Syntax:
1477"""""""
1478
1479::
1480
1481 x86mmx
1482
1483.. _t_void:
1484
1485Void Type
1486^^^^^^^^^
1487
1488Overview:
1489"""""""""
1490
1491The void type does not represent any value and has no size.
1492
1493Syntax:
1494"""""""
1495
1496::
1497
1498 void
1499
1500.. _t_label:
1501
1502Label Type
1503^^^^^^^^^^
1504
1505Overview:
1506"""""""""
1507
1508The label type represents code labels.
1509
1510Syntax:
1511"""""""
1512
1513::
1514
1515 label
1516
1517.. _t_metadata:
1518
1519Metadata Type
1520^^^^^^^^^^^^^
1521
1522Overview:
1523"""""""""
1524
1525The metadata type represents embedded metadata. No derived types may be
1526created from metadata except for :ref:`function <t_function>` arguments.
1527
1528Syntax:
1529"""""""
1530
1531::
1532
1533 metadata
1534
1535.. _t_derived:
1536
1537Derived Types
1538-------------
1539
1540The real power in LLVM comes from the derived types in the system. This
1541is what allows a programmer to represent arrays, functions, pointers,
1542and other useful types. Each of these types contain one or more element
1543types which may be a primitive type, or another derived type. For
1544example, it is possible to have a two dimensional array, using an array
1545as the element type of another array.
1546
1547.. _t_aggregate:
1548
1549Aggregate Types
1550^^^^^^^^^^^^^^^
1551
1552Aggregate Types are a subset of derived types that can contain multiple
1553member types. :ref:`Arrays <t_array>` and :ref:`structs <t_struct>` are
1554aggregate types. :ref:`Vectors <t_vector>` are not considered to be
1555aggregate types.
1556
1557.. _t_array:
1558
1559Array Type
1560^^^^^^^^^^
1561
1562Overview:
1563"""""""""
1564
1565The array type is a very simple derived type that arranges elements
1566sequentially in memory. The array type requires a size (number of
1567elements) and an underlying data type.
1568
1569Syntax:
1570"""""""
1571
1572::
1573
1574 [<# elements> x <elementtype>]
1575
1576The number of elements is a constant integer value; ``elementtype`` may
1577be any type with a size.
1578
1579Examples:
1580"""""""""
1581
1582+------------------+--------------------------------------+
1583| ``[40 x i32]`` | Array of 40 32-bit integer values. |
1584+------------------+--------------------------------------+
1585| ``[41 x i32]`` | Array of 41 32-bit integer values. |
1586+------------------+--------------------------------------+
1587| ``[4 x i8]`` | Array of 4 8-bit integer values. |
1588+------------------+--------------------------------------+
1589
1590Here are some examples of multidimensional arrays:
1591
1592+-----------------------------+----------------------------------------------------------+
1593| ``[3 x [4 x i32]]`` | 3x4 array of 32-bit integer values. |
1594+-----------------------------+----------------------------------------------------------+
1595| ``[12 x [10 x float]]`` | 12x10 array of single precision floating point values. |
1596+-----------------------------+----------------------------------------------------------+
1597| ``[2 x [3 x [4 x i16]]]`` | 2x3x4 array of 16-bit integer values. |
1598+-----------------------------+----------------------------------------------------------+
1599
1600There is no restriction on indexing beyond the end of the array implied
1601by a static type (though there are restrictions on indexing beyond the
1602bounds of an allocated object in some cases). This means that
1603single-dimension 'variable sized array' addressing can be implemented in
1604LLVM with a zero length array type. An implementation of 'pascal style
1605arrays' in LLVM could use the type "``{ i32, [0 x float]}``", for
1606example.
1607
1608.. _t_function:
1609
1610Function Type
1611^^^^^^^^^^^^^
1612
1613Overview:
1614"""""""""
1615
1616The function type can be thought of as a function signature. It consists
1617of a return type and a list of formal parameter types. The return type
1618of a function type is a first class type or a void type.
1619
1620Syntax:
1621"""""""
1622
1623::
1624
1625 <returntype> (<parameter list>)
1626
1627...where '``<parameter list>``' is a comma-separated list of type
1628specifiers. Optionally, the parameter list may include a type ``...``,
1629which indicates that the function takes a variable number of arguments.
1630Variable argument functions can access their arguments with the
1631:ref:`variable argument handling intrinsic <int_varargs>` functions.
1632'``<returntype>``' is any type except :ref:`label <t_label>`.
1633
1634Examples:
1635"""""""""
1636
1637+---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1638| ``i32 (i32)`` | function taking an ``i32``, returning an ``i32`` |
1639+---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Daniel Dunbar3389dbc2013-01-17 18:57:32 +00001640| ``float (i16, i32 *) *`` | :ref:`Pointer <t_pointer>` to a function that takes an ``i16`` and a :ref:`pointer <t_pointer>` to ``i32``, returning ``float``. |
Sean Silvaf722b002012-12-07 10:36:55 +00001641+---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1642| ``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. |
1643+---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1644| ``{i32, i32} (i32)`` | A function taking an ``i32``, returning a :ref:`structure <t_struct>` containing two ``i32`` values |
1645+---------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1646
1647.. _t_struct:
1648
1649Structure Type
1650^^^^^^^^^^^^^^
1651
1652Overview:
1653"""""""""
1654
1655The structure type is used to represent a collection of data members
1656together in memory. The elements of a structure may be any type that has
1657a size.
1658
1659Structures in memory are accessed using '``load``' and '``store``' by
1660getting a pointer to a field with the '``getelementptr``' instruction.
1661Structures in registers are accessed using the '``extractvalue``' and
1662'``insertvalue``' instructions.
1663
1664Structures may optionally be "packed" structures, which indicate that
1665the alignment of the struct is one byte, and that there is no padding
1666between the elements. In non-packed structs, padding between field types
1667is inserted as defined by the DataLayout string in the module, which is
1668required to match what the underlying code generator expects.
1669
1670Structures can either be "literal" or "identified". A literal structure
1671is defined inline with other types (e.g. ``{i32, i32}*``) whereas
1672identified types are always defined at the top level with a name.
1673Literal types are uniqued by their contents and can never be recursive
1674or opaque since there is no way to write one. Identified types can be
1675recursive, can be opaqued, and are never uniqued.
1676
1677Syntax:
1678"""""""
1679
1680::
1681
1682 %T1 = type { <type list> } ; Identified normal struct type
1683 %T2 = type <{ <type list> }> ; Identified packed struct type
1684
1685Examples:
1686"""""""""
1687
1688+------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1689| ``{ i32, i32, i32 }`` | A triple of three ``i32`` values |
1690+------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Daniel Dunbar3389dbc2013-01-17 18:57:32 +00001691| ``{ 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``. |
Sean Silvaf722b002012-12-07 10:36:55 +00001692+------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1693| ``<{ i8, i32 }>`` | A packed struct known to be 5 bytes in size. |
1694+------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1695
1696.. _t_opaque:
1697
1698Opaque Structure Types
1699^^^^^^^^^^^^^^^^^^^^^^
1700
1701Overview:
1702"""""""""
1703
1704Opaque structure types are used to represent named structure types that
1705do not have a body specified. This corresponds (for example) to the C
1706notion of a forward declared structure.
1707
1708Syntax:
1709"""""""
1710
1711::
1712
1713 %X = type opaque
1714 %52 = type opaque
1715
1716Examples:
1717"""""""""
1718
1719+--------------+-------------------+
1720| ``opaque`` | An opaque type. |
1721+--------------+-------------------+
1722
1723.. _t_pointer:
1724
1725Pointer Type
1726^^^^^^^^^^^^
1727
1728Overview:
1729"""""""""
1730
1731The pointer type is used to specify memory locations. Pointers are
1732commonly used to reference objects in memory.
1733
1734Pointer types may have an optional address space attribute defining the
1735numbered address space where the pointed-to object resides. The default
1736address space is number zero. The semantics of non-zero address spaces
1737are target-specific.
1738
1739Note that LLVM does not permit pointers to void (``void*``) nor does it
1740permit pointers to labels (``label*``). Use ``i8*`` instead.
1741
1742Syntax:
1743"""""""
1744
1745::
1746
1747 <type> *
1748
1749Examples:
1750"""""""""
1751
1752+-------------------------+--------------------------------------------------------------------------------------------------------------+
1753| ``[4 x i32]*`` | A :ref:`pointer <t_pointer>` to :ref:`array <t_array>` of four ``i32`` values. |
1754+-------------------------+--------------------------------------------------------------------------------------------------------------+
1755| ``i32 (i32*) *`` | A :ref:`pointer <t_pointer>` to a :ref:`function <t_function>` that takes an ``i32*``, returning an ``i32``. |
1756+-------------------------+--------------------------------------------------------------------------------------------------------------+
1757| ``i32 addrspace(5)*`` | A :ref:`pointer <t_pointer>` to an ``i32`` value that resides in address space #5. |
1758+-------------------------+--------------------------------------------------------------------------------------------------------------+
1759
1760.. _t_vector:
1761
1762Vector Type
1763^^^^^^^^^^^
1764
1765Overview:
1766"""""""""
1767
1768A vector type is a simple derived type that represents a vector of
1769elements. Vector types are used when multiple primitive data are
1770operated in parallel using a single instruction (SIMD). A vector type
1771requires a size (number of elements) and an underlying primitive data
1772type. Vector types are considered :ref:`first class <t_firstclass>`.
1773
1774Syntax:
1775"""""""
1776
1777::
1778
1779 < <# elements> x <elementtype> >
1780
1781The number of elements is a constant integer value larger than 0;
1782elementtype may be any integer or floating point type, or a pointer to
1783these types. Vectors of size zero are not allowed.
1784
1785Examples:
1786"""""""""
1787
1788+-------------------+--------------------------------------------------+
1789| ``<4 x i32>`` | Vector of 4 32-bit integer values. |
1790+-------------------+--------------------------------------------------+
1791| ``<8 x float>`` | Vector of 8 32-bit floating-point values. |
1792+-------------------+--------------------------------------------------+
1793| ``<2 x i64>`` | Vector of 2 64-bit integer values. |
1794+-------------------+--------------------------------------------------+
1795| ``<4 x i64*>`` | Vector of 4 pointers to 64-bit integer values. |
1796+-------------------+--------------------------------------------------+
1797
1798Constants
1799=========
1800
1801LLVM has several different basic types of constants. This section
1802describes them all and their syntax.
1803
1804Simple Constants
1805----------------
1806
1807**Boolean constants**
1808 The two strings '``true``' and '``false``' are both valid constants
1809 of the ``i1`` type.
1810**Integer constants**
1811 Standard integers (such as '4') are constants of the
1812 :ref:`integer <t_integer>` type. Negative numbers may be used with
1813 integer types.
1814**Floating point constants**
1815 Floating point constants use standard decimal notation (e.g.
1816 123.421), exponential notation (e.g. 1.23421e+2), or a more precise
1817 hexadecimal notation (see below). The assembler requires the exact
1818 decimal value of a floating-point constant. For example, the
1819 assembler accepts 1.25 but rejects 1.3 because 1.3 is a repeating
1820 decimal in binary. Floating point constants must have a :ref:`floating
1821 point <t_floating>` type.
1822**Null pointer constants**
1823 The identifier '``null``' is recognized as a null pointer constant
1824 and must be of :ref:`pointer type <t_pointer>`.
1825
1826The one non-intuitive notation for constants is the hexadecimal form of
1827floating point constants. For example, the form
1828'``double 0x432ff973cafa8000``' is equivalent to (but harder to read
1829than) '``double 4.5e+15``'. The only time hexadecimal floating point
1830constants are required (and the only time that they are generated by the
1831disassembler) is when a floating point constant must be emitted but it
1832cannot be represented as a decimal floating point number in a reasonable
1833number of digits. For example, NaN's, infinities, and other special
1834values are represented in their IEEE hexadecimal format so that assembly
1835and disassembly do not cause any bits to change in the constants.
1836
1837When using the hexadecimal form, constants of types half, float, and
1838double are represented using the 16-digit form shown above (which
1839matches the IEEE754 representation for double); half and float values
Dmitri Gribenkoc3c8d2a2013-01-16 23:40:37 +00001840must, however, be exactly representable as IEEE 754 half and single
Sean Silvaf722b002012-12-07 10:36:55 +00001841precision, respectively. Hexadecimal format is always used for long
1842double, and there are three forms of long double. The 80-bit format used
1843by x86 is represented as ``0xK`` followed by 20 hexadecimal digits. The
1844128-bit format used by PowerPC (two adjacent doubles) is represented by
1845``0xM`` followed by 32 hexadecimal digits. The IEEE 128-bit format is
1846represented by ``0xL`` followed by 32 hexadecimal digits; no currently
1847supported target uses this format. Long doubles will only work if they
1848match the long double format on your target. The IEEE 16-bit format
1849(half precision) is represented by ``0xH`` followed by 4 hexadecimal
1850digits. All hexadecimal formats are big-endian (sign bit at the left).
1851
1852There are no constants of type x86mmx.
1853
1854Complex Constants
1855-----------------
1856
1857Complex constants are a (potentially recursive) combination of simple
1858constants and smaller complex constants.
1859
1860**Structure constants**
1861 Structure constants are represented with notation similar to
1862 structure type definitions (a comma separated list of elements,
1863 surrounded by braces (``{}``)). For example:
1864 "``{ i32 4, float 17.0, i32* @G }``", where "``@G``" is declared as
1865 "``@G = external global i32``". Structure constants must have
1866 :ref:`structure type <t_struct>`, and the number and types of elements
1867 must match those specified by the type.
1868**Array constants**
1869 Array constants are represented with notation similar to array type
1870 definitions (a comma separated list of elements, surrounded by
1871 square brackets (``[]``)). For example:
1872 "``[ i32 42, i32 11, i32 74 ]``". Array constants must have
1873 :ref:`array type <t_array>`, and the number and types of elements must
1874 match those specified by the type.
1875**Vector constants**
1876 Vector constants are represented with notation similar to vector
1877 type definitions (a comma separated list of elements, surrounded by
1878 less-than/greater-than's (``<>``)). For example:
1879 "``< i32 42, i32 11, i32 74, i32 100 >``". Vector constants
1880 must have :ref:`vector type <t_vector>`, and the number and types of
1881 elements must match those specified by the type.
1882**Zero initialization**
1883 The string '``zeroinitializer``' can be used to zero initialize a
1884 value to zero of *any* type, including scalar and
1885 :ref:`aggregate <t_aggregate>` types. This is often used to avoid
1886 having to print large zero initializers (e.g. for large arrays) and
1887 is always exactly equivalent to using explicit zero initializers.
1888**Metadata node**
1889 A metadata node is a structure-like constant with :ref:`metadata
1890 type <t_metadata>`. For example:
1891 "``metadata !{ i32 0, metadata !"test" }``". Unlike other
1892 constants that are meant to be interpreted as part of the
1893 instruction stream, metadata is a place to attach additional
1894 information such as debug info.
1895
1896Global Variable and Function Addresses
1897--------------------------------------
1898
1899The addresses of :ref:`global variables <globalvars>` and
1900:ref:`functions <functionstructure>` are always implicitly valid
1901(link-time) constants. These constants are explicitly referenced when
1902the :ref:`identifier for the global <identifiers>` is used and always have
1903:ref:`pointer <t_pointer>` type. For example, the following is a legal LLVM
1904file:
1905
1906.. code-block:: llvm
1907
1908 @X = global i32 17
1909 @Y = global i32 42
1910 @Z = global [2 x i32*] [ i32* @X, i32* @Y ]
1911
1912.. _undefvalues:
1913
1914Undefined Values
1915----------------
1916
1917The string '``undef``' can be used anywhere a constant is expected, and
1918indicates that the user of the value may receive an unspecified
1919bit-pattern. Undefined values may be of any type (other than '``label``'
1920or '``void``') and be used anywhere a constant is permitted.
1921
1922Undefined values are useful because they indicate to the compiler that
1923the program is well defined no matter what value is used. This gives the
1924compiler more freedom to optimize. Here are some examples of
1925(potentially surprising) transformations that are valid (in pseudo IR):
1926
1927.. code-block:: llvm
1928
1929 %A = add %X, undef
1930 %B = sub %X, undef
1931 %C = xor %X, undef
1932 Safe:
1933 %A = undef
1934 %B = undef
1935 %C = undef
1936
1937This is safe because all of the output bits are affected by the undef
1938bits. Any output bit can have a zero or one depending on the input bits.
1939
1940.. code-block:: llvm
1941
1942 %A = or %X, undef
1943 %B = and %X, undef
1944 Safe:
1945 %A = -1
1946 %B = 0
1947 Unsafe:
1948 %A = undef
1949 %B = undef
1950
1951These logical operations have bits that are not always affected by the
1952input. For example, if ``%X`` has a zero bit, then the output of the
1953'``and``' operation will always be a zero for that bit, no matter what
1954the corresponding bit from the '``undef``' is. As such, it is unsafe to
1955optimize or assume that the result of the '``and``' is '``undef``'.
1956However, it is safe to assume that all bits of the '``undef``' could be
19570, and optimize the '``and``' to 0. Likewise, it is safe to assume that
1958all the bits of the '``undef``' operand to the '``or``' could be set,
1959allowing the '``or``' to be folded to -1.
1960
1961.. code-block:: llvm
1962
1963 %A = select undef, %X, %Y
1964 %B = select undef, 42, %Y
1965 %C = select %X, %Y, undef
1966 Safe:
1967 %A = %X (or %Y)
1968 %B = 42 (or %Y)
1969 %C = %Y
1970 Unsafe:
1971 %A = undef
1972 %B = undef
1973 %C = undef
1974
1975This set of examples shows that undefined '``select``' (and conditional
1976branch) conditions can go *either way*, but they have to come from one
1977of the two operands. In the ``%A`` example, if ``%X`` and ``%Y`` were
1978both known to have a clear low bit, then ``%A`` would have to have a
1979cleared low bit. However, in the ``%C`` example, the optimizer is
1980allowed to assume that the '``undef``' operand could be the same as
1981``%Y``, allowing the whole '``select``' to be eliminated.
1982
1983.. code-block:: llvm
1984
1985 %A = xor undef, undef
1986
1987 %B = undef
1988 %C = xor %B, %B
1989
1990 %D = undef
1991 %E = icmp lt %D, 4
1992 %F = icmp gte %D, 4
1993
1994 Safe:
1995 %A = undef
1996 %B = undef
1997 %C = undef
1998 %D = undef
1999 %E = undef
2000 %F = undef
2001
2002This example points out that two '``undef``' operands are not
2003necessarily the same. This can be surprising to people (and also matches
2004C semantics) where they assume that "``X^X``" is always zero, even if
2005``X`` is undefined. This isn't true for a number of reasons, but the
2006short answer is that an '``undef``' "variable" can arbitrarily change
2007its value over its "live range". This is true because the variable
2008doesn't actually *have a live range*. Instead, the value is logically
2009read from arbitrary registers that happen to be around when needed, so
2010the value is not necessarily consistent over time. In fact, ``%A`` and
2011``%C`` need to have the same semantics or the core LLVM "replace all
2012uses with" concept would not hold.
2013
2014.. code-block:: llvm
2015
2016 %A = fdiv undef, %X
2017 %B = fdiv %X, undef
2018 Safe:
2019 %A = undef
2020 b: unreachable
2021
2022These examples show the crucial difference between an *undefined value*
2023and *undefined behavior*. An undefined value (like '``undef``') is
2024allowed to have an arbitrary bit-pattern. This means that the ``%A``
2025operation can be constant folded to '``undef``', because the '``undef``'
2026could be an SNaN, and ``fdiv`` is not (currently) defined on SNaN's.
2027However, in the second example, we can make a more aggressive
2028assumption: because the ``undef`` is allowed to be an arbitrary value,
2029we are allowed to assume that it could be zero. Since a divide by zero
2030has *undefined behavior*, we are allowed to assume that the operation
2031does not execute at all. This allows us to delete the divide and all
2032code after it. Because the undefined operation "can't happen", the
2033optimizer can assume that it occurs in dead code.
2034
2035.. code-block:: llvm
2036
2037 a: store undef -> %X
2038 b: store %X -> undef
2039 Safe:
2040 a: <deleted>
2041 b: unreachable
2042
2043These examples reiterate the ``fdiv`` example: a store *of* an undefined
2044value can be assumed to not have any effect; we can assume that the
2045value is overwritten with bits that happen to match what was already
2046there. However, a store *to* an undefined location could clobber
2047arbitrary memory, therefore, it has undefined behavior.
2048
2049.. _poisonvalues:
2050
2051Poison Values
2052-------------
2053
2054Poison values are similar to :ref:`undef values <undefvalues>`, however
2055they also represent the fact that an instruction or constant expression
2056which cannot evoke side effects has nevertheless detected a condition
2057which results in undefined behavior.
2058
2059There is currently no way of representing a poison value in the IR; they
2060only exist when produced by operations such as :ref:`add <i_add>` with
2061the ``nsw`` flag.
2062
2063Poison value behavior is defined in terms of value *dependence*:
2064
2065- Values other than :ref:`phi <i_phi>` nodes depend on their operands.
2066- :ref:`Phi <i_phi>` nodes depend on the operand corresponding to
2067 their dynamic predecessor basic block.
2068- Function arguments depend on the corresponding actual argument values
2069 in the dynamic callers of their functions.
2070- :ref:`Call <i_call>` instructions depend on the :ref:`ret <i_ret>`
2071 instructions that dynamically transfer control back to them.
2072- :ref:`Invoke <i_invoke>` instructions depend on the
2073 :ref:`ret <i_ret>`, :ref:`resume <i_resume>`, or exception-throwing
2074 call instructions that dynamically transfer control back to them.
2075- Non-volatile loads and stores depend on the most recent stores to all
2076 of the referenced memory addresses, following the order in the IR
2077 (including loads and stores implied by intrinsics such as
2078 :ref:`@llvm.memcpy <int_memcpy>`.)
2079- An instruction with externally visible side effects depends on the
2080 most recent preceding instruction with externally visible side
2081 effects, following the order in the IR. (This includes :ref:`volatile
2082 operations <volatile>`.)
2083- An instruction *control-depends* on a :ref:`terminator
2084 instruction <terminators>` if the terminator instruction has
2085 multiple successors and the instruction is always executed when
2086 control transfers to one of the successors, and may not be executed
2087 when control is transferred to another.
2088- Additionally, an instruction also *control-depends* on a terminator
2089 instruction if the set of instructions it otherwise depends on would
2090 be different if the terminator had transferred control to a different
2091 successor.
2092- Dependence is transitive.
2093
2094Poison Values have the same behavior as :ref:`undef values <undefvalues>`,
2095with the additional affect that any instruction which has a *dependence*
2096on a poison value has undefined behavior.
2097
2098Here are some examples:
2099
2100.. code-block:: llvm
2101
2102 entry:
2103 %poison = sub nuw i32 0, 1 ; Results in a poison value.
2104 %still_poison = and i32 %poison, 0 ; 0, but also poison.
2105 %poison_yet_again = getelementptr i32* @h, i32 %still_poison
2106 store i32 0, i32* %poison_yet_again ; memory at @h[0] is poisoned
2107
2108 store i32 %poison, i32* @g ; Poison value stored to memory.
2109 %poison2 = load i32* @g ; Poison value loaded back from memory.
2110
2111 store volatile i32 %poison, i32* @g ; External observation; undefined behavior.
2112
2113 %narrowaddr = bitcast i32* @g to i16*
2114 %wideaddr = bitcast i32* @g to i64*
2115 %poison3 = load i16* %narrowaddr ; Returns a poison value.
2116 %poison4 = load i64* %wideaddr ; Returns a poison value.
2117
2118 %cmp = icmp slt i32 %poison, 0 ; Returns a poison value.
2119 br i1 %cmp, label %true, label %end ; Branch to either destination.
2120
2121 true:
2122 store volatile i32 0, i32* @g ; This is control-dependent on %cmp, so
2123 ; it has undefined behavior.
2124 br label %end
2125
2126 end:
2127 %p = phi i32 [ 0, %entry ], [ 1, %true ]
2128 ; Both edges into this PHI are
2129 ; control-dependent on %cmp, so this
2130 ; always results in a poison value.
2131
2132 store volatile i32 0, i32* @g ; This would depend on the store in %true
2133 ; if %cmp is true, or the store in %entry
2134 ; otherwise, so this is undefined behavior.
2135
2136 br i1 %cmp, label %second_true, label %second_end
2137 ; The same branch again, but this time the
2138 ; true block doesn't have side effects.
2139
2140 second_true:
2141 ; No side effects!
2142 ret void
2143
2144 second_end:
2145 store volatile i32 0, i32* @g ; This time, the instruction always depends
2146 ; on the store in %end. Also, it is
2147 ; control-equivalent to %end, so this is
2148 ; well-defined (ignoring earlier undefined
2149 ; behavior in this example).
2150
2151.. _blockaddress:
2152
2153Addresses of Basic Blocks
2154-------------------------
2155
2156``blockaddress(@function, %block)``
2157
2158The '``blockaddress``' constant computes the address of the specified
2159basic block in the specified function, and always has an ``i8*`` type.
2160Taking the address of the entry block is illegal.
2161
2162This value only has defined behavior when used as an operand to the
2163':ref:`indirectbr <i_indirectbr>`' instruction, or for comparisons
2164against null. Pointer equality tests between labels addresses results in
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00002165undefined behavior --- though, again, comparison against null is ok, and
Sean Silvaf722b002012-12-07 10:36:55 +00002166no label is equal to the null pointer. This may be passed around as an
2167opaque pointer sized value as long as the bits are not inspected. This
2168allows ``ptrtoint`` and arithmetic to be performed on these values so
2169long as the original value is reconstituted before the ``indirectbr``
2170instruction.
2171
2172Finally, some targets may provide defined semantics when using the value
2173as the operand to an inline assembly, but that is target specific.
2174
2175Constant Expressions
2176--------------------
2177
2178Constant expressions are used to allow expressions involving other
2179constants to be used as constants. Constant expressions may be of any
2180:ref:`first class <t_firstclass>` type and may involve any LLVM operation
2181that does not have side effects (e.g. load and call are not supported).
2182The following is the syntax for constant expressions:
2183
2184``trunc (CST to TYPE)``
2185 Truncate a constant to another type. The bit size of CST must be
2186 larger than the bit size of TYPE. Both types must be integers.
2187``zext (CST to TYPE)``
2188 Zero extend a constant to another type. The bit size of CST must be
2189 smaller than the bit size of TYPE. Both types must be integers.
2190``sext (CST to TYPE)``
2191 Sign extend a constant to another type. The bit size of CST must be
2192 smaller than the bit size of TYPE. Both types must be integers.
2193``fptrunc (CST to TYPE)``
2194 Truncate a floating point constant to another floating point type.
2195 The size of CST must be larger than the size of TYPE. Both types
2196 must be floating point.
2197``fpext (CST to TYPE)``
2198 Floating point extend a constant to another type. The size of CST
2199 must be smaller or equal to the size of TYPE. Both types must be
2200 floating point.
2201``fptoui (CST to TYPE)``
2202 Convert a floating point constant to the corresponding unsigned
2203 integer constant. TYPE must be a scalar or vector integer type. CST
2204 must be of scalar or vector floating point type. Both CST and TYPE
2205 must be scalars, or vectors of the same number of elements. If the
2206 value won't fit in the integer type, the results are undefined.
2207``fptosi (CST to TYPE)``
2208 Convert a floating point constant to the corresponding signed
2209 integer constant. TYPE must be a scalar or vector integer type. CST
2210 must be of scalar or vector floating point type. Both CST and TYPE
2211 must be scalars, or vectors of the same number of elements. If the
2212 value won't fit in the integer type, the results are undefined.
2213``uitofp (CST to TYPE)``
2214 Convert an unsigned integer constant to the corresponding floating
2215 point constant. TYPE must be a scalar or vector floating point type.
2216 CST must be of scalar or vector integer type. Both CST and TYPE must
2217 be scalars, or vectors of the same number of elements. If the value
2218 won't fit in the floating point type, the results are undefined.
2219``sitofp (CST to TYPE)``
2220 Convert a signed integer constant to the corresponding floating
2221 point constant. TYPE must be a scalar or vector floating point type.
2222 CST must be of scalar or vector integer type. Both CST and TYPE must
2223 be scalars, or vectors of the same number of elements. If the value
2224 won't fit in the floating point type, the results are undefined.
2225``ptrtoint (CST to TYPE)``
2226 Convert a pointer typed constant to the corresponding integer
2227 constant ``TYPE`` must be an integer type. ``CST`` must be of
2228 pointer type. The ``CST`` value is zero extended, truncated, or
2229 unchanged to make it fit in ``TYPE``.
2230``inttoptr (CST to TYPE)``
2231 Convert an integer constant to a pointer constant. TYPE must be a
2232 pointer type. CST must be of integer type. The CST value is zero
2233 extended, truncated, or unchanged to make it fit in a pointer size.
2234 This one is *really* dangerous!
2235``bitcast (CST to TYPE)``
2236 Convert a constant, CST, to another TYPE. The constraints of the
2237 operands are the same as those for the :ref:`bitcast
2238 instruction <i_bitcast>`.
2239``getelementptr (CSTPTR, IDX0, IDX1, ...)``, ``getelementptr inbounds (CSTPTR, IDX0, IDX1, ...)``
2240 Perform the :ref:`getelementptr operation <i_getelementptr>` on
2241 constants. As with the :ref:`getelementptr <i_getelementptr>`
2242 instruction, the index list may have zero or more indexes, which are
2243 required to make sense for the type of "CSTPTR".
2244``select (COND, VAL1, VAL2)``
2245 Perform the :ref:`select operation <i_select>` on constants.
2246``icmp COND (VAL1, VAL2)``
2247 Performs the :ref:`icmp operation <i_icmp>` on constants.
2248``fcmp COND (VAL1, VAL2)``
2249 Performs the :ref:`fcmp operation <i_fcmp>` on constants.
2250``extractelement (VAL, IDX)``
2251 Perform the :ref:`extractelement operation <i_extractelement>` on
2252 constants.
2253``insertelement (VAL, ELT, IDX)``
2254 Perform the :ref:`insertelement operation <i_insertelement>` on
2255 constants.
2256``shufflevector (VEC1, VEC2, IDXMASK)``
2257 Perform the :ref:`shufflevector operation <i_shufflevector>` on
2258 constants.
2259``extractvalue (VAL, IDX0, IDX1, ...)``
2260 Perform the :ref:`extractvalue operation <i_extractvalue>` on
2261 constants. The index list is interpreted in a similar manner as
2262 indices in a ':ref:`getelementptr <i_getelementptr>`' operation. At
2263 least one index value must be specified.
2264``insertvalue (VAL, ELT, IDX0, IDX1, ...)``
2265 Perform the :ref:`insertvalue operation <i_insertvalue>` on constants.
2266 The index list is interpreted in a similar manner as indices in a
2267 ':ref:`getelementptr <i_getelementptr>`' operation. At least one index
2268 value must be specified.
2269``OPCODE (LHS, RHS)``
2270 Perform the specified operation of the LHS and RHS constants. OPCODE
2271 may be any of the :ref:`binary <binaryops>` or :ref:`bitwise
2272 binary <bitwiseops>` operations. The constraints on operands are
2273 the same as those for the corresponding instruction (e.g. no bitwise
2274 operations on floating point values are allowed).
2275
2276Other Values
2277============
2278
2279Inline Assembler Expressions
2280----------------------------
2281
2282LLVM supports inline assembler expressions (as opposed to :ref:`Module-Level
2283Inline Assembly <moduleasm>`) through the use of a special value. This
2284value represents the inline assembler as a string (containing the
2285instructions to emit), a list of operand constraints (stored as a
2286string), a flag that indicates whether or not the inline asm expression
2287has side effects, and a flag indicating whether the function containing
2288the asm needs to align its stack conservatively. An example inline
2289assembler expression is:
2290
2291.. code-block:: llvm
2292
2293 i32 (i32) asm "bswap $0", "=r,r"
2294
2295Inline assembler expressions may **only** be used as the callee operand
2296of a :ref:`call <i_call>` or an :ref:`invoke <i_invoke>` instruction.
2297Thus, typically we have:
2298
2299.. code-block:: llvm
2300
2301 %X = call i32 asm "bswap $0", "=r,r"(i32 %Y)
2302
2303Inline asms with side effects not visible in the constraint list must be
2304marked as having side effects. This is done through the use of the
2305'``sideeffect``' keyword, like so:
2306
2307.. code-block:: llvm
2308
2309 call void asm sideeffect "eieio", ""()
2310
2311In some cases inline asms will contain code that will not work unless
2312the stack is aligned in some way, such as calls or SSE instructions on
2313x86, yet will not contain code that does that alignment within the asm.
2314The compiler should make conservative assumptions about what the asm
2315might contain and should generate its usual stack alignment code in the
2316prologue if the '``alignstack``' keyword is present:
2317
2318.. code-block:: llvm
2319
2320 call void asm alignstack "eieio", ""()
2321
2322Inline asms also support using non-standard assembly dialects. The
2323assumed dialect is ATT. When the '``inteldialect``' keyword is present,
2324the inline asm is using the Intel dialect. Currently, ATT and Intel are
2325the only supported dialects. An example is:
2326
2327.. code-block:: llvm
2328
2329 call void asm inteldialect "eieio", ""()
2330
2331If multiple keywords appear the '``sideeffect``' keyword must come
2332first, the '``alignstack``' keyword second and the '``inteldialect``'
2333keyword last.
2334
2335Inline Asm Metadata
2336^^^^^^^^^^^^^^^^^^^
2337
2338The call instructions that wrap inline asm nodes may have a
2339"``!srcloc``" MDNode attached to it that contains a list of constant
2340integers. If present, the code generator will use the integer as the
2341location cookie value when report errors through the ``LLVMContext``
2342error reporting mechanisms. This allows a front-end to correlate backend
2343errors that occur with inline asm back to the source code that produced
2344it. For example:
2345
2346.. code-block:: llvm
2347
2348 call void asm sideeffect "something bad", ""(), !srcloc !42
2349 ...
2350 !42 = !{ i32 1234567 }
2351
2352It is up to the front-end to make sense of the magic numbers it places
2353in the IR. If the MDNode contains multiple constants, the code generator
2354will use the one that corresponds to the line of the asm that the error
2355occurs on.
2356
2357.. _metadata:
2358
2359Metadata Nodes and Metadata Strings
2360-----------------------------------
2361
2362LLVM IR allows metadata to be attached to instructions in the program
2363that can convey extra information about the code to the optimizers and
2364code generator. One example application of metadata is source-level
2365debug information. There are two metadata primitives: strings and nodes.
2366All metadata has the ``metadata`` type and is identified in syntax by a
2367preceding exclamation point ('``!``').
2368
2369A metadata string is a string surrounded by double quotes. It can
2370contain any character by escaping non-printable characters with
2371"``\xx``" where "``xx``" is the two digit hex code. For example:
2372"``!"test\00"``".
2373
2374Metadata nodes are represented with notation similar to structure
2375constants (a comma separated list of elements, surrounded by braces and
2376preceded by an exclamation point). Metadata nodes can have any values as
2377their operand. For example:
2378
2379.. code-block:: llvm
2380
2381 !{ metadata !"test\00", i32 10}
2382
2383A :ref:`named metadata <namedmetadatastructure>` is a collection of
2384metadata nodes, which can be looked up in the module symbol table. For
2385example:
2386
2387.. code-block:: llvm
2388
2389 !foo = metadata !{!4, !3}
2390
2391Metadata can be used as function arguments. Here ``llvm.dbg.value``
2392function is using two metadata arguments:
2393
2394.. code-block:: llvm
2395
2396 call void @llvm.dbg.value(metadata !24, i64 0, metadata !25)
2397
2398Metadata can be attached with an instruction. Here metadata ``!21`` is
2399attached to the ``add`` instruction using the ``!dbg`` identifier:
2400
2401.. code-block:: llvm
2402
2403 %indvar.next = add i64 %indvar, 1, !dbg !21
2404
2405More information about specific metadata nodes recognized by the
2406optimizers and code generator is found below.
2407
2408'``tbaa``' Metadata
2409^^^^^^^^^^^^^^^^^^^
2410
2411In LLVM IR, memory does not have types, so LLVM's own type system is not
2412suitable for doing TBAA. Instead, metadata is added to the IR to
2413describe a type system of a higher level language. This can be used to
2414implement typical C/C++ TBAA, but it can also be used to implement
2415custom alias analysis behavior for other languages.
2416
2417The current metadata format is very simple. TBAA metadata nodes have up
2418to three fields, e.g.:
2419
2420.. code-block:: llvm
2421
2422 !0 = metadata !{ metadata !"an example type tree" }
2423 !1 = metadata !{ metadata !"int", metadata !0 }
2424 !2 = metadata !{ metadata !"float", metadata !0 }
2425 !3 = metadata !{ metadata !"const float", metadata !2, i64 1 }
2426
2427The first field is an identity field. It can be any value, usually a
2428metadata string, which uniquely identifies the type. The most important
2429name in the tree is the name of the root node. Two trees with different
2430root node names are entirely disjoint, even if they have leaves with
2431common names.
2432
2433The second field identifies the type's parent node in the tree, or is
2434null or omitted for a root node. A type is considered to alias all of
2435its descendants and all of its ancestors in the tree. Also, a type is
2436considered to alias all types in other trees, so that bitcode produced
2437from multiple front-ends is handled conservatively.
2438
2439If the third field is present, it's an integer which if equal to 1
2440indicates that the type is "constant" (meaning
2441``pointsToConstantMemory`` should return true; see `other useful
2442AliasAnalysis methods <AliasAnalysis.html#OtherItfs>`_).
2443
2444'``tbaa.struct``' Metadata
2445^^^^^^^^^^^^^^^^^^^^^^^^^^
2446
2447The :ref:`llvm.memcpy <int_memcpy>` is often used to implement
2448aggregate assignment operations in C and similar languages, however it
2449is defined to copy a contiguous region of memory, which is more than
2450strictly necessary for aggregate types which contain holes due to
2451padding. Also, it doesn't contain any TBAA information about the fields
2452of the aggregate.
2453
2454``!tbaa.struct`` metadata can describe which memory subregions in a
2455memcpy are padding and what the TBAA tags of the struct are.
2456
2457The current metadata format is very simple. ``!tbaa.struct`` metadata
2458nodes are a list of operands which are in conceptual groups of three.
2459For each group of three, the first operand gives the byte offset of a
2460field in bytes, the second gives its size in bytes, and the third gives
2461its tbaa tag. e.g.:
2462
2463.. code-block:: llvm
2464
2465 !4 = metadata !{ i64 0, i64 4, metadata !1, i64 8, i64 4, metadata !2 }
2466
2467This describes a struct with two fields. The first is at offset 0 bytes
2468with size 4 bytes, and has tbaa tag !1. The second is at offset 8 bytes
2469and has size 4 bytes and has tbaa tag !2.
2470
2471Note that the fields need not be contiguous. In this example, there is a
24724 byte gap between the two fields. This gap represents padding which
2473does not carry useful data and need not be preserved.
2474
2475'``fpmath``' Metadata
2476^^^^^^^^^^^^^^^^^^^^^
2477
2478``fpmath`` metadata may be attached to any instruction of floating point
2479type. It can be used to express the maximum acceptable error in the
2480result of that instruction, in ULPs, thus potentially allowing the
2481compiler to use a more efficient but less accurate method of computing
2482it. ULP is defined as follows:
2483
2484 If ``x`` is a real number that lies between two finite consecutive
2485 floating-point numbers ``a`` and ``b``, without being equal to one
2486 of them, then ``ulp(x) = |b - a|``, otherwise ``ulp(x)`` is the
2487 distance between the two non-equal finite floating-point numbers
2488 nearest ``x``. Moreover, ``ulp(NaN)`` is ``NaN``.
2489
2490The metadata node shall consist of a single positive floating point
2491number representing the maximum relative error, for example:
2492
2493.. code-block:: llvm
2494
2495 !0 = metadata !{ float 2.5 } ; maximum acceptable inaccuracy is 2.5 ULPs
2496
2497'``range``' Metadata
2498^^^^^^^^^^^^^^^^^^^^
2499
2500``range`` metadata may be attached only to loads of integer types. It
2501expresses the possible ranges the loaded value is in. The ranges are
2502represented with a flattened list of integers. The loaded value is known
2503to be in the union of the ranges defined by each consecutive pair. Each
2504pair has the following properties:
2505
2506- The type must match the type loaded by the instruction.
2507- The pair ``a,b`` represents the range ``[a,b)``.
2508- Both ``a`` and ``b`` are constants.
2509- The range is allowed to wrap.
2510- The range should not represent the full or empty set. That is,
2511 ``a!=b``.
2512
2513In addition, the pairs must be in signed order of the lower bound and
2514they must be non-contiguous.
2515
2516Examples:
2517
2518.. code-block:: llvm
2519
2520 %a = load i8* %x, align 1, !range !0 ; Can only be 0 or 1
2521 %b = load i8* %y, align 1, !range !1 ; Can only be 255 (-1), 0 or 1
2522 %c = load i8* %z, align 1, !range !2 ; Can only be 0, 1, 3, 4 or 5
2523 %d = load i8* %z, align 1, !range !3 ; Can only be -2, -1, 3, 4 or 5
2524 ...
2525 !0 = metadata !{ i8 0, i8 2 }
2526 !1 = metadata !{ i8 255, i8 2 }
2527 !2 = metadata !{ i8 0, i8 2, i8 3, i8 6 }
2528 !3 = metadata !{ i8 -2, i8 0, i8 3, i8 6 }
2529
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +00002530'``llvm.loop``'
2531^^^^^^^^^^^^^^^
2532
2533It is sometimes useful to attach information to loop constructs. Currently,
2534loop metadata is implemented as metadata attached to the branch instruction
2535in the loop latch block. This type of metadata refer to a metadata node that is
2536guaranteed to be separate for each loop. The loop-level metadata is prefixed
2537with ``llvm.loop``.
2538
2539The loop identifier metadata is implemented using a metadata that refers to
Pekka Jaaskelainen45b2c252013-02-22 12:03:07 +00002540itself to avoid merging it with any other identifier metadata, e.g.,
2541during module linkage or function inlining. That is, each loop should refer
2542to their own identification metadata even if they reside in separate functions.
2543The following example contains loop identifier metadata for two separate loop
2544constructs:
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +00002545
2546.. code-block:: llvm
Paul Redmond8f0696c2013-02-21 17:20:45 +00002547
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +00002548 !0 = metadata !{ metadata !0 }
Pekka Jaaskelainen45b2c252013-02-22 12:03:07 +00002549 !1 = metadata !{ metadata !1 }
2550
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +00002551
2552'``llvm.loop.parallel``' Metadata
2553^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2554
2555This loop metadata can be used to communicate that a loop should be considered
2556a parallel loop. The semantics of parallel loops in this case is the one
2557with the strongest cross-iteration instruction ordering freedom: the
2558iterations in the loop can be considered completely independent of each
2559other (also known as embarrassingly parallel loops).
2560
2561This metadata can originate from a programming language with parallel loop
2562constructs. In such a case it is completely the programmer's responsibility
2563to ensure the instructions from the different iterations of the loop can be
2564executed in an arbitrary order, in parallel, or intertwined. No loop-carried
2565dependency checking at all must be expected from the compiler.
2566
2567In order to fulfill the LLVM requirement for metadata to be safely ignored,
2568it is important to ensure that a parallel loop is converted to
2569a sequential loop in case an optimization (agnostic of the parallel loop
2570semantics) converts the loop back to such. This happens when new memory
2571accesses that do not fulfill the requirement of free ordering across iterations
2572are added to the loop. Therefore, this metadata is required, but not
2573sufficient, to consider the loop at hand a parallel loop. For a loop
2574to be parallel, all its memory accessing instructions need to be
2575marked with the ``llvm.mem.parallel_loop_access`` metadata that refer
2576to the same loop identifier metadata that identify the loop at hand.
2577
2578'``llvm.mem``'
2579^^^^^^^^^^^^^^^
2580
2581Metadata types used to annotate memory accesses with information helpful
2582for optimizations are prefixed with ``llvm.mem``.
2583
2584'``llvm.mem.parallel_loop_access``' Metadata
2585^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2586
2587For a loop to be parallel, in addition to using
2588the ``llvm.loop.parallel`` metadata to mark the loop latch branch instruction,
2589also all of the memory accessing instructions in the loop body need to be
2590marked with the ``llvm.mem.parallel_loop_access`` metadata. If there
2591is at least one memory accessing instruction not marked with the metadata,
2592the loop, despite it possibly using the ``llvm.loop.parallel`` metadata,
2593must be considered a sequential loop. This causes parallel loops to be
2594converted to sequential loops due to optimization passes that are unaware of
2595the parallel semantics and that insert new memory instructions to the loop
2596body.
2597
2598Example of a loop that is considered parallel due to its correct use of
2599both ``llvm.loop.parallel`` and ``llvm.mem.parallel_loop_access``
2600metadata types that refer to the same loop identifier metadata.
2601
2602.. code-block:: llvm
2603
2604 for.body:
2605 ...
2606 %0 = load i32* %arrayidx, align 4, !llvm.mem.parallel_loop_access !0
2607 ...
2608 store i32 %0, i32* %arrayidx4, align 4, !llvm.mem.parallel_loop_access !0
2609 ...
2610 br i1 %exitcond, label %for.end, label %for.body, !llvm.loop.parallel !0
2611
2612 for.end:
2613 ...
2614 !0 = metadata !{ metadata !0 }
2615
2616It is also possible to have nested parallel loops. In that case the
2617memory accesses refer to a list of loop identifier metadata nodes instead of
2618the loop identifier metadata node directly:
2619
2620.. code-block:: llvm
2621
2622 outer.for.body:
2623 ...
2624
2625 inner.for.body:
2626 ...
2627 %0 = load i32* %arrayidx, align 4, !llvm.mem.parallel_loop_access !0
2628 ...
2629 store i32 %0, i32* %arrayidx4, align 4, !llvm.mem.parallel_loop_access !0
2630 ...
2631 br i1 %exitcond, label %inner.for.end, label %inner.for.body, !llvm.loop.parallel !1
2632
2633 inner.for.end:
2634 ...
2635 %0 = load i32* %arrayidx, align 4, !llvm.mem.parallel_loop_access !0
2636 ...
2637 store i32 %0, i32* %arrayidx4, align 4, !llvm.mem.parallel_loop_access !0
2638 ...
2639 br i1 %exitcond, label %outer.for.end, label %outer.for.body, !llvm.loop.parallel !2
2640
2641 outer.for.end: ; preds = %for.body
2642 ...
2643 !0 = metadata !{ metadata !1, metadata !2 } ; a list of parallel loop identifiers
2644 !1 = metadata !{ metadata !1 } ; an identifier for the inner parallel loop
2645 !2 = metadata !{ metadata !2 } ; an identifier for the outer parallel loop
2646
2647
Sean Silvaf722b002012-12-07 10:36:55 +00002648Module Flags Metadata
2649=====================
2650
2651Information about the module as a whole is difficult to convey to LLVM's
2652subsystems. The LLVM IR isn't sufficient to transmit this information.
2653The ``llvm.module.flags`` named metadata exists in order to facilitate
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00002654this. These flags are in the form of key / value pairs --- much like a
2655dictionary --- making it easy for any subsystem who cares about a flag to
Sean Silvaf722b002012-12-07 10:36:55 +00002656look it up.
2657
2658The ``llvm.module.flags`` metadata contains a list of metadata triplets.
2659Each triplet has the following form:
2660
2661- The first element is a *behavior* flag, which specifies the behavior
2662 when two (or more) modules are merged together, and it encounters two
2663 (or more) metadata with the same ID. The supported behaviors are
2664 described below.
2665- The second element is a metadata string that is a unique ID for the
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002666 metadata. Each module may only have one flag entry for each unique ID (not
2667 including entries with the **Require** behavior).
Sean Silvaf722b002012-12-07 10:36:55 +00002668- The third element is the value of the flag.
2669
2670When two (or more) modules are merged together, the resulting
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002671``llvm.module.flags`` metadata is the union of the modules' flags. That is, for
2672each unique metadata ID string, there will be exactly one entry in the merged
2673modules ``llvm.module.flags`` metadata table, and the value for that entry will
2674be determined by the merge behavior flag, as described below. The only exception
2675is that entries with the *Require* behavior are always preserved.
Sean Silvaf722b002012-12-07 10:36:55 +00002676
2677The following behaviors are supported:
2678
2679.. list-table::
2680 :header-rows: 1
2681 :widths: 10 90
2682
2683 * - Value
2684 - Behavior
2685
2686 * - 1
2687 - **Error**
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002688 Emits an error if two values disagree, otherwise the resulting value
2689 is that of the operands.
Sean Silvaf722b002012-12-07 10:36:55 +00002690
2691 * - 2
2692 - **Warning**
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002693 Emits a warning if two values disagree. The result value will be the
2694 operand for the flag from the first module being linked.
Sean Silvaf722b002012-12-07 10:36:55 +00002695
2696 * - 3
2697 - **Require**
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002698 Adds a requirement that another module flag be present and have a
2699 specified value after linking is performed. The value must be a
2700 metadata pair, where the first element of the pair is the ID of the
2701 module flag to be restricted, and the second element of the pair is
2702 the value the module flag should be restricted to. This behavior can
2703 be used to restrict the allowable results (via triggering of an
2704 error) of linking IDs with the **Override** behavior.
Sean Silvaf722b002012-12-07 10:36:55 +00002705
2706 * - 4
2707 - **Override**
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002708 Uses the specified value, regardless of the behavior or value of the
2709 other module. If both modules specify **Override**, but the values
2710 differ, an error will be emitted.
2711
Daniel Dunbar5db391c2013-01-16 21:38:56 +00002712 * - 5
2713 - **Append**
2714 Appends the two values, which are required to be metadata nodes.
2715
2716 * - 6
2717 - **AppendUnique**
2718 Appends the two values, which are required to be metadata
2719 nodes. However, duplicate entries in the second list are dropped
2720 during the append operation.
2721
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002722It is an error for a particular unique flag ID to have multiple behaviors,
2723except in the case of **Require** (which adds restrictions on another metadata
2724value) or **Override**.
Sean Silvaf722b002012-12-07 10:36:55 +00002725
2726An example of module flags:
2727
2728.. code-block:: llvm
2729
2730 !0 = metadata !{ i32 1, metadata !"foo", i32 1 }
2731 !1 = metadata !{ i32 4, metadata !"bar", i32 37 }
2732 !2 = metadata !{ i32 2, metadata !"qux", i32 42 }
2733 !3 = metadata !{ i32 3, metadata !"qux",
2734 metadata !{
2735 metadata !"foo", i32 1
2736 }
2737 }
2738 !llvm.module.flags = !{ !0, !1, !2, !3 }
2739
2740- Metadata ``!0`` has the ID ``!"foo"`` and the value '1'. The behavior
2741 if two or more ``!"foo"`` flags are seen is to emit an error if their
2742 values are not equal.
2743
2744- Metadata ``!1`` has the ID ``!"bar"`` and the value '37'. The
2745 behavior if two or more ``!"bar"`` flags are seen is to use the value
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002746 '37'.
Sean Silvaf722b002012-12-07 10:36:55 +00002747
2748- Metadata ``!2`` has the ID ``!"qux"`` and the value '42'. The
2749 behavior if two or more ``!"qux"`` flags are seen is to emit a
2750 warning if their values are not equal.
2751
2752- Metadata ``!3`` has the ID ``!"qux"`` and the value:
2753
2754 ::
2755
2756 metadata !{ metadata !"foo", i32 1 }
2757
Daniel Dunbar8dd938e2013-01-15 01:22:53 +00002758 The behavior is to emit an error if the ``llvm.module.flags`` does not
2759 contain a flag with the ID ``!"foo"`` that has the value '1' after linking is
2760 performed.
Sean Silvaf722b002012-12-07 10:36:55 +00002761
2762Objective-C Garbage Collection Module Flags Metadata
2763----------------------------------------------------
2764
2765On the Mach-O platform, Objective-C stores metadata about garbage
2766collection in a special section called "image info". The metadata
2767consists of a version number and a bitmask specifying what types of
2768garbage collection are supported (if any) by the file. If two or more
2769modules are linked together their garbage collection metadata needs to
2770be merged rather than appended together.
2771
2772The Objective-C garbage collection module flags metadata consists of the
2773following key-value pairs:
2774
2775.. list-table::
2776 :header-rows: 1
2777 :widths: 30 70
2778
2779 * - Key
2780 - Value
2781
Daniel Dunbar3389dbc2013-01-17 18:57:32 +00002782 * - ``Objective-C Version``
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00002783 - **[Required]** --- The Objective-C ABI version. Valid values are 1 and 2.
Sean Silvaf722b002012-12-07 10:36:55 +00002784
Daniel Dunbar3389dbc2013-01-17 18:57:32 +00002785 * - ``Objective-C Image Info Version``
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00002786 - **[Required]** --- The version of the image info section. Currently
Sean Silvaf722b002012-12-07 10:36:55 +00002787 always 0.
2788
Daniel Dunbar3389dbc2013-01-17 18:57:32 +00002789 * - ``Objective-C Image Info Section``
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00002790 - **[Required]** --- The section to place the metadata. Valid values are
Sean Silvaf722b002012-12-07 10:36:55 +00002791 ``"__OBJC, __image_info, regular"`` for Objective-C ABI version 1, and
2792 ``"__DATA,__objc_imageinfo, regular, no_dead_strip"`` for
2793 Objective-C ABI version 2.
2794
Daniel Dunbar3389dbc2013-01-17 18:57:32 +00002795 * - ``Objective-C Garbage Collection``
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00002796 - **[Required]** --- Specifies whether garbage collection is supported or
Sean Silvaf722b002012-12-07 10:36:55 +00002797 not. Valid values are 0, for no garbage collection, and 2, for garbage
2798 collection supported.
2799
Daniel Dunbar3389dbc2013-01-17 18:57:32 +00002800 * - ``Objective-C GC Only``
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00002801 - **[Optional]** --- Specifies that only garbage collection is supported.
Sean Silvaf722b002012-12-07 10:36:55 +00002802 If present, its value must be 6. This flag requires that the
2803 ``Objective-C Garbage Collection`` flag have the value 2.
2804
2805Some important flag interactions:
2806
2807- If a module with ``Objective-C Garbage Collection`` set to 0 is
2808 merged with a module with ``Objective-C Garbage Collection`` set to
2809 2, then the resulting module has the
2810 ``Objective-C Garbage Collection`` flag set to 0.
2811- A module with ``Objective-C Garbage Collection`` set to 0 cannot be
2812 merged with a module with ``Objective-C GC Only`` set to 6.
2813
Daniel Dunbare06bfe82013-01-17 00:16:27 +00002814Automatic Linker Flags Module Flags Metadata
2815--------------------------------------------
2816
2817Some targets support embedding flags to the linker inside individual object
2818files. Typically this is used in conjunction with language extensions which
2819allow source files to explicitly declare the libraries they depend on, and have
2820these automatically be transmitted to the linker via object files.
2821
2822These flags are encoded in the IR using metadata in the module flags section,
Daniel Dunbar3389dbc2013-01-17 18:57:32 +00002823using the ``Linker Options`` key. The merge behavior for this flag is required
Daniel Dunbare06bfe82013-01-17 00:16:27 +00002824to be ``AppendUnique``, and the value for the key is expected to be a metadata
2825node which should be a list of other metadata nodes, each of which should be a
2826list of metadata strings defining linker options.
2827
2828For example, the following metadata section specifies two separate sets of
2829linker options, presumably to link against ``libz`` and the ``Cocoa``
2830framework::
2831
Daniel Dunbar6d49b682013-01-18 19:37:00 +00002832 !0 = metadata !{ i32 6, metadata !"Linker Options",
Daniel Dunbare06bfe82013-01-17 00:16:27 +00002833 metadata !{
Daniel Dunbar6d49b682013-01-18 19:37:00 +00002834 metadata !{ metadata !"-lz" },
2835 metadata !{ metadata !"-framework", metadata !"Cocoa" } } }
Daniel Dunbare06bfe82013-01-17 00:16:27 +00002836 !llvm.module.flags = !{ !0 }
2837
2838The metadata encoding as lists of lists of options, as opposed to a collapsed
2839list of options, is chosen so that the IR encoding can use multiple option
2840strings to specify e.g., a single library, while still having that specifier be
2841preserved as an atomic element that can be recognized by a target specific
2842assembly writer or object file emitter.
2843
2844Each individual option is required to be either a valid option for the target's
2845linker, or an option that is reserved by the target specific assembly writer or
2846object file emitter. No other aspect of these options is defined by the IR.
2847
Sean Silvaf722b002012-12-07 10:36:55 +00002848Intrinsic Global Variables
2849==========================
2850
2851LLVM has a number of "magic" global variables that contain data that
2852affect code generation or other IR semantics. These are documented here.
2853All globals of this sort should have a section specified as
2854"``llvm.metadata``". This section and all globals that start with
2855"``llvm.``" are reserved for use by LLVM.
2856
2857The '``llvm.used``' Global Variable
2858-----------------------------------
2859
2860The ``@llvm.used`` global is an array with i8\* element type which has
2861:ref:`appending linkage <linkage_appending>`. This array contains a list of
2862pointers to global variables and functions which may optionally have a
2863pointer cast formed of bitcast or getelementptr. For example, a legal
2864use of it is:
2865
2866.. code-block:: llvm
2867
2868 @X = global i8 4
2869 @Y = global i32 123
2870
2871 @llvm.used = appending global [2 x i8*] [
2872 i8* @X,
2873 i8* bitcast (i32* @Y to i8*)
2874 ], section "llvm.metadata"
2875
2876If a global variable appears in the ``@llvm.used`` list, then the
2877compiler, assembler, and linker are required to treat the symbol as if
2878there is a reference to the global that it cannot see. For example, if a
2879variable has internal linkage and no references other than that from the
2880``@llvm.used`` list, it cannot be deleted. This is commonly used to
2881represent references from inline asms and other things the compiler
2882cannot "see", and corresponds to "``attribute((used))``" in GNU C.
2883
2884On some targets, the code generator must emit a directive to the
2885assembler or object file to prevent the assembler and linker from
2886molesting the symbol.
2887
2888The '``llvm.compiler.used``' Global Variable
2889--------------------------------------------
2890
2891The ``@llvm.compiler.used`` directive is the same as the ``@llvm.used``
2892directive, except that it only prevents the compiler from touching the
2893symbol. On targets that support it, this allows an intelligent linker to
2894optimize references to the symbol without being impeded as it would be
2895by ``@llvm.used``.
2896
2897This is a rare construct that should only be used in rare circumstances,
2898and should not be exposed to source languages.
2899
2900The '``llvm.global_ctors``' Global Variable
2901-------------------------------------------
2902
2903.. code-block:: llvm
2904
2905 %0 = type { i32, void ()* }
2906 @llvm.global_ctors = appending global [1 x %0] [%0 { i32 65535, void ()* @ctor }]
2907
2908The ``@llvm.global_ctors`` array contains a list of constructor
2909functions and associated priorities. The functions referenced by this
2910array will be called in ascending order of priority (i.e. lowest first)
2911when the module is loaded. The order of functions with the same priority
2912is not defined.
2913
2914The '``llvm.global_dtors``' Global Variable
2915-------------------------------------------
2916
2917.. code-block:: llvm
2918
2919 %0 = type { i32, void ()* }
2920 @llvm.global_dtors = appending global [1 x %0] [%0 { i32 65535, void ()* @dtor }]
2921
2922The ``@llvm.global_dtors`` array contains a list of destructor functions
2923and associated priorities. The functions referenced by this array will
2924be called in descending order of priority (i.e. highest first) when the
2925module is loaded. The order of functions with the same priority is not
2926defined.
2927
2928Instruction Reference
2929=====================
2930
2931The LLVM instruction set consists of several different classifications
2932of instructions: :ref:`terminator instructions <terminators>`, :ref:`binary
2933instructions <binaryops>`, :ref:`bitwise binary
2934instructions <bitwiseops>`, :ref:`memory instructions <memoryops>`, and
2935:ref:`other instructions <otherops>`.
2936
2937.. _terminators:
2938
2939Terminator Instructions
2940-----------------------
2941
2942As mentioned :ref:`previously <functionstructure>`, every basic block in a
2943program ends with a "Terminator" instruction, which indicates which
2944block should be executed after the current block is finished. These
2945terminator instructions typically yield a '``void``' value: they produce
2946control flow, not values (the one exception being the
2947':ref:`invoke <i_invoke>`' instruction).
2948
2949The terminator instructions are: ':ref:`ret <i_ret>`',
2950':ref:`br <i_br>`', ':ref:`switch <i_switch>`',
2951':ref:`indirectbr <i_indirectbr>`', ':ref:`invoke <i_invoke>`',
2952':ref:`resume <i_resume>`', and ':ref:`unreachable <i_unreachable>`'.
2953
2954.. _i_ret:
2955
2956'``ret``' Instruction
2957^^^^^^^^^^^^^^^^^^^^^
2958
2959Syntax:
2960"""""""
2961
2962::
2963
2964 ret <type> <value> ; Return a value from a non-void function
2965 ret void ; Return from void function
2966
2967Overview:
2968"""""""""
2969
2970The '``ret``' instruction is used to return control flow (and optionally
2971a value) from a function back to the caller.
2972
2973There are two forms of the '``ret``' instruction: one that returns a
2974value and then causes control flow, and one that just causes control
2975flow to occur.
2976
2977Arguments:
2978""""""""""
2979
2980The '``ret``' instruction optionally accepts a single argument, the
2981return value. The type of the return value must be a ':ref:`first
2982class <t_firstclass>`' type.
2983
2984A function is not :ref:`well formed <wellformed>` if it it has a non-void
2985return type and contains a '``ret``' instruction with no return value or
2986a return value with a type that does not match its type, or if it has a
2987void return type and contains a '``ret``' instruction with a return
2988value.
2989
2990Semantics:
2991""""""""""
2992
2993When the '``ret``' instruction is executed, control flow returns back to
2994the calling function's context. If the caller is a
2995":ref:`call <i_call>`" instruction, execution continues at the
2996instruction after the call. If the caller was an
2997":ref:`invoke <i_invoke>`" instruction, execution continues at the
2998beginning of the "normal" destination block. If the instruction returns
2999a value, that value shall set the call or invoke instruction's return
3000value.
3001
3002Example:
3003""""""""
3004
3005.. code-block:: llvm
3006
3007 ret i32 5 ; Return an integer value of 5
3008 ret void ; Return from a void function
3009 ret { i32, i8 } { i32 4, i8 2 } ; Return a struct of values 4 and 2
3010
3011.. _i_br:
3012
3013'``br``' Instruction
3014^^^^^^^^^^^^^^^^^^^^
3015
3016Syntax:
3017"""""""
3018
3019::
3020
3021 br i1 <cond>, label <iftrue>, label <iffalse>
3022 br label <dest> ; Unconditional branch
3023
3024Overview:
3025"""""""""
3026
3027The '``br``' instruction is used to cause control flow to transfer to a
3028different basic block in the current function. There are two forms of
3029this instruction, corresponding to a conditional branch and an
3030unconditional branch.
3031
3032Arguments:
3033""""""""""
3034
3035The conditional branch form of the '``br``' instruction takes a single
3036'``i1``' value and two '``label``' values. The unconditional form of the
3037'``br``' instruction takes a single '``label``' value as a target.
3038
3039Semantics:
3040""""""""""
3041
3042Upon execution of a conditional '``br``' instruction, the '``i1``'
3043argument is evaluated. If the value is ``true``, control flows to the
3044'``iftrue``' ``label`` argument. If "cond" is ``false``, control flows
3045to the '``iffalse``' ``label`` argument.
3046
3047Example:
3048""""""""
3049
3050.. code-block:: llvm
3051
3052 Test:
3053 %cond = icmp eq i32 %a, %b
3054 br i1 %cond, label %IfEqual, label %IfUnequal
3055 IfEqual:
3056 ret i32 1
3057 IfUnequal:
3058 ret i32 0
3059
3060.. _i_switch:
3061
3062'``switch``' Instruction
3063^^^^^^^^^^^^^^^^^^^^^^^^
3064
3065Syntax:
3066"""""""
3067
3068::
3069
3070 switch <intty> <value>, label <defaultdest> [ <intty> <val>, label <dest> ... ]
3071
3072Overview:
3073"""""""""
3074
3075The '``switch``' instruction is used to transfer control flow to one of
3076several different places. It is a generalization of the '``br``'
3077instruction, allowing a branch to occur to one of many possible
3078destinations.
3079
3080Arguments:
3081""""""""""
3082
3083The '``switch``' instruction uses three parameters: an integer
3084comparison value '``value``', a default '``label``' destination, and an
3085array of pairs of comparison value constants and '``label``'s. The table
3086is not allowed to contain duplicate constant entries.
3087
3088Semantics:
3089""""""""""
3090
3091The ``switch`` instruction specifies a table of values and destinations.
3092When the '``switch``' instruction is executed, this table is searched
3093for the given value. If the value is found, control flow is transferred
3094to the corresponding destination; otherwise, control flow is transferred
3095to the default destination.
3096
3097Implementation:
3098"""""""""""""""
3099
3100Depending on properties of the target machine and the particular
3101``switch`` instruction, this instruction may be code generated in
3102different ways. For example, it could be generated as a series of
3103chained conditional branches or with a lookup table.
3104
3105Example:
3106""""""""
3107
3108.. code-block:: llvm
3109
3110 ; Emulate a conditional br instruction
3111 %Val = zext i1 %value to i32
3112 switch i32 %Val, label %truedest [ i32 0, label %falsedest ]
3113
3114 ; Emulate an unconditional br instruction
3115 switch i32 0, label %dest [ ]
3116
3117 ; Implement a jump table:
3118 switch i32 %val, label %otherwise [ i32 0, label %onzero
3119 i32 1, label %onone
3120 i32 2, label %ontwo ]
3121
3122.. _i_indirectbr:
3123
3124'``indirectbr``' Instruction
3125^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3126
3127Syntax:
3128"""""""
3129
3130::
3131
3132 indirectbr <somety>* <address>, [ label <dest1>, label <dest2>, ... ]
3133
3134Overview:
3135"""""""""
3136
3137The '``indirectbr``' instruction implements an indirect branch to a
3138label within the current function, whose address is specified by
3139"``address``". Address must be derived from a
3140:ref:`blockaddress <blockaddress>` constant.
3141
3142Arguments:
3143""""""""""
3144
3145The '``address``' argument is the address of the label to jump to. The
3146rest of the arguments indicate the full set of possible destinations
3147that the address may point to. Blocks are allowed to occur multiple
3148times in the destination list, though this isn't particularly useful.
3149
3150This destination list is required so that dataflow analysis has an
3151accurate understanding of the CFG.
3152
3153Semantics:
3154""""""""""
3155
3156Control transfers to the block specified in the address argument. All
3157possible destination blocks must be listed in the label list, otherwise
3158this instruction has undefined behavior. This implies that jumps to
3159labels defined in other functions have undefined behavior as well.
3160
3161Implementation:
3162"""""""""""""""
3163
3164This is typically implemented with a jump through a register.
3165
3166Example:
3167""""""""
3168
3169.. code-block:: llvm
3170
3171 indirectbr i8* %Addr, [ label %bb1, label %bb2, label %bb3 ]
3172
3173.. _i_invoke:
3174
3175'``invoke``' Instruction
3176^^^^^^^^^^^^^^^^^^^^^^^^
3177
3178Syntax:
3179"""""""
3180
3181::
3182
3183 <result> = invoke [cconv] [ret attrs] <ptr to function ty> <function ptr val>(<function args>) [fn attrs]
3184 to label <normal label> unwind label <exception label>
3185
3186Overview:
3187"""""""""
3188
3189The '``invoke``' instruction causes control to transfer to a specified
3190function, with the possibility of control flow transfer to either the
3191'``normal``' label or the '``exception``' label. If the callee function
3192returns with the "``ret``" instruction, control flow will return to the
3193"normal" label. If the callee (or any indirect callees) returns via the
3194":ref:`resume <i_resume>`" instruction or other exception handling
3195mechanism, control is interrupted and continued at the dynamically
3196nearest "exception" label.
3197
3198The '``exception``' label is a `landing
3199pad <ExceptionHandling.html#overview>`_ for the exception. As such,
3200'``exception``' label is required to have the
3201":ref:`landingpad <i_landingpad>`" instruction, which contains the
3202information about the behavior of the program after unwinding happens,
3203as its first non-PHI instruction. The restrictions on the
3204"``landingpad``" instruction's tightly couples it to the "``invoke``"
3205instruction, so that the important information contained within the
3206"``landingpad``" instruction can't be lost through normal code motion.
3207
3208Arguments:
3209""""""""""
3210
3211This instruction requires several arguments:
3212
3213#. The optional "cconv" marker indicates which :ref:`calling
3214 convention <callingconv>` the call should use. If none is
3215 specified, the call defaults to using C calling conventions.
3216#. The optional :ref:`Parameter Attributes <paramattrs>` list for return
3217 values. Only '``zeroext``', '``signext``', and '``inreg``' attributes
3218 are valid here.
3219#. '``ptr to function ty``': shall be the signature of the pointer to
3220 function value being invoked. In most cases, this is a direct
3221 function invocation, but indirect ``invoke``'s are just as possible,
3222 branching off an arbitrary pointer to function value.
3223#. '``function ptr val``': An LLVM value containing a pointer to a
3224 function to be invoked.
3225#. '``function args``': argument list whose types match the function
3226 signature argument types and parameter attributes. All arguments must
3227 be of :ref:`first class <t_firstclass>` type. If the function signature
3228 indicates the function accepts a variable number of arguments, the
3229 extra arguments can be specified.
3230#. '``normal label``': the label reached when the called function
3231 executes a '``ret``' instruction.
3232#. '``exception label``': the label reached when a callee returns via
3233 the :ref:`resume <i_resume>` instruction or other exception handling
3234 mechanism.
3235#. The optional :ref:`function attributes <fnattrs>` list. Only
3236 '``noreturn``', '``nounwind``', '``readonly``' and '``readnone``'
3237 attributes are valid here.
3238
3239Semantics:
3240""""""""""
3241
3242This instruction is designed to operate as a standard '``call``'
3243instruction in most regards. The primary difference is that it
3244establishes an association with a label, which is used by the runtime
3245library to unwind the stack.
3246
3247This instruction is used in languages with destructors to ensure that
3248proper cleanup is performed in the case of either a ``longjmp`` or a
3249thrown exception. Additionally, this is important for implementation of
3250'``catch``' clauses in high-level languages that support them.
3251
3252For the purposes of the SSA form, the definition of the value returned
3253by the '``invoke``' instruction is deemed to occur on the edge from the
3254current block to the "normal" label. If the callee unwinds then no
3255return value is available.
3256
3257Example:
3258""""""""
3259
3260.. code-block:: llvm
3261
3262 %retval = invoke i32 @Test(i32 15) to label %Continue
3263 unwind label %TestCleanup ; {i32}:retval set
3264 %retval = invoke coldcc i32 %Testfnptr(i32 15) to label %Continue
3265 unwind label %TestCleanup ; {i32}:retval set
3266
3267.. _i_resume:
3268
3269'``resume``' Instruction
3270^^^^^^^^^^^^^^^^^^^^^^^^
3271
3272Syntax:
3273"""""""
3274
3275::
3276
3277 resume <type> <value>
3278
3279Overview:
3280"""""""""
3281
3282The '``resume``' instruction is a terminator instruction that has no
3283successors.
3284
3285Arguments:
3286""""""""""
3287
3288The '``resume``' instruction requires one argument, which must have the
3289same type as the result of any '``landingpad``' instruction in the same
3290function.
3291
3292Semantics:
3293""""""""""
3294
3295The '``resume``' instruction resumes propagation of an existing
3296(in-flight) exception whose unwinding was interrupted with a
3297:ref:`landingpad <i_landingpad>` instruction.
3298
3299Example:
3300""""""""
3301
3302.. code-block:: llvm
3303
3304 resume { i8*, i32 } %exn
3305
3306.. _i_unreachable:
3307
3308'``unreachable``' Instruction
3309^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3310
3311Syntax:
3312"""""""
3313
3314::
3315
3316 unreachable
3317
3318Overview:
3319"""""""""
3320
3321The '``unreachable``' instruction has no defined semantics. This
3322instruction is used to inform the optimizer that a particular portion of
3323the code is not reachable. This can be used to indicate that the code
3324after a no-return function cannot be reached, and other facts.
3325
3326Semantics:
3327""""""""""
3328
3329The '``unreachable``' instruction has no defined semantics.
3330
3331.. _binaryops:
3332
3333Binary Operations
3334-----------------
3335
3336Binary operators are used to do most of the computation in a program.
3337They require two operands of the same type, execute an operation on
3338them, and produce a single value. The operands might represent multiple
3339data, as is the case with the :ref:`vector <t_vector>` data type. The
3340result value has the same type as its operands.
3341
3342There are several different binary operators:
3343
3344.. _i_add:
3345
3346'``add``' Instruction
3347^^^^^^^^^^^^^^^^^^^^^
3348
3349Syntax:
3350"""""""
3351
3352::
3353
3354 <result> = add <ty> <op1>, <op2> ; yields {ty}:result
3355 <result> = add nuw <ty> <op1>, <op2> ; yields {ty}:result
3356 <result> = add nsw <ty> <op1>, <op2> ; yields {ty}:result
3357 <result> = add nuw nsw <ty> <op1>, <op2> ; yields {ty}:result
3358
3359Overview:
3360"""""""""
3361
3362The '``add``' instruction returns the sum of its two operands.
3363
3364Arguments:
3365""""""""""
3366
3367The two arguments to the '``add``' instruction must be
3368:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
3369arguments must have identical types.
3370
3371Semantics:
3372""""""""""
3373
3374The value produced is the integer sum of the two operands.
3375
3376If the sum has unsigned overflow, the result returned is the
3377mathematical result modulo 2\ :sup:`n`\ , where n is the bit width of
3378the result.
3379
3380Because LLVM integers use a two's complement representation, this
3381instruction is appropriate for both signed and unsigned integers.
3382
3383``nuw`` and ``nsw`` stand for "No Unsigned Wrap" and "No Signed Wrap",
3384respectively. If the ``nuw`` and/or ``nsw`` keywords are present, the
3385result value of the ``add`` is a :ref:`poison value <poisonvalues>` if
3386unsigned and/or signed overflow, respectively, occurs.
3387
3388Example:
3389""""""""
3390
3391.. code-block:: llvm
3392
3393 <result> = add i32 4, %var ; yields {i32}:result = 4 + %var
3394
3395.. _i_fadd:
3396
3397'``fadd``' Instruction
3398^^^^^^^^^^^^^^^^^^^^^^
3399
3400Syntax:
3401"""""""
3402
3403::
3404
3405 <result> = fadd [fast-math flags]* <ty> <op1>, <op2> ; yields {ty}:result
3406
3407Overview:
3408"""""""""
3409
3410The '``fadd``' instruction returns the sum of its two operands.
3411
3412Arguments:
3413""""""""""
3414
3415The two arguments to the '``fadd``' instruction must be :ref:`floating
3416point <t_floating>` or :ref:`vector <t_vector>` of floating point values.
3417Both arguments must have identical types.
3418
3419Semantics:
3420""""""""""
3421
3422The value produced is the floating point sum of the two operands. This
3423instruction can also take any number of :ref:`fast-math flags <fastmath>`,
3424which are optimization hints to enable otherwise unsafe floating point
3425optimizations:
3426
3427Example:
3428""""""""
3429
3430.. code-block:: llvm
3431
3432 <result> = fadd float 4.0, %var ; yields {float}:result = 4.0 + %var
3433
3434'``sub``' Instruction
3435^^^^^^^^^^^^^^^^^^^^^
3436
3437Syntax:
3438"""""""
3439
3440::
3441
3442 <result> = sub <ty> <op1>, <op2> ; yields {ty}:result
3443 <result> = sub nuw <ty> <op1>, <op2> ; yields {ty}:result
3444 <result> = sub nsw <ty> <op1>, <op2> ; yields {ty}:result
3445 <result> = sub nuw nsw <ty> <op1>, <op2> ; yields {ty}:result
3446
3447Overview:
3448"""""""""
3449
3450The '``sub``' instruction returns the difference of its two operands.
3451
3452Note that the '``sub``' instruction is used to represent the '``neg``'
3453instruction present in most other intermediate representations.
3454
3455Arguments:
3456""""""""""
3457
3458The two arguments to the '``sub``' instruction must be
3459:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
3460arguments must have identical types.
3461
3462Semantics:
3463""""""""""
3464
3465The value produced is the integer difference of the two operands.
3466
3467If the difference has unsigned overflow, the result returned is the
3468mathematical result modulo 2\ :sup:`n`\ , where n is the bit width of
3469the result.
3470
3471Because LLVM integers use a two's complement representation, this
3472instruction is appropriate for both signed and unsigned integers.
3473
3474``nuw`` and ``nsw`` stand for "No Unsigned Wrap" and "No Signed Wrap",
3475respectively. If the ``nuw`` and/or ``nsw`` keywords are present, the
3476result value of the ``sub`` is a :ref:`poison value <poisonvalues>` if
3477unsigned and/or signed overflow, respectively, occurs.
3478
3479Example:
3480""""""""
3481
3482.. code-block:: llvm
3483
3484 <result> = sub i32 4, %var ; yields {i32}:result = 4 - %var
3485 <result> = sub i32 0, %val ; yields {i32}:result = -%var
3486
3487.. _i_fsub:
3488
3489'``fsub``' Instruction
3490^^^^^^^^^^^^^^^^^^^^^^
3491
3492Syntax:
3493"""""""
3494
3495::
3496
3497 <result> = fsub [fast-math flags]* <ty> <op1>, <op2> ; yields {ty}:result
3498
3499Overview:
3500"""""""""
3501
3502The '``fsub``' instruction returns the difference of its two operands.
3503
3504Note that the '``fsub``' instruction is used to represent the '``fneg``'
3505instruction present in most other intermediate representations.
3506
3507Arguments:
3508""""""""""
3509
3510The two arguments to the '``fsub``' instruction must be :ref:`floating
3511point <t_floating>` or :ref:`vector <t_vector>` of floating point values.
3512Both arguments must have identical types.
3513
3514Semantics:
3515""""""""""
3516
3517The value produced is the floating point difference of the two operands.
3518This instruction can also take any number of :ref:`fast-math
3519flags <fastmath>`, which are optimization hints to enable otherwise
3520unsafe floating point optimizations:
3521
3522Example:
3523""""""""
3524
3525.. code-block:: llvm
3526
3527 <result> = fsub float 4.0, %var ; yields {float}:result = 4.0 - %var
3528 <result> = fsub float -0.0, %val ; yields {float}:result = -%var
3529
3530'``mul``' Instruction
3531^^^^^^^^^^^^^^^^^^^^^
3532
3533Syntax:
3534"""""""
3535
3536::
3537
3538 <result> = mul <ty> <op1>, <op2> ; yields {ty}:result
3539 <result> = mul nuw <ty> <op1>, <op2> ; yields {ty}:result
3540 <result> = mul nsw <ty> <op1>, <op2> ; yields {ty}:result
3541 <result> = mul nuw nsw <ty> <op1>, <op2> ; yields {ty}:result
3542
3543Overview:
3544"""""""""
3545
3546The '``mul``' instruction returns the product of its two operands.
3547
3548Arguments:
3549""""""""""
3550
3551The two arguments to the '``mul``' instruction must be
3552:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
3553arguments must have identical types.
3554
3555Semantics:
3556""""""""""
3557
3558The value produced is the integer product of the two operands.
3559
3560If the result of the multiplication has unsigned overflow, the result
3561returned is the mathematical result modulo 2\ :sup:`n`\ , where n is the
3562bit width of the result.
3563
3564Because LLVM integers use a two's complement representation, and the
3565result is the same width as the operands, this instruction returns the
3566correct result for both signed and unsigned integers. If a full product
3567(e.g. ``i32`` * ``i32`` -> ``i64``) is needed, the operands should be
3568sign-extended or zero-extended as appropriate to the width of the full
3569product.
3570
3571``nuw`` and ``nsw`` stand for "No Unsigned Wrap" and "No Signed Wrap",
3572respectively. If the ``nuw`` and/or ``nsw`` keywords are present, the
3573result value of the ``mul`` is a :ref:`poison value <poisonvalues>` if
3574unsigned and/or signed overflow, respectively, occurs.
3575
3576Example:
3577""""""""
3578
3579.. code-block:: llvm
3580
3581 <result> = mul i32 4, %var ; yields {i32}:result = 4 * %var
3582
3583.. _i_fmul:
3584
3585'``fmul``' Instruction
3586^^^^^^^^^^^^^^^^^^^^^^
3587
3588Syntax:
3589"""""""
3590
3591::
3592
3593 <result> = fmul [fast-math flags]* <ty> <op1>, <op2> ; yields {ty}:result
3594
3595Overview:
3596"""""""""
3597
3598The '``fmul``' instruction returns the product of its two operands.
3599
3600Arguments:
3601""""""""""
3602
3603The two arguments to the '``fmul``' instruction must be :ref:`floating
3604point <t_floating>` or :ref:`vector <t_vector>` of floating point values.
3605Both arguments must have identical types.
3606
3607Semantics:
3608""""""""""
3609
3610The value produced is the floating point product of the two operands.
3611This instruction can also take any number of :ref:`fast-math
3612flags <fastmath>`, which are optimization hints to enable otherwise
3613unsafe floating point optimizations:
3614
3615Example:
3616""""""""
3617
3618.. code-block:: llvm
3619
3620 <result> = fmul float 4.0, %var ; yields {float}:result = 4.0 * %var
3621
3622'``udiv``' Instruction
3623^^^^^^^^^^^^^^^^^^^^^^
3624
3625Syntax:
3626"""""""
3627
3628::
3629
3630 <result> = udiv <ty> <op1>, <op2> ; yields {ty}:result
3631 <result> = udiv exact <ty> <op1>, <op2> ; yields {ty}:result
3632
3633Overview:
3634"""""""""
3635
3636The '``udiv``' instruction returns the quotient of its two operands.
3637
3638Arguments:
3639""""""""""
3640
3641The two arguments to the '``udiv``' instruction must be
3642:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
3643arguments must have identical types.
3644
3645Semantics:
3646""""""""""
3647
3648The value produced is the unsigned integer quotient of the two operands.
3649
3650Note that unsigned integer division and signed integer division are
3651distinct operations; for signed integer division, use '``sdiv``'.
3652
3653Division by zero leads to undefined behavior.
3654
3655If the ``exact`` keyword is present, the result value of the ``udiv`` is
3656a :ref:`poison value <poisonvalues>` if %op1 is not a multiple of %op2 (as
3657such, "((a udiv exact b) mul b) == a").
3658
3659Example:
3660""""""""
3661
3662.. code-block:: llvm
3663
3664 <result> = udiv i32 4, %var ; yields {i32}:result = 4 / %var
3665
3666'``sdiv``' Instruction
3667^^^^^^^^^^^^^^^^^^^^^^
3668
3669Syntax:
3670"""""""
3671
3672::
3673
3674 <result> = sdiv <ty> <op1>, <op2> ; yields {ty}:result
3675 <result> = sdiv exact <ty> <op1>, <op2> ; yields {ty}:result
3676
3677Overview:
3678"""""""""
3679
3680The '``sdiv``' instruction returns the quotient of its two operands.
3681
3682Arguments:
3683""""""""""
3684
3685The two arguments to the '``sdiv``' instruction must be
3686:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
3687arguments must have identical types.
3688
3689Semantics:
3690""""""""""
3691
3692The value produced is the signed integer quotient of the two operands
3693rounded towards zero.
3694
3695Note that signed integer division and unsigned integer division are
3696distinct operations; for unsigned integer division, use '``udiv``'.
3697
3698Division by zero leads to undefined behavior. Overflow also leads to
3699undefined behavior; this is a rare case, but can occur, for example, by
3700doing a 32-bit division of -2147483648 by -1.
3701
3702If the ``exact`` keyword is present, the result value of the ``sdiv`` is
3703a :ref:`poison value <poisonvalues>` if the result would be rounded.
3704
3705Example:
3706""""""""
3707
3708.. code-block:: llvm
3709
3710 <result> = sdiv i32 4, %var ; yields {i32}:result = 4 / %var
3711
3712.. _i_fdiv:
3713
3714'``fdiv``' Instruction
3715^^^^^^^^^^^^^^^^^^^^^^
3716
3717Syntax:
3718"""""""
3719
3720::
3721
3722 <result> = fdiv [fast-math flags]* <ty> <op1>, <op2> ; yields {ty}:result
3723
3724Overview:
3725"""""""""
3726
3727The '``fdiv``' instruction returns the quotient of its two operands.
3728
3729Arguments:
3730""""""""""
3731
3732The two arguments to the '``fdiv``' instruction must be :ref:`floating
3733point <t_floating>` or :ref:`vector <t_vector>` of floating point values.
3734Both arguments must have identical types.
3735
3736Semantics:
3737""""""""""
3738
3739The value produced is the floating point quotient of the two operands.
3740This instruction can also take any number of :ref:`fast-math
3741flags <fastmath>`, which are optimization hints to enable otherwise
3742unsafe floating point optimizations:
3743
3744Example:
3745""""""""
3746
3747.. code-block:: llvm
3748
3749 <result> = fdiv float 4.0, %var ; yields {float}:result = 4.0 / %var
3750
3751'``urem``' Instruction
3752^^^^^^^^^^^^^^^^^^^^^^
3753
3754Syntax:
3755"""""""
3756
3757::
3758
3759 <result> = urem <ty> <op1>, <op2> ; yields {ty}:result
3760
3761Overview:
3762"""""""""
3763
3764The '``urem``' instruction returns the remainder from the unsigned
3765division of its two arguments.
3766
3767Arguments:
3768""""""""""
3769
3770The two arguments to the '``urem``' instruction must be
3771:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
3772arguments must have identical types.
3773
3774Semantics:
3775""""""""""
3776
3777This instruction returns the unsigned integer *remainder* of a division.
3778This instruction always performs an unsigned division to get the
3779remainder.
3780
3781Note that unsigned integer remainder and signed integer remainder are
3782distinct operations; for signed integer remainder, use '``srem``'.
3783
3784Taking the remainder of a division by zero leads to undefined behavior.
3785
3786Example:
3787""""""""
3788
3789.. code-block:: llvm
3790
3791 <result> = urem i32 4, %var ; yields {i32}:result = 4 % %var
3792
3793'``srem``' Instruction
3794^^^^^^^^^^^^^^^^^^^^^^
3795
3796Syntax:
3797"""""""
3798
3799::
3800
3801 <result> = srem <ty> <op1>, <op2> ; yields {ty}:result
3802
3803Overview:
3804"""""""""
3805
3806The '``srem``' instruction returns the remainder from the signed
3807division of its two operands. This instruction can also take
3808:ref:`vector <t_vector>` versions of the values in which case the elements
3809must be integers.
3810
3811Arguments:
3812""""""""""
3813
3814The two arguments to the '``srem``' instruction must be
3815:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
3816arguments must have identical types.
3817
3818Semantics:
3819""""""""""
3820
3821This instruction returns the *remainder* of a division (where the result
3822is either zero or has the same sign as the dividend, ``op1``), not the
3823*modulo* operator (where the result is either zero or has the same sign
3824as the divisor, ``op2``) of a value. For more information about the
3825difference, see `The Math
3826Forum <http://mathforum.org/dr.math/problems/anne.4.28.99.html>`_. For a
3827table of how this is implemented in various languages, please see
3828`Wikipedia: modulo
3829operation <http://en.wikipedia.org/wiki/Modulo_operation>`_.
3830
3831Note that signed integer remainder and unsigned integer remainder are
3832distinct operations; for unsigned integer remainder, use '``urem``'.
3833
3834Taking the remainder of a division by zero leads to undefined behavior.
3835Overflow also leads to undefined behavior; this is a rare case, but can
3836occur, for example, by taking the remainder of a 32-bit division of
3837-2147483648 by -1. (The remainder doesn't actually overflow, but this
3838rule lets srem be implemented using instructions that return both the
3839result of the division and the remainder.)
3840
3841Example:
3842""""""""
3843
3844.. code-block:: llvm
3845
3846 <result> = srem i32 4, %var ; yields {i32}:result = 4 % %var
3847
3848.. _i_frem:
3849
3850'``frem``' Instruction
3851^^^^^^^^^^^^^^^^^^^^^^
3852
3853Syntax:
3854"""""""
3855
3856::
3857
3858 <result> = frem [fast-math flags]* <ty> <op1>, <op2> ; yields {ty}:result
3859
3860Overview:
3861"""""""""
3862
3863The '``frem``' instruction returns the remainder from the division of
3864its two operands.
3865
3866Arguments:
3867""""""""""
3868
3869The two arguments to the '``frem``' instruction must be :ref:`floating
3870point <t_floating>` or :ref:`vector <t_vector>` of floating point values.
3871Both arguments must have identical types.
3872
3873Semantics:
3874""""""""""
3875
3876This instruction returns the *remainder* of a division. The remainder
3877has the same sign as the dividend. This instruction can also take any
3878number of :ref:`fast-math flags <fastmath>`, which are optimization hints
3879to enable otherwise unsafe floating point optimizations:
3880
3881Example:
3882""""""""
3883
3884.. code-block:: llvm
3885
3886 <result> = frem float 4.0, %var ; yields {float}:result = 4.0 % %var
3887
3888.. _bitwiseops:
3889
3890Bitwise Binary Operations
3891-------------------------
3892
3893Bitwise binary operators are used to do various forms of bit-twiddling
3894in a program. They are generally very efficient instructions and can
3895commonly be strength reduced from other instructions. They require two
3896operands of the same type, execute an operation on them, and produce a
3897single value. The resulting value is the same type as its operands.
3898
3899'``shl``' Instruction
3900^^^^^^^^^^^^^^^^^^^^^
3901
3902Syntax:
3903"""""""
3904
3905::
3906
3907 <result> = shl <ty> <op1>, <op2> ; yields {ty}:result
3908 <result> = shl nuw <ty> <op1>, <op2> ; yields {ty}:result
3909 <result> = shl nsw <ty> <op1>, <op2> ; yields {ty}:result
3910 <result> = shl nuw nsw <ty> <op1>, <op2> ; yields {ty}:result
3911
3912Overview:
3913"""""""""
3914
3915The '``shl``' instruction returns the first operand shifted to the left
3916a specified number of bits.
3917
3918Arguments:
3919""""""""""
3920
3921Both arguments to the '``shl``' instruction must be the same
3922:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer type.
3923'``op2``' is treated as an unsigned value.
3924
3925Semantics:
3926""""""""""
3927
3928The value produced is ``op1`` \* 2\ :sup:`op2` mod 2\ :sup:`n`,
3929where ``n`` is the width of the result. If ``op2`` is (statically or
3930dynamically) negative or equal to or larger than the number of bits in
3931``op1``, the result is undefined. If the arguments are vectors, each
3932vector element of ``op1`` is shifted by the corresponding shift amount
3933in ``op2``.
3934
3935If the ``nuw`` keyword is present, then the shift produces a :ref:`poison
3936value <poisonvalues>` if it shifts out any non-zero bits. If the
3937``nsw`` keyword is present, then the shift produces a :ref:`poison
3938value <poisonvalues>` if it shifts out any bits that disagree with the
3939resultant sign bit. As such, NUW/NSW have the same semantics as they
3940would if the shift were expressed as a mul instruction with the same
3941nsw/nuw bits in (mul %op1, (shl 1, %op2)).
3942
3943Example:
3944""""""""
3945
3946.. code-block:: llvm
3947
3948 <result> = shl i32 4, %var ; yields {i32}: 4 << %var
3949 <result> = shl i32 4, 2 ; yields {i32}: 16
3950 <result> = shl i32 1, 10 ; yields {i32}: 1024
3951 <result> = shl i32 1, 32 ; undefined
3952 <result> = shl <2 x i32> < i32 1, i32 1>, < i32 1, i32 2> ; yields: result=<2 x i32> < i32 2, i32 4>
3953
3954'``lshr``' Instruction
3955^^^^^^^^^^^^^^^^^^^^^^
3956
3957Syntax:
3958"""""""
3959
3960::
3961
3962 <result> = lshr <ty> <op1>, <op2> ; yields {ty}:result
3963 <result> = lshr exact <ty> <op1>, <op2> ; yields {ty}:result
3964
3965Overview:
3966"""""""""
3967
3968The '``lshr``' instruction (logical shift right) returns the first
3969operand shifted to the right a specified number of bits with zero fill.
3970
3971Arguments:
3972""""""""""
3973
3974Both arguments to the '``lshr``' instruction must be the same
3975:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer type.
3976'``op2``' is treated as an unsigned value.
3977
3978Semantics:
3979""""""""""
3980
3981This instruction always performs a logical shift right operation. The
3982most significant bits of the result will be filled with zero bits after
3983the shift. If ``op2`` is (statically or dynamically) equal to or larger
3984than the number of bits in ``op1``, the result is undefined. If the
3985arguments are vectors, each vector element of ``op1`` is shifted by the
3986corresponding shift amount in ``op2``.
3987
3988If the ``exact`` keyword is present, the result value of the ``lshr`` is
3989a :ref:`poison value <poisonvalues>` if any of the bits shifted out are
3990non-zero.
3991
3992Example:
3993""""""""
3994
3995.. code-block:: llvm
3996
3997 <result> = lshr i32 4, 1 ; yields {i32}:result = 2
3998 <result> = lshr i32 4, 2 ; yields {i32}:result = 1
3999 <result> = lshr i8 4, 3 ; yields {i8}:result = 0
4000 <result> = lshr i8 -2, 1 ; yields {i8}:result = 0x7FFFFFFF
4001 <result> = lshr i32 1, 32 ; undefined
4002 <result> = lshr <2 x i32> < i32 -2, i32 4>, < i32 1, i32 2> ; yields: result=<2 x i32> < i32 0x7FFFFFFF, i32 1>
4003
4004'``ashr``' Instruction
4005^^^^^^^^^^^^^^^^^^^^^^
4006
4007Syntax:
4008"""""""
4009
4010::
4011
4012 <result> = ashr <ty> <op1>, <op2> ; yields {ty}:result
4013 <result> = ashr exact <ty> <op1>, <op2> ; yields {ty}:result
4014
4015Overview:
4016"""""""""
4017
4018The '``ashr``' instruction (arithmetic shift right) returns the first
4019operand shifted to the right a specified number of bits with sign
4020extension.
4021
4022Arguments:
4023""""""""""
4024
4025Both arguments to the '``ashr``' instruction must be the same
4026:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer type.
4027'``op2``' is treated as an unsigned value.
4028
4029Semantics:
4030""""""""""
4031
4032This instruction always performs an arithmetic shift right operation,
4033The most significant bits of the result will be filled with the sign bit
4034of ``op1``. If ``op2`` is (statically or dynamically) equal to or larger
4035than the number of bits in ``op1``, the result is undefined. If the
4036arguments are vectors, each vector element of ``op1`` is shifted by the
4037corresponding shift amount in ``op2``.
4038
4039If the ``exact`` keyword is present, the result value of the ``ashr`` is
4040a :ref:`poison value <poisonvalues>` if any of the bits shifted out are
4041non-zero.
4042
4043Example:
4044""""""""
4045
4046.. code-block:: llvm
4047
4048 <result> = ashr i32 4, 1 ; yields {i32}:result = 2
4049 <result> = ashr i32 4, 2 ; yields {i32}:result = 1
4050 <result> = ashr i8 4, 3 ; yields {i8}:result = 0
4051 <result> = ashr i8 -2, 1 ; yields {i8}:result = -1
4052 <result> = ashr i32 1, 32 ; undefined
4053 <result> = ashr <2 x i32> < i32 -2, i32 4>, < i32 1, i32 3> ; yields: result=<2 x i32> < i32 -1, i32 0>
4054
4055'``and``' Instruction
4056^^^^^^^^^^^^^^^^^^^^^
4057
4058Syntax:
4059"""""""
4060
4061::
4062
4063 <result> = and <ty> <op1>, <op2> ; yields {ty}:result
4064
4065Overview:
4066"""""""""
4067
4068The '``and``' instruction returns the bitwise logical and of its two
4069operands.
4070
4071Arguments:
4072""""""""""
4073
4074The two arguments to the '``and``' instruction must be
4075:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
4076arguments must have identical types.
4077
4078Semantics:
4079""""""""""
4080
4081The truth table used for the '``and``' instruction is:
4082
4083+-----+-----+-----+
4084| In0 | In1 | Out |
4085+-----+-----+-----+
4086| 0 | 0 | 0 |
4087+-----+-----+-----+
4088| 0 | 1 | 0 |
4089+-----+-----+-----+
4090| 1 | 0 | 0 |
4091+-----+-----+-----+
4092| 1 | 1 | 1 |
4093+-----+-----+-----+
4094
4095Example:
4096""""""""
4097
4098.. code-block:: llvm
4099
4100 <result> = and i32 4, %var ; yields {i32}:result = 4 & %var
4101 <result> = and i32 15, 40 ; yields {i32}:result = 8
4102 <result> = and i32 4, 8 ; yields {i32}:result = 0
4103
4104'``or``' Instruction
4105^^^^^^^^^^^^^^^^^^^^
4106
4107Syntax:
4108"""""""
4109
4110::
4111
4112 <result> = or <ty> <op1>, <op2> ; yields {ty}:result
4113
4114Overview:
4115"""""""""
4116
4117The '``or``' instruction returns the bitwise logical inclusive or of its
4118two operands.
4119
4120Arguments:
4121""""""""""
4122
4123The two arguments to the '``or``' instruction must be
4124:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
4125arguments must have identical types.
4126
4127Semantics:
4128""""""""""
4129
4130The truth table used for the '``or``' instruction is:
4131
4132+-----+-----+-----+
4133| In0 | In1 | Out |
4134+-----+-----+-----+
4135| 0 | 0 | 0 |
4136+-----+-----+-----+
4137| 0 | 1 | 1 |
4138+-----+-----+-----+
4139| 1 | 0 | 1 |
4140+-----+-----+-----+
4141| 1 | 1 | 1 |
4142+-----+-----+-----+
4143
4144Example:
4145""""""""
4146
4147::
4148
4149 <result> = or i32 4, %var ; yields {i32}:result = 4 | %var
4150 <result> = or i32 15, 40 ; yields {i32}:result = 47
4151 <result> = or i32 4, 8 ; yields {i32}:result = 12
4152
4153'``xor``' Instruction
4154^^^^^^^^^^^^^^^^^^^^^
4155
4156Syntax:
4157"""""""
4158
4159::
4160
4161 <result> = xor <ty> <op1>, <op2> ; yields {ty}:result
4162
4163Overview:
4164"""""""""
4165
4166The '``xor``' instruction returns the bitwise logical exclusive or of
4167its two operands. The ``xor`` is used to implement the "one's
4168complement" operation, which is the "~" operator in C.
4169
4170Arguments:
4171""""""""""
4172
4173The two arguments to the '``xor``' instruction must be
4174:ref:`integer <t_integer>` or :ref:`vector <t_vector>` of integer values. Both
4175arguments must have identical types.
4176
4177Semantics:
4178""""""""""
4179
4180The truth table used for the '``xor``' instruction is:
4181
4182+-----+-----+-----+
4183| In0 | In1 | Out |
4184+-----+-----+-----+
4185| 0 | 0 | 0 |
4186+-----+-----+-----+
4187| 0 | 1 | 1 |
4188+-----+-----+-----+
4189| 1 | 0 | 1 |
4190+-----+-----+-----+
4191| 1 | 1 | 0 |
4192+-----+-----+-----+
4193
4194Example:
4195""""""""
4196
4197.. code-block:: llvm
4198
4199 <result> = xor i32 4, %var ; yields {i32}:result = 4 ^ %var
4200 <result> = xor i32 15, 40 ; yields {i32}:result = 39
4201 <result> = xor i32 4, 8 ; yields {i32}:result = 12
4202 <result> = xor i32 %V, -1 ; yields {i32}:result = ~%V
4203
4204Vector Operations
4205-----------------
4206
4207LLVM supports several instructions to represent vector operations in a
4208target-independent manner. These instructions cover the element-access
4209and vector-specific operations needed to process vectors effectively.
4210While LLVM does directly support these vector operations, many
4211sophisticated algorithms will want to use target-specific intrinsics to
4212take full advantage of a specific target.
4213
4214.. _i_extractelement:
4215
4216'``extractelement``' Instruction
4217^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4218
4219Syntax:
4220"""""""
4221
4222::
4223
4224 <result> = extractelement <n x <ty>> <val>, i32 <idx> ; yields <ty>
4225
4226Overview:
4227"""""""""
4228
4229The '``extractelement``' instruction extracts a single scalar element
4230from a vector at a specified index.
4231
4232Arguments:
4233""""""""""
4234
4235The first operand of an '``extractelement``' instruction is a value of
4236:ref:`vector <t_vector>` type. The second operand is an index indicating
4237the position from which to extract the element. The index may be a
4238variable.
4239
4240Semantics:
4241""""""""""
4242
4243The result is a scalar of the same type as the element type of ``val``.
4244Its value is the value at position ``idx`` of ``val``. If ``idx``
4245exceeds the length of ``val``, the results are undefined.
4246
4247Example:
4248""""""""
4249
4250.. code-block:: llvm
4251
4252 <result> = extractelement <4 x i32> %vec, i32 0 ; yields i32
4253
4254.. _i_insertelement:
4255
4256'``insertelement``' Instruction
4257^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4258
4259Syntax:
4260"""""""
4261
4262::
4263
4264 <result> = insertelement <n x <ty>> <val>, <ty> <elt>, i32 <idx> ; yields <n x <ty>>
4265
4266Overview:
4267"""""""""
4268
4269The '``insertelement``' instruction inserts a scalar element into a
4270vector at a specified index.
4271
4272Arguments:
4273""""""""""
4274
4275The first operand of an '``insertelement``' instruction is a value of
4276:ref:`vector <t_vector>` type. The second operand is a scalar value whose
4277type must equal the element type of the first operand. The third operand
4278is an index indicating the position at which to insert the value. The
4279index may be a variable.
4280
4281Semantics:
4282""""""""""
4283
4284The result is a vector of the same type as ``val``. Its element values
4285are those of ``val`` except at position ``idx``, where it gets the value
4286``elt``. If ``idx`` exceeds the length of ``val``, the results are
4287undefined.
4288
4289Example:
4290""""""""
4291
4292.. code-block:: llvm
4293
4294 <result> = insertelement <4 x i32> %vec, i32 1, i32 0 ; yields <4 x i32>
4295
4296.. _i_shufflevector:
4297
4298'``shufflevector``' Instruction
4299^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4300
4301Syntax:
4302"""""""
4303
4304::
4305
4306 <result> = shufflevector <n x <ty>> <v1>, <n x <ty>> <v2>, <m x i32> <mask> ; yields <m x <ty>>
4307
4308Overview:
4309"""""""""
4310
4311The '``shufflevector``' instruction constructs a permutation of elements
4312from two input vectors, returning a vector with the same element type as
4313the input and length that is the same as the shuffle mask.
4314
4315Arguments:
4316""""""""""
4317
4318The first two operands of a '``shufflevector``' instruction are vectors
4319with the same type. The third argument is a shuffle mask whose element
4320type is always 'i32'. The result of the instruction is a vector whose
4321length is the same as the shuffle mask and whose element type is the
4322same as the element type of the first two operands.
4323
4324The shuffle mask operand is required to be a constant vector with either
4325constant integer or undef values.
4326
4327Semantics:
4328""""""""""
4329
4330The elements of the two input vectors are numbered from left to right
4331across both of the vectors. The shuffle mask operand specifies, for each
4332element of the result vector, which element of the two input vectors the
4333result element gets. The element selector may be undef (meaning "don't
4334care") and the second operand may be undef if performing a shuffle from
4335only one vector.
4336
4337Example:
4338""""""""
4339
4340.. code-block:: llvm
4341
4342 <result> = shufflevector <4 x i32> %v1, <4 x i32> %v2,
4343 <4 x i32> <i32 0, i32 4, i32 1, i32 5> ; yields <4 x i32>
4344 <result> = shufflevector <4 x i32> %v1, <4 x i32> undef,
4345 <4 x i32> <i32 0, i32 1, i32 2, i32 3> ; yields <4 x i32> - Identity shuffle.
4346 <result> = shufflevector <8 x i32> %v1, <8 x i32> undef,
4347 <4 x i32> <i32 0, i32 1, i32 2, i32 3> ; yields <4 x i32>
4348 <result> = shufflevector <4 x i32> %v1, <4 x i32> %v2,
4349 <8 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7 > ; yields <8 x i32>
4350
4351Aggregate Operations
4352--------------------
4353
4354LLVM supports several instructions for working with
4355:ref:`aggregate <t_aggregate>` values.
4356
4357.. _i_extractvalue:
4358
4359'``extractvalue``' Instruction
4360^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4361
4362Syntax:
4363"""""""
4364
4365::
4366
4367 <result> = extractvalue <aggregate type> <val>, <idx>{, <idx>}*
4368
4369Overview:
4370"""""""""
4371
4372The '``extractvalue``' instruction extracts the value of a member field
4373from an :ref:`aggregate <t_aggregate>` value.
4374
4375Arguments:
4376""""""""""
4377
4378The first operand of an '``extractvalue``' instruction is a value of
4379:ref:`struct <t_struct>` or :ref:`array <t_array>` type. The operands are
4380constant indices to specify which value to extract in a similar manner
4381as indices in a '``getelementptr``' instruction.
4382
4383The major differences to ``getelementptr`` indexing are:
4384
4385- Since the value being indexed is not a pointer, the first index is
4386 omitted and assumed to be zero.
4387- At least one index must be specified.
4388- Not only struct indices but also array indices must be in bounds.
4389
4390Semantics:
4391""""""""""
4392
4393The result is the value at the position in the aggregate specified by
4394the index operands.
4395
4396Example:
4397""""""""
4398
4399.. code-block:: llvm
4400
4401 <result> = extractvalue {i32, float} %agg, 0 ; yields i32
4402
4403.. _i_insertvalue:
4404
4405'``insertvalue``' Instruction
4406^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4407
4408Syntax:
4409"""""""
4410
4411::
4412
4413 <result> = insertvalue <aggregate type> <val>, <ty> <elt>, <idx>{, <idx>}* ; yields <aggregate type>
4414
4415Overview:
4416"""""""""
4417
4418The '``insertvalue``' instruction inserts a value into a member field in
4419an :ref:`aggregate <t_aggregate>` value.
4420
4421Arguments:
4422""""""""""
4423
4424The first operand of an '``insertvalue``' instruction is a value of
4425:ref:`struct <t_struct>` or :ref:`array <t_array>` type. The second operand is
4426a first-class value to insert. The following operands are constant
4427indices indicating the position at which to insert the value in a
4428similar manner as indices in a '``extractvalue``' instruction. The value
4429to insert must have the same type as the value identified by the
4430indices.
4431
4432Semantics:
4433""""""""""
4434
4435The result is an aggregate of the same type as ``val``. Its value is
4436that of ``val`` except that the value at the position specified by the
4437indices is that of ``elt``.
4438
4439Example:
4440""""""""
4441
4442.. code-block:: llvm
4443
4444 %agg1 = insertvalue {i32, float} undef, i32 1, 0 ; yields {i32 1, float undef}
4445 %agg2 = insertvalue {i32, float} %agg1, float %val, 1 ; yields {i32 1, float %val}
4446 %agg3 = insertvalue {i32, {float}} %agg1, float %val, 1, 0 ; yields {i32 1, float %val}
4447
4448.. _memoryops:
4449
4450Memory Access and Addressing Operations
4451---------------------------------------
4452
4453A key design point of an SSA-based representation is how it represents
4454memory. In LLVM, no memory locations are in SSA form, which makes things
4455very simple. This section describes how to read, write, and allocate
4456memory in LLVM.
4457
4458.. _i_alloca:
4459
4460'``alloca``' Instruction
4461^^^^^^^^^^^^^^^^^^^^^^^^
4462
4463Syntax:
4464"""""""
4465
4466::
4467
4468 <result> = alloca <type>[, <ty> <NumElements>][, align <alignment>] ; yields {type*}:result
4469
4470Overview:
4471"""""""""
4472
4473The '``alloca``' instruction allocates memory on the stack frame of the
4474currently executing function, to be automatically released when this
4475function returns to its caller. The object is always allocated in the
4476generic address space (address space zero).
4477
4478Arguments:
4479""""""""""
4480
4481The '``alloca``' instruction allocates ``sizeof(<type>)*NumElements``
4482bytes of memory on the runtime stack, returning a pointer of the
4483appropriate type to the program. If "NumElements" is specified, it is
4484the number of elements allocated, otherwise "NumElements" is defaulted
4485to be one. If a constant alignment is specified, the value result of the
4486allocation is guaranteed to be aligned to at least that boundary. If not
4487specified, or if zero, the target can choose to align the allocation on
4488any convenient boundary compatible with the type.
4489
4490'``type``' may be any sized type.
4491
4492Semantics:
4493""""""""""
4494
4495Memory is allocated; a pointer is returned. The operation is undefined
4496if there is insufficient stack space for the allocation. '``alloca``'d
4497memory is automatically released when the function returns. The
4498'``alloca``' instruction is commonly used to represent automatic
4499variables that must have an address available. When the function returns
4500(either with the ``ret`` or ``resume`` instructions), the memory is
4501reclaimed. Allocating zero bytes is legal, but the result is undefined.
4502The order in which memory is allocated (ie., which way the stack grows)
4503is not specified.
4504
4505Example:
4506""""""""
4507
4508.. code-block:: llvm
4509
4510 %ptr = alloca i32 ; yields {i32*}:ptr
4511 %ptr = alloca i32, i32 4 ; yields {i32*}:ptr
4512 %ptr = alloca i32, i32 4, align 1024 ; yields {i32*}:ptr
4513 %ptr = alloca i32, align 1024 ; yields {i32*}:ptr
4514
4515.. _i_load:
4516
4517'``load``' Instruction
4518^^^^^^^^^^^^^^^^^^^^^^
4519
4520Syntax:
4521"""""""
4522
4523::
4524
4525 <result> = load [volatile] <ty>* <pointer>[, align <alignment>][, !nontemporal !<index>][, !invariant.load !<index>]
4526 <result> = load atomic [volatile] <ty>* <pointer> [singlethread] <ordering>, align <alignment>
4527 !<index> = !{ i32 1 }
4528
4529Overview:
4530"""""""""
4531
4532The '``load``' instruction is used to read from memory.
4533
4534Arguments:
4535""""""""""
4536
4537The argument to the '``load``' instruction specifies the memory address
4538from which to load. The pointer must point to a :ref:`first
4539class <t_firstclass>` type. If the ``load`` is marked as ``volatile``,
4540then the optimizer is not allowed to modify the number or order of
4541execution of this ``load`` with other :ref:`volatile
4542operations <volatile>`.
4543
4544If the ``load`` is marked as ``atomic``, it takes an extra
4545:ref:`ordering <ordering>` and optional ``singlethread`` argument. The
4546``release`` and ``acq_rel`` orderings are not valid on ``load``
4547instructions. Atomic loads produce :ref:`defined <memmodel>` results
4548when they may see multiple atomic stores. The type of the pointee must
4549be an integer type whose bit width is a power of two greater than or
4550equal to eight and less than or equal to a target-specific size limit.
4551``align`` must be explicitly specified on atomic loads, and the load has
4552undefined behavior if the alignment is not set to a value which is at
4553least the size in bytes of the pointee. ``!nontemporal`` does not have
4554any defined semantics for atomic loads.
4555
4556The optional constant ``align`` argument specifies the alignment of the
4557operation (that is, the alignment of the memory address). A value of 0
4558or an omitted ``align`` argument means that the operation has the abi
4559alignment for the target. It is the responsibility of the code emitter
4560to ensure that the alignment information is correct. Overestimating the
4561alignment results in undefined behavior. Underestimating the alignment
4562may produce less efficient code. An alignment of 1 is always safe.
4563
4564The optional ``!nontemporal`` metadata must reference a single
4565metatadata name <index> corresponding to a metadata node with one
4566``i32`` entry of value 1. The existence of the ``!nontemporal``
4567metatadata on the instruction tells the optimizer and code generator
4568that this load is not expected to be reused in the cache. The code
4569generator may select special instructions to save cache bandwidth, such
4570as the ``MOVNT`` instruction on x86.
4571
4572The optional ``!invariant.load`` metadata must reference a single
4573metatadata name <index> corresponding to a metadata node with no
4574entries. The existence of the ``!invariant.load`` metatadata on the
4575instruction tells the optimizer and code generator that this load
4576address points to memory which does not change value during program
4577execution. The optimizer may then move this load around, for example, by
4578hoisting it out of loops using loop invariant code motion.
4579
4580Semantics:
4581""""""""""
4582
4583The location of memory pointed to is loaded. If the value being loaded
4584is of scalar type then the number of bytes read does not exceed the
4585minimum number of bytes needed to hold all bits of the type. For
4586example, loading an ``i24`` reads at most three bytes. When loading a
4587value of a type like ``i20`` with a size that is not an integral number
4588of bytes, the result is undefined if the value was not originally
4589written using a store of the same type.
4590
4591Examples:
4592"""""""""
4593
4594.. code-block:: llvm
4595
4596 %ptr = alloca i32 ; yields {i32*}:ptr
4597 store i32 3, i32* %ptr ; yields {void}
4598 %val = load i32* %ptr ; yields {i32}:val = i32 3
4599
4600.. _i_store:
4601
4602'``store``' Instruction
4603^^^^^^^^^^^^^^^^^^^^^^^
4604
4605Syntax:
4606"""""""
4607
4608::
4609
4610 store [volatile] <ty> <value>, <ty>* <pointer>[, align <alignment>][, !nontemporal !<index>] ; yields {void}
4611 store atomic [volatile] <ty> <value>, <ty>* <pointer> [singlethread] <ordering>, align <alignment> ; yields {void}
4612
4613Overview:
4614"""""""""
4615
4616The '``store``' instruction is used to write to memory.
4617
4618Arguments:
4619""""""""""
4620
4621There are two arguments to the '``store``' instruction: a value to store
4622and an address at which to store it. The type of the '``<pointer>``'
4623operand must be a pointer to the :ref:`first class <t_firstclass>` type of
4624the '``<value>``' operand. If the ``store`` is marked as ``volatile``,
4625then the optimizer is not allowed to modify the number or order of
4626execution of this ``store`` with other :ref:`volatile
4627operations <volatile>`.
4628
4629If the ``store`` is marked as ``atomic``, it takes an extra
4630:ref:`ordering <ordering>` and optional ``singlethread`` argument. The
4631``acquire`` and ``acq_rel`` orderings aren't valid on ``store``
4632instructions. Atomic loads produce :ref:`defined <memmodel>` results
4633when they may see multiple atomic stores. The type of the pointee must
4634be an integer type whose bit width is a power of two greater than or
4635equal to eight and less than or equal to a target-specific size limit.
4636``align`` must be explicitly specified on atomic stores, and the store
4637has undefined behavior if the alignment is not set to a value which is
4638at least the size in bytes of the pointee. ``!nontemporal`` does not
4639have any defined semantics for atomic stores.
4640
4641The optional constant "align" argument specifies the alignment of the
4642operation (that is, the alignment of the memory address). A value of 0
4643or an omitted "align" argument means that the operation has the abi
4644alignment for the target. It is the responsibility of the code emitter
4645to ensure that the alignment information is correct. Overestimating the
4646alignment results in an undefined behavior. Underestimating the
4647alignment may produce less efficient code. An alignment of 1 is always
4648safe.
4649
4650The optional !nontemporal metadata must reference a single metatadata
4651name <index> corresponding to a metadata node with one i32 entry of
4652value 1. The existence of the !nontemporal metatadata on the instruction
4653tells the optimizer and code generator that this load is not expected to
4654be reused in the cache. The code generator may select special
4655instructions to save cache bandwidth, such as the MOVNT instruction on
4656x86.
4657
4658Semantics:
4659""""""""""
4660
4661The contents of memory are updated to contain '``<value>``' at the
4662location specified by the '``<pointer>``' operand. If '``<value>``' is
4663of scalar type then the number of bytes written does not exceed the
4664minimum number of bytes needed to hold all bits of the type. For
4665example, storing an ``i24`` writes at most three bytes. When writing a
4666value of a type like ``i20`` with a size that is not an integral number
4667of bytes, it is unspecified what happens to the extra bits that do not
4668belong to the type, but they will typically be overwritten.
4669
4670Example:
4671""""""""
4672
4673.. code-block:: llvm
4674
4675 %ptr = alloca i32 ; yields {i32*}:ptr
4676 store i32 3, i32* %ptr ; yields {void}
4677 %val = load i32* %ptr ; yields {i32}:val = i32 3
4678
4679.. _i_fence:
4680
4681'``fence``' Instruction
4682^^^^^^^^^^^^^^^^^^^^^^^
4683
4684Syntax:
4685"""""""
4686
4687::
4688
4689 fence [singlethread] <ordering> ; yields {void}
4690
4691Overview:
4692"""""""""
4693
4694The '``fence``' instruction is used to introduce happens-before edges
4695between operations.
4696
4697Arguments:
4698""""""""""
4699
4700'``fence``' instructions take an :ref:`ordering <ordering>` argument which
4701defines what *synchronizes-with* edges they add. They can only be given
4702``acquire``, ``release``, ``acq_rel``, and ``seq_cst`` orderings.
4703
4704Semantics:
4705""""""""""
4706
4707A fence A which has (at least) ``release`` ordering semantics
4708*synchronizes with* a fence B with (at least) ``acquire`` ordering
4709semantics if and only if there exist atomic operations X and Y, both
4710operating on some atomic object M, such that A is sequenced before X, X
4711modifies M (either directly or through some side effect of a sequence
4712headed by X), Y is sequenced before B, and Y observes M. This provides a
4713*happens-before* dependency between A and B. Rather than an explicit
4714``fence``, one (but not both) of the atomic operations X or Y might
4715provide a ``release`` or ``acquire`` (resp.) ordering constraint and
4716still *synchronize-with* the explicit ``fence`` and establish the
4717*happens-before* edge.
4718
4719A ``fence`` which has ``seq_cst`` ordering, in addition to having both
4720``acquire`` and ``release`` semantics specified above, participates in
4721the global program order of other ``seq_cst`` operations and/or fences.
4722
4723The optional ":ref:`singlethread <singlethread>`" argument specifies
4724that the fence only synchronizes with other fences in the same thread.
4725(This is useful for interacting with signal handlers.)
4726
4727Example:
4728""""""""
4729
4730.. code-block:: llvm
4731
4732 fence acquire ; yields {void}
4733 fence singlethread seq_cst ; yields {void}
4734
4735.. _i_cmpxchg:
4736
4737'``cmpxchg``' Instruction
4738^^^^^^^^^^^^^^^^^^^^^^^^^
4739
4740Syntax:
4741"""""""
4742
4743::
4744
4745 cmpxchg [volatile] <ty>* <pointer>, <ty> <cmp>, <ty> <new> [singlethread] <ordering> ; yields {ty}
4746
4747Overview:
4748"""""""""
4749
4750The '``cmpxchg``' instruction is used to atomically modify memory. It
4751loads a value in memory and compares it to a given value. If they are
4752equal, it stores a new value into the memory.
4753
4754Arguments:
4755""""""""""
4756
4757There are three arguments to the '``cmpxchg``' instruction: an address
4758to operate on, a value to compare to the value currently be at that
4759address, and a new value to place at that address if the compared values
4760are equal. The type of '<cmp>' must be an integer type whose bit width
4761is a power of two greater than or equal to eight and less than or equal
4762to a target-specific size limit. '<cmp>' and '<new>' must have the same
4763type, and the type of '<pointer>' must be a pointer to that type. If the
4764``cmpxchg`` is marked as ``volatile``, then the optimizer is not allowed
4765to modify the number or order of execution of this ``cmpxchg`` with
4766other :ref:`volatile operations <volatile>`.
4767
4768The :ref:`ordering <ordering>` argument specifies how this ``cmpxchg``
4769synchronizes with other atomic operations.
4770
4771The optional "``singlethread``" argument declares that the ``cmpxchg``
4772is only atomic with respect to code (usually signal handlers) running in
4773the same thread as the ``cmpxchg``. Otherwise the cmpxchg is atomic with
4774respect to all other code in the system.
4775
4776The pointer passed into cmpxchg must have alignment greater than or
4777equal to the size in memory of the operand.
4778
4779Semantics:
4780""""""""""
4781
4782The contents of memory at the location specified by the '``<pointer>``'
4783operand is read and compared to '``<cmp>``'; if the read value is the
4784equal, '``<new>``' is written. The original value at the location is
4785returned.
4786
4787A successful ``cmpxchg`` is a read-modify-write instruction for the purpose
4788of identifying release sequences. A failed ``cmpxchg`` is equivalent to an
4789atomic load with an ordering parameter determined by dropping any
4790``release`` part of the ``cmpxchg``'s ordering.
4791
4792Example:
4793""""""""
4794
4795.. code-block:: llvm
4796
4797 entry:
4798 %orig = atomic load i32* %ptr unordered ; yields {i32}
4799 br label %loop
4800
4801 loop:
4802 %cmp = phi i32 [ %orig, %entry ], [%old, %loop]
4803 %squared = mul i32 %cmp, %cmp
4804 %old = cmpxchg i32* %ptr, i32 %cmp, i32 %squared ; yields {i32}
4805 %success = icmp eq i32 %cmp, %old
4806 br i1 %success, label %done, label %loop
4807
4808 done:
4809 ...
4810
4811.. _i_atomicrmw:
4812
4813'``atomicrmw``' Instruction
4814^^^^^^^^^^^^^^^^^^^^^^^^^^^
4815
4816Syntax:
4817"""""""
4818
4819::
4820
4821 atomicrmw [volatile] <operation> <ty>* <pointer>, <ty> <value> [singlethread] <ordering> ; yields {ty}
4822
4823Overview:
4824"""""""""
4825
4826The '``atomicrmw``' instruction is used to atomically modify memory.
4827
4828Arguments:
4829""""""""""
4830
4831There are three arguments to the '``atomicrmw``' instruction: an
4832operation to apply, an address whose value to modify, an argument to the
4833operation. The operation must be one of the following keywords:
4834
4835- xchg
4836- add
4837- sub
4838- and
4839- nand
4840- or
4841- xor
4842- max
4843- min
4844- umax
4845- umin
4846
4847The type of '<value>' must be an integer type whose bit width is a power
4848of two greater than or equal to eight and less than or equal to a
4849target-specific size limit. The type of the '``<pointer>``' operand must
4850be a pointer to that type. If the ``atomicrmw`` is marked as
4851``volatile``, then the optimizer is not allowed to modify the number or
4852order of execution of this ``atomicrmw`` with other :ref:`volatile
4853operations <volatile>`.
4854
4855Semantics:
4856""""""""""
4857
4858The contents of memory at the location specified by the '``<pointer>``'
4859operand are atomically read, modified, and written back. The original
4860value at the location is returned. The modification is specified by the
4861operation argument:
4862
4863- xchg: ``*ptr = val``
4864- add: ``*ptr = *ptr + val``
4865- sub: ``*ptr = *ptr - val``
4866- and: ``*ptr = *ptr & val``
4867- nand: ``*ptr = ~(*ptr & val)``
4868- or: ``*ptr = *ptr | val``
4869- xor: ``*ptr = *ptr ^ val``
4870- max: ``*ptr = *ptr > val ? *ptr : val`` (using a signed comparison)
4871- min: ``*ptr = *ptr < val ? *ptr : val`` (using a signed comparison)
4872- umax: ``*ptr = *ptr > val ? *ptr : val`` (using an unsigned
4873 comparison)
4874- umin: ``*ptr = *ptr < val ? *ptr : val`` (using an unsigned
4875 comparison)
4876
4877Example:
4878""""""""
4879
4880.. code-block:: llvm
4881
4882 %old = atomicrmw add i32* %ptr, i32 1 acquire ; yields {i32}
4883
4884.. _i_getelementptr:
4885
4886'``getelementptr``' Instruction
4887^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4888
4889Syntax:
4890"""""""
4891
4892::
4893
4894 <result> = getelementptr <pty>* <ptrval>{, <ty> <idx>}*
4895 <result> = getelementptr inbounds <pty>* <ptrval>{, <ty> <idx>}*
4896 <result> = getelementptr <ptr vector> ptrval, <vector index type> idx
4897
4898Overview:
4899"""""""""
4900
4901The '``getelementptr``' instruction is used to get the address of a
4902subelement of an :ref:`aggregate <t_aggregate>` data structure. It performs
4903address calculation only and does not access memory.
4904
4905Arguments:
4906""""""""""
4907
4908The first argument is always a pointer or a vector of pointers, and
4909forms the basis of the calculation. The remaining arguments are indices
4910that indicate which of the elements of the aggregate object are indexed.
4911The interpretation of each index is dependent on the type being indexed
4912into. The first index always indexes the pointer value given as the
4913first argument, the second index indexes a value of the type pointed to
4914(not necessarily the value directly pointed to, since the first index
4915can be non-zero), etc. The first type indexed into must be a pointer
4916value, subsequent types can be arrays, vectors, and structs. Note that
4917subsequent types being indexed into can never be pointers, since that
4918would require loading the pointer before continuing calculation.
4919
4920The type of each index argument depends on the type it is indexing into.
4921When indexing into a (optionally packed) structure, only ``i32`` integer
4922**constants** are allowed (when using a vector of indices they must all
4923be the **same** ``i32`` integer constant). When indexing into an array,
4924pointer or vector, integers of any width are allowed, and they are not
4925required to be constant. These integers are treated as signed values
4926where relevant.
4927
4928For example, let's consider a C code fragment and how it gets compiled
4929to LLVM:
4930
4931.. code-block:: c
4932
4933 struct RT {
4934 char A;
4935 int B[10][20];
4936 char C;
4937 };
4938 struct ST {
4939 int X;
4940 double Y;
4941 struct RT Z;
4942 };
4943
4944 int *foo(struct ST *s) {
4945 return &s[1].Z.B[5][13];
4946 }
4947
4948The LLVM code generated by Clang is:
4949
4950.. code-block:: llvm
4951
4952 %struct.RT = type { i8, [10 x [20 x i32]], i8 }
4953 %struct.ST = type { i32, double, %struct.RT }
4954
4955 define i32* @foo(%struct.ST* %s) nounwind uwtable readnone optsize ssp {
4956 entry:
4957 %arrayidx = getelementptr inbounds %struct.ST* %s, i64 1, i32 2, i32 1, i64 5, i64 13
4958 ret i32* %arrayidx
4959 }
4960
4961Semantics:
4962""""""""""
4963
4964In the example above, the first index is indexing into the
4965'``%struct.ST*``' type, which is a pointer, yielding a '``%struct.ST``'
4966= '``{ i32, double, %struct.RT }``' type, a structure. The second index
4967indexes into the third element of the structure, yielding a
4968'``%struct.RT``' = '``{ i8 , [10 x [20 x i32]], i8 }``' type, another
4969structure. The third index indexes into the second element of the
4970structure, yielding a '``[10 x [20 x i32]]``' type, an array. The two
4971dimensions of the array are subscripted into, yielding an '``i32``'
4972type. The '``getelementptr``' instruction returns a pointer to this
4973element, thus computing a value of '``i32*``' type.
4974
4975Note that it is perfectly legal to index partially through a structure,
4976returning a pointer to an inner element. Because of this, the LLVM code
4977for the given testcase is equivalent to:
4978
4979.. code-block:: llvm
4980
4981 define i32* @foo(%struct.ST* %s) {
4982 %t1 = getelementptr %struct.ST* %s, i32 1 ; yields %struct.ST*:%t1
4983 %t2 = getelementptr %struct.ST* %t1, i32 0, i32 2 ; yields %struct.RT*:%t2
4984 %t3 = getelementptr %struct.RT* %t2, i32 0, i32 1 ; yields [10 x [20 x i32]]*:%t3
4985 %t4 = getelementptr [10 x [20 x i32]]* %t3, i32 0, i32 5 ; yields [20 x i32]*:%t4
4986 %t5 = getelementptr [20 x i32]* %t4, i32 0, i32 13 ; yields i32*:%t5
4987 ret i32* %t5
4988 }
4989
4990If the ``inbounds`` keyword is present, the result value of the
4991``getelementptr`` is a :ref:`poison value <poisonvalues>` if the base
4992pointer is not an *in bounds* address of an allocated object, or if any
4993of the addresses that would be formed by successive addition of the
4994offsets implied by the indices to the base address with infinitely
4995precise signed arithmetic are not an *in bounds* address of that
4996allocated object. The *in bounds* addresses for an allocated object are
4997all the addresses that point into the object, plus the address one byte
4998past the end. In cases where the base is a vector of pointers the
4999``inbounds`` keyword applies to each of the computations element-wise.
5000
5001If the ``inbounds`` keyword is not present, the offsets are added to the
5002base address with silently-wrapping two's complement arithmetic. If the
5003offsets have a different width from the pointer, they are sign-extended
5004or truncated to the width of the pointer. The result value of the
5005``getelementptr`` may be outside the object pointed to by the base
5006pointer. The result value may not necessarily be used to access memory
5007though, even if it happens to point into allocated storage. See the
5008:ref:`Pointer Aliasing Rules <pointeraliasing>` section for more
5009information.
5010
5011The getelementptr instruction is often confusing. For some more insight
5012into how it works, see :doc:`the getelementptr FAQ <GetElementPtr>`.
5013
5014Example:
5015""""""""
5016
5017.. code-block:: llvm
5018
5019 ; yields [12 x i8]*:aptr
5020 %aptr = getelementptr {i32, [12 x i8]}* %saptr, i64 0, i32 1
5021 ; yields i8*:vptr
5022 %vptr = getelementptr {i32, <2 x i8>}* %svptr, i64 0, i32 1, i32 1
5023 ; yields i8*:eptr
5024 %eptr = getelementptr [12 x i8]* %aptr, i64 0, i32 1
5025 ; yields i32*:iptr
5026 %iptr = getelementptr [10 x i32]* @arr, i16 0, i16 0
5027
5028In cases where the pointer argument is a vector of pointers, each index
5029must be a vector with the same number of elements. For example:
5030
5031.. code-block:: llvm
5032
5033 %A = getelementptr <4 x i8*> %ptrs, <4 x i64> %offsets,
5034
5035Conversion Operations
5036---------------------
5037
5038The instructions in this category are the conversion instructions
5039(casting) which all take a single operand and a type. They perform
5040various bit conversions on the operand.
5041
5042'``trunc .. to``' Instruction
5043^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5044
5045Syntax:
5046"""""""
5047
5048::
5049
5050 <result> = trunc <ty> <value> to <ty2> ; yields ty2
5051
5052Overview:
5053"""""""""
5054
5055The '``trunc``' instruction truncates its operand to the type ``ty2``.
5056
5057Arguments:
5058""""""""""
5059
5060The '``trunc``' instruction takes a value to trunc, and a type to trunc
5061it to. Both types must be of :ref:`integer <t_integer>` types, or vectors
5062of the same number of integers. The bit size of the ``value`` must be
5063larger than the bit size of the destination type, ``ty2``. Equal sized
5064types are not allowed.
5065
5066Semantics:
5067""""""""""
5068
5069The '``trunc``' instruction truncates the high order bits in ``value``
5070and converts the remaining bits to ``ty2``. Since the source size must
5071be larger than the destination size, ``trunc`` cannot be a *no-op cast*.
5072It will always truncate bits.
5073
5074Example:
5075""""""""
5076
5077.. code-block:: llvm
5078
5079 %X = trunc i32 257 to i8 ; yields i8:1
5080 %Y = trunc i32 123 to i1 ; yields i1:true
5081 %Z = trunc i32 122 to i1 ; yields i1:false
5082 %W = trunc <2 x i16> <i16 8, i16 7> to <2 x i8> ; yields <i8 8, i8 7>
5083
5084'``zext .. to``' Instruction
5085^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5086
5087Syntax:
5088"""""""
5089
5090::
5091
5092 <result> = zext <ty> <value> to <ty2> ; yields ty2
5093
5094Overview:
5095"""""""""
5096
5097The '``zext``' instruction zero extends its operand to type ``ty2``.
5098
5099Arguments:
5100""""""""""
5101
5102The '``zext``' instruction takes a value to cast, and a type to cast it
5103to. Both types must be of :ref:`integer <t_integer>` types, or vectors of
5104the same number of integers. The bit size of the ``value`` must be
5105smaller than the bit size of the destination type, ``ty2``.
5106
5107Semantics:
5108""""""""""
5109
5110The ``zext`` fills the high order bits of the ``value`` with zero bits
5111until it reaches the size of the destination type, ``ty2``.
5112
5113When zero extending from i1, the result will always be either 0 or 1.
5114
5115Example:
5116""""""""
5117
5118.. code-block:: llvm
5119
5120 %X = zext i32 257 to i64 ; yields i64:257
5121 %Y = zext i1 true to i32 ; yields i32:1
5122 %Z = zext <2 x i16> <i16 8, i16 7> to <2 x i32> ; yields <i32 8, i32 7>
5123
5124'``sext .. to``' Instruction
5125^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5126
5127Syntax:
5128"""""""
5129
5130::
5131
5132 <result> = sext <ty> <value> to <ty2> ; yields ty2
5133
5134Overview:
5135"""""""""
5136
5137The '``sext``' sign extends ``value`` to the type ``ty2``.
5138
5139Arguments:
5140""""""""""
5141
5142The '``sext``' instruction takes a value to cast, and a type to cast it
5143to. Both types must be of :ref:`integer <t_integer>` types, or vectors of
5144the same number of integers. The bit size of the ``value`` must be
5145smaller than the bit size of the destination type, ``ty2``.
5146
5147Semantics:
5148""""""""""
5149
5150The '``sext``' instruction performs a sign extension by copying the sign
5151bit (highest order bit) of the ``value`` until it reaches the bit size
5152of the type ``ty2``.
5153
5154When sign extending from i1, the extension always results in -1 or 0.
5155
5156Example:
5157""""""""
5158
5159.. code-block:: llvm
5160
5161 %X = sext i8 -1 to i16 ; yields i16 :65535
5162 %Y = sext i1 true to i32 ; yields i32:-1
5163 %Z = sext <2 x i16> <i16 8, i16 7> to <2 x i32> ; yields <i32 8, i32 7>
5164
5165'``fptrunc .. to``' Instruction
5166^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5167
5168Syntax:
5169"""""""
5170
5171::
5172
5173 <result> = fptrunc <ty> <value> to <ty2> ; yields ty2
5174
5175Overview:
5176"""""""""
5177
5178The '``fptrunc``' instruction truncates ``value`` to type ``ty2``.
5179
5180Arguments:
5181""""""""""
5182
5183The '``fptrunc``' instruction takes a :ref:`floating point <t_floating>`
5184value to cast and a :ref:`floating point <t_floating>` type to cast it to.
5185The size of ``value`` must be larger than the size of ``ty2``. This
5186implies that ``fptrunc`` cannot be used to make a *no-op cast*.
5187
5188Semantics:
5189""""""""""
5190
5191The '``fptrunc``' instruction truncates a ``value`` from a larger
5192:ref:`floating point <t_floating>` type to a smaller :ref:`floating
5193point <t_floating>` type. If the value cannot fit within the
5194destination type, ``ty2``, then the results are undefined.
5195
5196Example:
5197""""""""
5198
5199.. code-block:: llvm
5200
5201 %X = fptrunc double 123.0 to float ; yields float:123.0
5202 %Y = fptrunc double 1.0E+300 to float ; yields undefined
5203
5204'``fpext .. to``' Instruction
5205^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5206
5207Syntax:
5208"""""""
5209
5210::
5211
5212 <result> = fpext <ty> <value> to <ty2> ; yields ty2
5213
5214Overview:
5215"""""""""
5216
5217The '``fpext``' extends a floating point ``value`` to a larger floating
5218point value.
5219
5220Arguments:
5221""""""""""
5222
5223The '``fpext``' instruction takes a :ref:`floating point <t_floating>`
5224``value`` to cast, and a :ref:`floating point <t_floating>` type to cast it
5225to. The source type must be smaller than the destination type.
5226
5227Semantics:
5228""""""""""
5229
5230The '``fpext``' instruction extends the ``value`` from a smaller
5231:ref:`floating point <t_floating>` type to a larger :ref:`floating
5232point <t_floating>` type. The ``fpext`` cannot be used to make a
5233*no-op cast* because it always changes bits. Use ``bitcast`` to make a
5234*no-op cast* for a floating point cast.
5235
5236Example:
5237""""""""
5238
5239.. code-block:: llvm
5240
5241 %X = fpext float 3.125 to double ; yields double:3.125000e+00
5242 %Y = fpext double %X to fp128 ; yields fp128:0xL00000000000000004000900000000000
5243
5244'``fptoui .. to``' Instruction
5245^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5246
5247Syntax:
5248"""""""
5249
5250::
5251
5252 <result> = fptoui <ty> <value> to <ty2> ; yields ty2
5253
5254Overview:
5255"""""""""
5256
5257The '``fptoui``' converts a floating point ``value`` to its unsigned
5258integer equivalent of type ``ty2``.
5259
5260Arguments:
5261""""""""""
5262
5263The '``fptoui``' instruction takes a value to cast, which must be a
5264scalar or vector :ref:`floating point <t_floating>` value, and a type to
5265cast it to ``ty2``, which must be an :ref:`integer <t_integer>` type. If
5266``ty`` is a vector floating point type, ``ty2`` must be a vector integer
5267type with the same number of elements as ``ty``
5268
5269Semantics:
5270""""""""""
5271
5272The '``fptoui``' instruction converts its :ref:`floating
5273point <t_floating>` operand into the nearest (rounding towards zero)
5274unsigned integer value. If the value cannot fit in ``ty2``, the results
5275are undefined.
5276
5277Example:
5278""""""""
5279
5280.. code-block:: llvm
5281
5282 %X = fptoui double 123.0 to i32 ; yields i32:123
5283 %Y = fptoui float 1.0E+300 to i1 ; yields undefined:1
5284 %Z = fptoui float 1.04E+17 to i8 ; yields undefined:1
5285
5286'``fptosi .. to``' Instruction
5287^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5288
5289Syntax:
5290"""""""
5291
5292::
5293
5294 <result> = fptosi <ty> <value> to <ty2> ; yields ty2
5295
5296Overview:
5297"""""""""
5298
5299The '``fptosi``' instruction converts :ref:`floating point <t_floating>`
5300``value`` to type ``ty2``.
5301
5302Arguments:
5303""""""""""
5304
5305The '``fptosi``' instruction takes a value to cast, which must be a
5306scalar or vector :ref:`floating point <t_floating>` value, and a type to
5307cast it to ``ty2``, which must be an :ref:`integer <t_integer>` type. If
5308``ty`` is a vector floating point type, ``ty2`` must be a vector integer
5309type with the same number of elements as ``ty``
5310
5311Semantics:
5312""""""""""
5313
5314The '``fptosi``' instruction converts its :ref:`floating
5315point <t_floating>` operand into the nearest (rounding towards zero)
5316signed integer value. If the value cannot fit in ``ty2``, the results
5317are undefined.
5318
5319Example:
5320""""""""
5321
5322.. code-block:: llvm
5323
5324 %X = fptosi double -123.0 to i32 ; yields i32:-123
5325 %Y = fptosi float 1.0E-247 to i1 ; yields undefined:1
5326 %Z = fptosi float 1.04E+17 to i8 ; yields undefined:1
5327
5328'``uitofp .. to``' Instruction
5329^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5330
5331Syntax:
5332"""""""
5333
5334::
5335
5336 <result> = uitofp <ty> <value> to <ty2> ; yields ty2
5337
5338Overview:
5339"""""""""
5340
5341The '``uitofp``' instruction regards ``value`` as an unsigned integer
5342and converts that value to the ``ty2`` type.
5343
5344Arguments:
5345""""""""""
5346
5347The '``uitofp``' instruction takes a value to cast, which must be a
5348scalar or vector :ref:`integer <t_integer>` value, and a type to cast it to
5349``ty2``, which must be an :ref:`floating point <t_floating>` type. If
5350``ty`` is a vector integer type, ``ty2`` must be a vector floating point
5351type with the same number of elements as ``ty``
5352
5353Semantics:
5354""""""""""
5355
5356The '``uitofp``' instruction interprets its operand as an unsigned
5357integer quantity and converts it to the corresponding floating point
5358value. If the value cannot fit in the floating point value, the results
5359are undefined.
5360
5361Example:
5362""""""""
5363
5364.. code-block:: llvm
5365
5366 %X = uitofp i32 257 to float ; yields float:257.0
5367 %Y = uitofp i8 -1 to double ; yields double:255.0
5368
5369'``sitofp .. to``' Instruction
5370^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5371
5372Syntax:
5373"""""""
5374
5375::
5376
5377 <result> = sitofp <ty> <value> to <ty2> ; yields ty2
5378
5379Overview:
5380"""""""""
5381
5382The '``sitofp``' instruction regards ``value`` as a signed integer and
5383converts that value to the ``ty2`` type.
5384
5385Arguments:
5386""""""""""
5387
5388The '``sitofp``' instruction takes a value to cast, which must be a
5389scalar or vector :ref:`integer <t_integer>` value, and a type to cast it to
5390``ty2``, which must be an :ref:`floating point <t_floating>` type. If
5391``ty`` is a vector integer type, ``ty2`` must be a vector floating point
5392type with the same number of elements as ``ty``
5393
5394Semantics:
5395""""""""""
5396
5397The '``sitofp``' instruction interprets its operand as a signed integer
5398quantity and converts it to the corresponding floating point value. If
5399the value cannot fit in the floating point value, the results are
5400undefined.
5401
5402Example:
5403""""""""
5404
5405.. code-block:: llvm
5406
5407 %X = sitofp i32 257 to float ; yields float:257.0
5408 %Y = sitofp i8 -1 to double ; yields double:-1.0
5409
5410.. _i_ptrtoint:
5411
5412'``ptrtoint .. to``' Instruction
5413^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5414
5415Syntax:
5416"""""""
5417
5418::
5419
5420 <result> = ptrtoint <ty> <value> to <ty2> ; yields ty2
5421
5422Overview:
5423"""""""""
5424
5425The '``ptrtoint``' instruction converts the pointer or a vector of
5426pointers ``value`` to the integer (or vector of integers) type ``ty2``.
5427
5428Arguments:
5429""""""""""
5430
5431The '``ptrtoint``' instruction takes a ``value`` to cast, which must be
5432a a value of type :ref:`pointer <t_pointer>` or a vector of pointers, and a
5433type to cast it to ``ty2``, which must be an :ref:`integer <t_integer>` or
5434a vector of integers type.
5435
5436Semantics:
5437""""""""""
5438
5439The '``ptrtoint``' instruction converts ``value`` to integer type
5440``ty2`` by interpreting the pointer value as an integer and either
5441truncating or zero extending that value to the size of the integer type.
5442If ``value`` is smaller than ``ty2`` then a zero extension is done. If
5443``value`` is larger than ``ty2`` then a truncation is done. If they are
5444the same size, then nothing is done (*no-op cast*) other than a type
5445change.
5446
5447Example:
5448""""""""
5449
5450.. code-block:: llvm
5451
5452 %X = ptrtoint i32* %P to i8 ; yields truncation on 32-bit architecture
5453 %Y = ptrtoint i32* %P to i64 ; yields zero extension on 32-bit architecture
5454 %Z = ptrtoint <4 x i32*> %P to <4 x i64>; yields vector zero extension for a vector of addresses on 32-bit architecture
5455
5456.. _i_inttoptr:
5457
5458'``inttoptr .. to``' Instruction
5459^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5460
5461Syntax:
5462"""""""
5463
5464::
5465
5466 <result> = inttoptr <ty> <value> to <ty2> ; yields ty2
5467
5468Overview:
5469"""""""""
5470
5471The '``inttoptr``' instruction converts an integer ``value`` to a
5472pointer type, ``ty2``.
5473
5474Arguments:
5475""""""""""
5476
5477The '``inttoptr``' instruction takes an :ref:`integer <t_integer>` value to
5478cast, and a type to cast it to, which must be a :ref:`pointer <t_pointer>`
5479type.
5480
5481Semantics:
5482""""""""""
5483
5484The '``inttoptr``' instruction converts ``value`` to type ``ty2`` by
5485applying either a zero extension or a truncation depending on the size
5486of the integer ``value``. If ``value`` is larger than the size of a
5487pointer then a truncation is done. If ``value`` is smaller than the size
5488of a pointer then a zero extension is done. If they are the same size,
5489nothing is done (*no-op cast*).
5490
5491Example:
5492""""""""
5493
5494.. code-block:: llvm
5495
5496 %X = inttoptr i32 255 to i32* ; yields zero extension on 64-bit architecture
5497 %Y = inttoptr i32 255 to i32* ; yields no-op on 32-bit architecture
5498 %Z = inttoptr i64 0 to i32* ; yields truncation on 32-bit architecture
5499 %Z = inttoptr <4 x i32> %G to <4 x i8*>; yields truncation of vector G to four pointers
5500
5501.. _i_bitcast:
5502
5503'``bitcast .. to``' Instruction
5504^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5505
5506Syntax:
5507"""""""
5508
5509::
5510
5511 <result> = bitcast <ty> <value> to <ty2> ; yields ty2
5512
5513Overview:
5514"""""""""
5515
5516The '``bitcast``' instruction converts ``value`` to type ``ty2`` without
5517changing any bits.
5518
5519Arguments:
5520""""""""""
5521
5522The '``bitcast``' instruction takes a value to cast, which must be a
5523non-aggregate first class value, and a type to cast it to, which must
5524also be a non-aggregate :ref:`first class <t_firstclass>` type. The bit
5525sizes of ``value`` and the destination type, ``ty2``, must be identical.
5526If the source type is a pointer, the destination type must also be a
5527pointer. This instruction supports bitwise conversion of vectors to
5528integers and to vectors of other types (as long as they have the same
5529size).
5530
5531Semantics:
5532""""""""""
5533
5534The '``bitcast``' instruction converts ``value`` to type ``ty2``. It is
5535always a *no-op cast* because no bits change with this conversion. The
5536conversion is done as if the ``value`` had been stored to memory and
5537read back as type ``ty2``. Pointer (or vector of pointers) types may
5538only be converted to other pointer (or vector of pointers) types with
5539this instruction. To convert pointers to other types, use the
5540:ref:`inttoptr <i_inttoptr>` or :ref:`ptrtoint <i_ptrtoint>` instructions
5541first.
5542
5543Example:
5544""""""""
5545
5546.. code-block:: llvm
5547
5548 %X = bitcast i8 255 to i8 ; yields i8 :-1
5549 %Y = bitcast i32* %x to sint* ; yields sint*:%x
5550 %Z = bitcast <2 x int> %V to i64; ; yields i64: %V
5551 %Z = bitcast <2 x i32*> %V to <2 x i64*> ; yields <2 x i64*>
5552
5553.. _otherops:
5554
5555Other Operations
5556----------------
5557
5558The instructions in this category are the "miscellaneous" instructions,
5559which defy better classification.
5560
5561.. _i_icmp:
5562
5563'``icmp``' Instruction
5564^^^^^^^^^^^^^^^^^^^^^^
5565
5566Syntax:
5567"""""""
5568
5569::
5570
5571 <result> = icmp <cond> <ty> <op1>, <op2> ; yields {i1} or {<N x i1>}:result
5572
5573Overview:
5574"""""""""
5575
5576The '``icmp``' instruction returns a boolean value or a vector of
5577boolean values based on comparison of its two integer, integer vector,
5578pointer, or pointer vector operands.
5579
5580Arguments:
5581""""""""""
5582
5583The '``icmp``' instruction takes three operands. The first operand is
5584the condition code indicating the kind of comparison to perform. It is
5585not a value, just a keyword. The possible condition code are:
5586
5587#. ``eq``: equal
5588#. ``ne``: not equal
5589#. ``ugt``: unsigned greater than
5590#. ``uge``: unsigned greater or equal
5591#. ``ult``: unsigned less than
5592#. ``ule``: unsigned less or equal
5593#. ``sgt``: signed greater than
5594#. ``sge``: signed greater or equal
5595#. ``slt``: signed less than
5596#. ``sle``: signed less or equal
5597
5598The remaining two arguments must be :ref:`integer <t_integer>` or
5599:ref:`pointer <t_pointer>` or integer :ref:`vector <t_vector>` typed. They
5600must also be identical types.
5601
5602Semantics:
5603""""""""""
5604
5605The '``icmp``' compares ``op1`` and ``op2`` according to the condition
5606code given as ``cond``. The comparison performed always yields either an
5607:ref:`i1 <t_integer>` or vector of ``i1`` result, as follows:
5608
5609#. ``eq``: yields ``true`` if the operands are equal, ``false``
5610 otherwise. No sign interpretation is necessary or performed.
5611#. ``ne``: yields ``true`` if the operands are unequal, ``false``
5612 otherwise. No sign interpretation is necessary or performed.
5613#. ``ugt``: interprets the operands as unsigned values and yields
5614 ``true`` if ``op1`` is greater than ``op2``.
5615#. ``uge``: interprets the operands as unsigned values and yields
5616 ``true`` if ``op1`` is greater than or equal to ``op2``.
5617#. ``ult``: interprets the operands as unsigned values and yields
5618 ``true`` if ``op1`` is less than ``op2``.
5619#. ``ule``: interprets the operands as unsigned values and yields
5620 ``true`` if ``op1`` is less than or equal to ``op2``.
5621#. ``sgt``: interprets the operands as signed values and yields ``true``
5622 if ``op1`` is greater than ``op2``.
5623#. ``sge``: interprets the operands as signed values and yields ``true``
5624 if ``op1`` is greater than or equal to ``op2``.
5625#. ``slt``: interprets the operands as signed values and yields ``true``
5626 if ``op1`` is less than ``op2``.
5627#. ``sle``: interprets the operands as signed values and yields ``true``
5628 if ``op1`` is less than or equal to ``op2``.
5629
5630If the operands are :ref:`pointer <t_pointer>` typed, the pointer values
5631are compared as if they were integers.
5632
5633If the operands are integer vectors, then they are compared element by
5634element. The result is an ``i1`` vector with the same number of elements
5635as the values being compared. Otherwise, the result is an ``i1``.
5636
5637Example:
5638""""""""
5639
5640.. code-block:: llvm
5641
5642 <result> = icmp eq i32 4, 5 ; yields: result=false
5643 <result> = icmp ne float* %X, %X ; yields: result=false
5644 <result> = icmp ult i16 4, 5 ; yields: result=true
5645 <result> = icmp sgt i16 4, 5 ; yields: result=false
5646 <result> = icmp ule i16 -4, 5 ; yields: result=false
5647 <result> = icmp sge i16 4, 5 ; yields: result=false
5648
5649Note that the code generator does not yet support vector types with the
5650``icmp`` instruction.
5651
5652.. _i_fcmp:
5653
5654'``fcmp``' Instruction
5655^^^^^^^^^^^^^^^^^^^^^^
5656
5657Syntax:
5658"""""""
5659
5660::
5661
5662 <result> = fcmp <cond> <ty> <op1>, <op2> ; yields {i1} or {<N x i1>}:result
5663
5664Overview:
5665"""""""""
5666
5667The '``fcmp``' instruction returns a boolean value or vector of boolean
5668values based on comparison of its operands.
5669
5670If the operands are floating point scalars, then the result type is a
5671boolean (:ref:`i1 <t_integer>`).
5672
5673If the operands are floating point vectors, then the result type is a
5674vector of boolean with the same number of elements as the operands being
5675compared.
5676
5677Arguments:
5678""""""""""
5679
5680The '``fcmp``' instruction takes three operands. The first operand is
5681the condition code indicating the kind of comparison to perform. It is
5682not a value, just a keyword. The possible condition code are:
5683
5684#. ``false``: no comparison, always returns false
5685#. ``oeq``: ordered and equal
5686#. ``ogt``: ordered and greater than
5687#. ``oge``: ordered and greater than or equal
5688#. ``olt``: ordered and less than
5689#. ``ole``: ordered and less than or equal
5690#. ``one``: ordered and not equal
5691#. ``ord``: ordered (no nans)
5692#. ``ueq``: unordered or equal
5693#. ``ugt``: unordered or greater than
5694#. ``uge``: unordered or greater than or equal
5695#. ``ult``: unordered or less than
5696#. ``ule``: unordered or less than or equal
5697#. ``une``: unordered or not equal
5698#. ``uno``: unordered (either nans)
5699#. ``true``: no comparison, always returns true
5700
5701*Ordered* means that neither operand is a QNAN while *unordered* means
5702that either operand may be a QNAN.
5703
5704Each of ``val1`` and ``val2`` arguments must be either a :ref:`floating
5705point <t_floating>` type or a :ref:`vector <t_vector>` of floating point
5706type. They must have identical types.
5707
5708Semantics:
5709""""""""""
5710
5711The '``fcmp``' instruction compares ``op1`` and ``op2`` according to the
5712condition code given as ``cond``. If the operands are vectors, then the
5713vectors are compared element by element. Each comparison performed
5714always yields an :ref:`i1 <t_integer>` result, as follows:
5715
5716#. ``false``: always yields ``false``, regardless of operands.
5717#. ``oeq``: yields ``true`` if both operands are not a QNAN and ``op1``
5718 is equal to ``op2``.
5719#. ``ogt``: yields ``true`` if both operands are not a QNAN and ``op1``
5720 is greater than ``op2``.
5721#. ``oge``: yields ``true`` if both operands are not a QNAN and ``op1``
5722 is greater than or equal to ``op2``.
5723#. ``olt``: yields ``true`` if both operands are not a QNAN and ``op1``
5724 is less than ``op2``.
5725#. ``ole``: yields ``true`` if both operands are not a QNAN and ``op1``
5726 is less than or equal to ``op2``.
5727#. ``one``: yields ``true`` if both operands are not a QNAN and ``op1``
5728 is not equal to ``op2``.
5729#. ``ord``: yields ``true`` if both operands are not a QNAN.
5730#. ``ueq``: yields ``true`` if either operand is a QNAN or ``op1`` is
5731 equal to ``op2``.
5732#. ``ugt``: yields ``true`` if either operand is a QNAN or ``op1`` is
5733 greater than ``op2``.
5734#. ``uge``: yields ``true`` if either operand is a QNAN or ``op1`` is
5735 greater than or equal to ``op2``.
5736#. ``ult``: yields ``true`` if either operand is a QNAN or ``op1`` is
5737 less than ``op2``.
5738#. ``ule``: yields ``true`` if either operand is a QNAN or ``op1`` is
5739 less than or equal to ``op2``.
5740#. ``une``: yields ``true`` if either operand is a QNAN or ``op1`` is
5741 not equal to ``op2``.
5742#. ``uno``: yields ``true`` if either operand is a QNAN.
5743#. ``true``: always yields ``true``, regardless of operands.
5744
5745Example:
5746""""""""
5747
5748.. code-block:: llvm
5749
5750 <result> = fcmp oeq float 4.0, 5.0 ; yields: result=false
5751 <result> = fcmp one float 4.0, 5.0 ; yields: result=true
5752 <result> = fcmp olt float 4.0, 5.0 ; yields: result=true
5753 <result> = fcmp ueq double 1.0, 2.0 ; yields: result=false
5754
5755Note that the code generator does not yet support vector types with the
5756``fcmp`` instruction.
5757
5758.. _i_phi:
5759
5760'``phi``' Instruction
5761^^^^^^^^^^^^^^^^^^^^^
5762
5763Syntax:
5764"""""""
5765
5766::
5767
5768 <result> = phi <ty> [ <val0>, <label0>], ...
5769
5770Overview:
5771"""""""""
5772
5773The '``phi``' instruction is used to implement the φ node in the SSA
5774graph representing the function.
5775
5776Arguments:
5777""""""""""
5778
5779The type of the incoming values is specified with the first type field.
5780After this, the '``phi``' instruction takes a list of pairs as
5781arguments, with one pair for each predecessor basic block of the current
5782block. Only values of :ref:`first class <t_firstclass>` type may be used as
5783the value arguments to the PHI node. Only labels may be used as the
5784label arguments.
5785
5786There must be no non-phi instructions between the start of a basic block
5787and the PHI instructions: i.e. PHI instructions must be first in a basic
5788block.
5789
5790For the purposes of the SSA form, the use of each incoming value is
5791deemed to occur on the edge from the corresponding predecessor block to
5792the current block (but after any definition of an '``invoke``'
5793instruction's return value on the same edge).
5794
5795Semantics:
5796""""""""""
5797
5798At runtime, the '``phi``' instruction logically takes on the value
5799specified by the pair corresponding to the predecessor basic block that
5800executed just prior to the current block.
5801
5802Example:
5803""""""""
5804
5805.. code-block:: llvm
5806
5807 Loop: ; Infinite loop that counts from 0 on up...
5808 %indvar = phi i32 [ 0, %LoopHeader ], [ %nextindvar, %Loop ]
5809 %nextindvar = add i32 %indvar, 1
5810 br label %Loop
5811
5812.. _i_select:
5813
5814'``select``' Instruction
5815^^^^^^^^^^^^^^^^^^^^^^^^
5816
5817Syntax:
5818"""""""
5819
5820::
5821
5822 <result> = select selty <cond>, <ty> <val1>, <ty> <val2> ; yields ty
5823
5824 selty is either i1 or {<N x i1>}
5825
5826Overview:
5827"""""""""
5828
5829The '``select``' instruction is used to choose one value based on a
5830condition, without branching.
5831
5832Arguments:
5833""""""""""
5834
5835The '``select``' instruction requires an 'i1' value or a vector of 'i1'
5836values indicating the condition, and two values of the same :ref:`first
5837class <t_firstclass>` type. If the val1/val2 are vectors and the
5838condition is a scalar, then entire vectors are selected, not individual
5839elements.
5840
5841Semantics:
5842""""""""""
5843
5844If the condition is an i1 and it evaluates to 1, the instruction returns
5845the first value argument; otherwise, it returns the second value
5846argument.
5847
5848If the condition is a vector of i1, then the value arguments must be
5849vectors of the same size, and the selection is done element by element.
5850
5851Example:
5852""""""""
5853
5854.. code-block:: llvm
5855
5856 %X = select i1 true, i8 17, i8 42 ; yields i8:17
5857
5858.. _i_call:
5859
5860'``call``' Instruction
5861^^^^^^^^^^^^^^^^^^^^^^
5862
5863Syntax:
5864"""""""
5865
5866::
5867
5868 <result> = [tail] call [cconv] [ret attrs] <ty> [<fnty>*] <fnptrval>(<function args>) [fn attrs]
5869
5870Overview:
5871"""""""""
5872
5873The '``call``' instruction represents a simple function call.
5874
5875Arguments:
5876""""""""""
5877
5878This instruction requires several arguments:
5879
5880#. The optional "tail" marker indicates that the callee function does
5881 not access any allocas or varargs in the caller. Note that calls may
5882 be marked "tail" even if they do not occur before a
5883 :ref:`ret <i_ret>` instruction. If the "tail" marker is present, the
5884 function call is eligible for tail call optimization, but `might not
5885 in fact be optimized into a jump <CodeGenerator.html#tailcallopt>`_.
5886 The code generator may optimize calls marked "tail" with either 1)
5887 automatic `sibling call
5888 optimization <CodeGenerator.html#sibcallopt>`_ when the caller and
5889 callee have matching signatures, or 2) forced tail call optimization
5890 when the following extra requirements are met:
5891
5892 - Caller and callee both have the calling convention ``fastcc``.
5893 - The call is in tail position (ret immediately follows call and ret
5894 uses value of call or is void).
5895 - Option ``-tailcallopt`` is enabled, or
5896 ``llvm::GuaranteedTailCallOpt`` is ``true``.
5897 - `Platform specific constraints are
5898 met. <CodeGenerator.html#tailcallopt>`_
5899
5900#. The optional "cconv" marker indicates which :ref:`calling
5901 convention <callingconv>` the call should use. If none is
5902 specified, the call defaults to using C calling conventions. The
5903 calling convention of the call must match the calling convention of
5904 the target function, or else the behavior is undefined.
5905#. The optional :ref:`Parameter Attributes <paramattrs>` list for return
5906 values. Only '``zeroext``', '``signext``', and '``inreg``' attributes
5907 are valid here.
5908#. '``ty``': the type of the call instruction itself which is also the
5909 type of the return value. Functions that return no value are marked
5910 ``void``.
5911#. '``fnty``': shall be the signature of the pointer to function value
5912 being invoked. The argument types must match the types implied by
5913 this signature. This type can be omitted if the function is not
5914 varargs and if the function type does not return a pointer to a
5915 function.
5916#. '``fnptrval``': An LLVM value containing a pointer to a function to
5917 be invoked. In most cases, this is a direct function invocation, but
5918 indirect ``call``'s are just as possible, calling an arbitrary pointer
5919 to function value.
5920#. '``function args``': argument list whose types match the function
5921 signature argument types and parameter attributes. All arguments must
5922 be of :ref:`first class <t_firstclass>` type. If the function signature
5923 indicates the function accepts a variable number of arguments, the
5924 extra arguments can be specified.
5925#. The optional :ref:`function attributes <fnattrs>` list. Only
5926 '``noreturn``', '``nounwind``', '``readonly``' and '``readnone``'
5927 attributes are valid here.
5928
5929Semantics:
5930""""""""""
5931
5932The '``call``' instruction is used to cause control flow to transfer to
5933a specified function, with its incoming arguments bound to the specified
5934values. Upon a '``ret``' instruction in the called function, control
5935flow continues with the instruction after the function call, and the
5936return value of the function is bound to the result argument.
5937
5938Example:
5939""""""""
5940
5941.. code-block:: llvm
5942
5943 %retval = call i32 @test(i32 %argc)
5944 call i32 (i8*, ...)* @printf(i8* %msg, i32 12, i8 42) ; yields i32
5945 %X = tail call i32 @foo() ; yields i32
5946 %Y = tail call fastcc i32 @foo() ; yields i32
5947 call void %foo(i8 97 signext)
5948
5949 %struct.A = type { i32, i8 }
5950 %r = call %struct.A @foo() ; yields { 32, i8 }
5951 %gr = extractvalue %struct.A %r, 0 ; yields i32
5952 %gr1 = extractvalue %struct.A %r, 1 ; yields i8
5953 %Z = call void @foo() noreturn ; indicates that %foo never returns normally
5954 %ZZ = call zeroext i32 @bar() ; Return value is %zero extended
5955
5956llvm treats calls to some functions with names and arguments that match
5957the standard C99 library as being the C99 library functions, and may
5958perform optimizations or generate code for them under that assumption.
5959This is something we'd like to change in the future to provide better
5960support for freestanding environments and non-C-based languages.
5961
5962.. _i_va_arg:
5963
5964'``va_arg``' Instruction
5965^^^^^^^^^^^^^^^^^^^^^^^^
5966
5967Syntax:
5968"""""""
5969
5970::
5971
5972 <resultval> = va_arg <va_list*> <arglist>, <argty>
5973
5974Overview:
5975"""""""""
5976
5977The '``va_arg``' instruction is used to access arguments passed through
5978the "variable argument" area of a function call. It is used to implement
5979the ``va_arg`` macro in C.
5980
5981Arguments:
5982""""""""""
5983
5984This instruction takes a ``va_list*`` value and the type of the
5985argument. It returns a value of the specified argument type and
5986increments the ``va_list`` to point to the next argument. The actual
5987type of ``va_list`` is target specific.
5988
5989Semantics:
5990""""""""""
5991
5992The '``va_arg``' instruction loads an argument of the specified type
5993from the specified ``va_list`` and causes the ``va_list`` to point to
5994the next argument. For more information, see the variable argument
5995handling :ref:`Intrinsic Functions <int_varargs>`.
5996
5997It is legal for this instruction to be called in a function which does
5998not take a variable number of arguments, for example, the ``vfprintf``
5999function.
6000
6001``va_arg`` is an LLVM instruction instead of an :ref:`intrinsic
6002function <intrinsics>` because it takes a type as an argument.
6003
6004Example:
6005""""""""
6006
6007See the :ref:`variable argument processing <int_varargs>` section.
6008
6009Note that the code generator does not yet fully support va\_arg on many
6010targets. Also, it does not currently support va\_arg with aggregate
6011types on any target.
6012
6013.. _i_landingpad:
6014
6015'``landingpad``' Instruction
6016^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6017
6018Syntax:
6019"""""""
6020
6021::
6022
6023 <resultval> = landingpad <resultty> personality <type> <pers_fn> <clause>+
6024 <resultval> = landingpad <resultty> personality <type> <pers_fn> cleanup <clause>*
6025
6026 <clause> := catch <type> <value>
6027 <clause> := filter <array constant type> <array constant>
6028
6029Overview:
6030"""""""""
6031
6032The '``landingpad``' instruction is used by `LLVM's exception handling
6033system <ExceptionHandling.html#overview>`_ to specify that a basic block
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00006034is a landing pad --- one where the exception lands, and corresponds to the
Sean Silvaf722b002012-12-07 10:36:55 +00006035code found in the ``catch`` portion of a ``try``/``catch`` sequence. It
6036defines values supplied by the personality function (``pers_fn``) upon
6037re-entry to the function. The ``resultval`` has the type ``resultty``.
6038
6039Arguments:
6040""""""""""
6041
6042This instruction takes a ``pers_fn`` value. This is the personality
6043function associated with the unwinding mechanism. The optional
6044``cleanup`` flag indicates that the landing pad block is a cleanup.
6045
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00006046A ``clause`` begins with the clause type --- ``catch`` or ``filter`` --- and
Sean Silvaf722b002012-12-07 10:36:55 +00006047contains the global variable representing the "type" that may be caught
6048or filtered respectively. Unlike the ``catch`` clause, the ``filter``
6049clause takes an array constant as its argument. Use
6050"``[0 x i8**] undef``" for a filter which cannot throw. The
6051'``landingpad``' instruction must contain *at least* one ``clause`` or
6052the ``cleanup`` flag.
6053
6054Semantics:
6055""""""""""
6056
6057The '``landingpad``' instruction defines the values which are set by the
6058personality function (``pers_fn``) upon re-entry to the function, and
6059therefore the "result type" of the ``landingpad`` instruction. As with
6060calling conventions, how the personality function results are
6061represented in LLVM IR is target specific.
6062
6063The clauses are applied in order from top to bottom. If two
6064``landingpad`` instructions are merged together through inlining, the
6065clauses from the calling function are appended to the list of clauses.
6066When the call stack is being unwound due to an exception being thrown,
6067the exception is compared against each ``clause`` in turn. If it doesn't
6068match any of the clauses, and the ``cleanup`` flag is not set, then
6069unwinding continues further up the call stack.
6070
6071The ``landingpad`` instruction has several restrictions:
6072
6073- A landing pad block is a basic block which is the unwind destination
6074 of an '``invoke``' instruction.
6075- A landing pad block must have a '``landingpad``' instruction as its
6076 first non-PHI instruction.
6077- There can be only one '``landingpad``' instruction within the landing
6078 pad block.
6079- A basic block that is not a landing pad block may not include a
6080 '``landingpad``' instruction.
6081- All '``landingpad``' instructions in a function must have the same
6082 personality function.
6083
6084Example:
6085""""""""
6086
6087.. code-block:: llvm
6088
6089 ;; A landing pad which can catch an integer.
6090 %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0
6091 catch i8** @_ZTIi
6092 ;; A landing pad that is a cleanup.
6093 %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0
6094 cleanup
6095 ;; A landing pad which can catch an integer and can only throw a double.
6096 %res = landingpad { i8*, i32 } personality i32 (...)* @__gxx_personality_v0
6097 catch i8** @_ZTIi
6098 filter [1 x i8**] [@_ZTId]
6099
6100.. _intrinsics:
6101
6102Intrinsic Functions
6103===================
6104
6105LLVM supports the notion of an "intrinsic function". These functions
6106have well known names and semantics and are required to follow certain
6107restrictions. Overall, these intrinsics represent an extension mechanism
6108for the LLVM language that does not require changing all of the
6109transformations in LLVM when adding to the language (or the bitcode
6110reader/writer, the parser, etc...).
6111
6112Intrinsic function names must all start with an "``llvm.``" prefix. This
6113prefix is reserved in LLVM for intrinsic names; thus, function names may
6114not begin with this prefix. Intrinsic functions must always be external
6115functions: you cannot define the body of intrinsic functions. Intrinsic
6116functions may only be used in call or invoke instructions: it is illegal
6117to take the address of an intrinsic function. Additionally, because
6118intrinsic functions are part of the LLVM language, it is required if any
6119are added that they be documented here.
6120
6121Some intrinsic functions can be overloaded, i.e., the intrinsic
6122represents a family of functions that perform the same operation but on
6123different data types. Because LLVM can represent over 8 million
6124different integer types, overloading is used commonly to allow an
6125intrinsic function to operate on any integer type. One or more of the
6126argument types or the result type can be overloaded to accept any
6127integer type. Argument types may also be defined as exactly matching a
6128previous argument's type or the result type. This allows an intrinsic
6129function which accepts multiple arguments, but needs all of them to be
6130of the same type, to only be overloaded with respect to a single
6131argument or the result.
6132
6133Overloaded intrinsics will have the names of its overloaded argument
6134types encoded into its function name, each preceded by a period. Only
6135those types which are overloaded result in a name suffix. Arguments
6136whose type is matched against another type do not. For example, the
6137``llvm.ctpop`` function can take an integer of any width and returns an
6138integer of exactly the same integer width. This leads to a family of
6139functions such as ``i8 @llvm.ctpop.i8(i8 %val)`` and
6140``i29 @llvm.ctpop.i29(i29 %val)``. Only one type, the return type, is
6141overloaded, and only one type suffix is required. Because the argument's
6142type is matched against the return type, it does not require its own
6143name suffix.
6144
6145To learn how to add an intrinsic function, please see the `Extending
6146LLVM Guide <ExtendingLLVM.html>`_.
6147
6148.. _int_varargs:
6149
6150Variable Argument Handling Intrinsics
6151-------------------------------------
6152
6153Variable argument support is defined in LLVM with the
6154:ref:`va_arg <i_va_arg>` instruction and these three intrinsic
6155functions. These functions are related to the similarly named macros
6156defined in the ``<stdarg.h>`` header file.
6157
6158All of these functions operate on arguments that use a target-specific
6159value type "``va_list``". The LLVM assembly language reference manual
6160does not define what this type is, so all transformations should be
6161prepared to handle these functions regardless of the type used.
6162
6163This example shows how the :ref:`va_arg <i_va_arg>` instruction and the
6164variable argument handling intrinsic functions are used.
6165
6166.. code-block:: llvm
6167
6168 define i32 @test(i32 %X, ...) {
6169 ; Initialize variable argument processing
6170 %ap = alloca i8*
6171 %ap2 = bitcast i8** %ap to i8*
6172 call void @llvm.va_start(i8* %ap2)
6173
6174 ; Read a single integer argument
6175 %tmp = va_arg i8** %ap, i32
6176
6177 ; Demonstrate usage of llvm.va_copy and llvm.va_end
6178 %aq = alloca i8*
6179 %aq2 = bitcast i8** %aq to i8*
6180 call void @llvm.va_copy(i8* %aq2, i8* %ap2)
6181 call void @llvm.va_end(i8* %aq2)
6182
6183 ; Stop processing of arguments.
6184 call void @llvm.va_end(i8* %ap2)
6185 ret i32 %tmp
6186 }
6187
6188 declare void @llvm.va_start(i8*)
6189 declare void @llvm.va_copy(i8*, i8*)
6190 declare void @llvm.va_end(i8*)
6191
6192.. _int_va_start:
6193
6194'``llvm.va_start``' Intrinsic
6195^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6196
6197Syntax:
6198"""""""
6199
6200::
6201
6202 declare void %llvm.va_start(i8* <arglist>)
6203
6204Overview:
6205"""""""""
6206
6207The '``llvm.va_start``' intrinsic initializes ``*<arglist>`` for
6208subsequent use by ``va_arg``.
6209
6210Arguments:
6211""""""""""
6212
6213The argument is a pointer to a ``va_list`` element to initialize.
6214
6215Semantics:
6216""""""""""
6217
6218The '``llvm.va_start``' intrinsic works just like the ``va_start`` macro
6219available in C. In a target-dependent way, it initializes the
6220``va_list`` element to which the argument points, so that the next call
6221to ``va_arg`` will produce the first variable argument passed to the
6222function. Unlike the C ``va_start`` macro, this intrinsic does not need
6223to know the last argument of the function as the compiler can figure
6224that out.
6225
6226'``llvm.va_end``' Intrinsic
6227^^^^^^^^^^^^^^^^^^^^^^^^^^^
6228
6229Syntax:
6230"""""""
6231
6232::
6233
6234 declare void @llvm.va_end(i8* <arglist>)
6235
6236Overview:
6237"""""""""
6238
6239The '``llvm.va_end``' intrinsic destroys ``*<arglist>``, which has been
6240initialized previously with ``llvm.va_start`` or ``llvm.va_copy``.
6241
6242Arguments:
6243""""""""""
6244
6245The argument is a pointer to a ``va_list`` to destroy.
6246
6247Semantics:
6248""""""""""
6249
6250The '``llvm.va_end``' intrinsic works just like the ``va_end`` macro
6251available in C. In a target-dependent way, it destroys the ``va_list``
6252element to which the argument points. Calls to
6253:ref:`llvm.va_start <int_va_start>` and
6254:ref:`llvm.va_copy <int_va_copy>` must be matched exactly with calls to
6255``llvm.va_end``.
6256
6257.. _int_va_copy:
6258
6259'``llvm.va_copy``' Intrinsic
6260^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6261
6262Syntax:
6263"""""""
6264
6265::
6266
6267 declare void @llvm.va_copy(i8* <destarglist>, i8* <srcarglist>)
6268
6269Overview:
6270"""""""""
6271
6272The '``llvm.va_copy``' intrinsic copies the current argument position
6273from the source argument list to the destination argument list.
6274
6275Arguments:
6276""""""""""
6277
6278The first argument is a pointer to a ``va_list`` element to initialize.
6279The second argument is a pointer to a ``va_list`` element to copy from.
6280
6281Semantics:
6282""""""""""
6283
6284The '``llvm.va_copy``' intrinsic works just like the ``va_copy`` macro
6285available in C. In a target-dependent way, it copies the source
6286``va_list`` element into the destination ``va_list`` element. This
6287intrinsic is necessary because the `` llvm.va_start`` intrinsic may be
6288arbitrarily complex and require, for example, memory allocation.
6289
6290Accurate Garbage Collection Intrinsics
6291--------------------------------------
6292
6293LLVM support for `Accurate Garbage Collection <GarbageCollection.html>`_
6294(GC) requires the implementation and generation of these intrinsics.
6295These intrinsics allow identification of :ref:`GC roots on the
6296stack <int_gcroot>`, as well as garbage collector implementations that
6297require :ref:`read <int_gcread>` and :ref:`write <int_gcwrite>` barriers.
6298Front-ends for type-safe garbage collected languages should generate
6299these intrinsics to make use of the LLVM garbage collectors. For more
6300details, see `Accurate Garbage Collection with
6301LLVM <GarbageCollection.html>`_.
6302
6303The garbage collection intrinsics only operate on objects in the generic
6304address space (address space zero).
6305
6306.. _int_gcroot:
6307
6308'``llvm.gcroot``' Intrinsic
6309^^^^^^^^^^^^^^^^^^^^^^^^^^^
6310
6311Syntax:
6312"""""""
6313
6314::
6315
6316 declare void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
6317
6318Overview:
6319"""""""""
6320
6321The '``llvm.gcroot``' intrinsic declares the existence of a GC root to
6322the code generator, and allows some metadata to be associated with it.
6323
6324Arguments:
6325""""""""""
6326
6327The first argument specifies the address of a stack object that contains
6328the root pointer. The second pointer (which must be either a constant or
6329a global value address) contains the meta-data to be associated with the
6330root.
6331
6332Semantics:
6333""""""""""
6334
6335At runtime, a call to this intrinsic stores a null pointer into the
6336"ptrloc" location. At compile-time, the code generator generates
6337information to allow the runtime to find the pointer at GC safe points.
6338The '``llvm.gcroot``' intrinsic may only be used in a function which
6339:ref:`specifies a GC algorithm <gc>`.
6340
6341.. _int_gcread:
6342
6343'``llvm.gcread``' Intrinsic
6344^^^^^^^^^^^^^^^^^^^^^^^^^^^
6345
6346Syntax:
6347"""""""
6348
6349::
6350
6351 declare i8* @llvm.gcread(i8* %ObjPtr, i8** %Ptr)
6352
6353Overview:
6354"""""""""
6355
6356The '``llvm.gcread``' intrinsic identifies reads of references from heap
6357locations, allowing garbage collector implementations that require read
6358barriers.
6359
6360Arguments:
6361""""""""""
6362
6363The second argument is the address to read from, which should be an
6364address allocated from the garbage collector. The first object is a
6365pointer to the start of the referenced object, if needed by the language
6366runtime (otherwise null).
6367
6368Semantics:
6369""""""""""
6370
6371The '``llvm.gcread``' intrinsic has the same semantics as a load
6372instruction, but may be replaced with substantially more complex code by
6373the garbage collector runtime, as needed. The '``llvm.gcread``'
6374intrinsic may only be used in a function which :ref:`specifies a GC
6375algorithm <gc>`.
6376
6377.. _int_gcwrite:
6378
6379'``llvm.gcwrite``' Intrinsic
6380^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6381
6382Syntax:
6383"""""""
6384
6385::
6386
6387 declare void @llvm.gcwrite(i8* %P1, i8* %Obj, i8** %P2)
6388
6389Overview:
6390"""""""""
6391
6392The '``llvm.gcwrite``' intrinsic identifies writes of references to heap
6393locations, allowing garbage collector implementations that require write
6394barriers (such as generational or reference counting collectors).
6395
6396Arguments:
6397""""""""""
6398
6399The first argument is the reference to store, the second is the start of
6400the object to store it to, and the third is the address of the field of
6401Obj to store to. If the runtime does not require a pointer to the
6402object, Obj may be null.
6403
6404Semantics:
6405""""""""""
6406
6407The '``llvm.gcwrite``' intrinsic has the same semantics as a store
6408instruction, but may be replaced with substantially more complex code by
6409the garbage collector runtime, as needed. The '``llvm.gcwrite``'
6410intrinsic may only be used in a function which :ref:`specifies a GC
6411algorithm <gc>`.
6412
6413Code Generator Intrinsics
6414-------------------------
6415
6416These intrinsics are provided by LLVM to expose special features that
6417may only be implemented with code generator support.
6418
6419'``llvm.returnaddress``' Intrinsic
6420^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6421
6422Syntax:
6423"""""""
6424
6425::
6426
6427 declare i8 *@llvm.returnaddress(i32 <level>)
6428
6429Overview:
6430"""""""""
6431
6432The '``llvm.returnaddress``' intrinsic attempts to compute a
6433target-specific value indicating the return address of the current
6434function or one of its callers.
6435
6436Arguments:
6437""""""""""
6438
6439The argument to this intrinsic indicates which function to return the
6440address for. Zero indicates the calling function, one indicates its
6441caller, etc. The argument is **required** to be a constant integer
6442value.
6443
6444Semantics:
6445""""""""""
6446
6447The '``llvm.returnaddress``' intrinsic either returns a pointer
6448indicating the return address of the specified call frame, or zero if it
6449cannot be identified. The value returned by this intrinsic is likely to
6450be incorrect or 0 for arguments other than zero, so it should only be
6451used for debugging purposes.
6452
6453Note that calling this intrinsic does not prevent function inlining or
6454other aggressive transformations, so the value returned may not be that
6455of the obvious source-language caller.
6456
6457'``llvm.frameaddress``' Intrinsic
6458^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6459
6460Syntax:
6461"""""""
6462
6463::
6464
6465 declare i8* @llvm.frameaddress(i32 <level>)
6466
6467Overview:
6468"""""""""
6469
6470The '``llvm.frameaddress``' intrinsic attempts to return the
6471target-specific frame pointer value for the specified stack frame.
6472
6473Arguments:
6474""""""""""
6475
6476The argument to this intrinsic indicates which function to return the
6477frame pointer for. Zero indicates the calling function, one indicates
6478its caller, etc. The argument is **required** to be a constant integer
6479value.
6480
6481Semantics:
6482""""""""""
6483
6484The '``llvm.frameaddress``' intrinsic either returns a pointer
6485indicating the frame address of the specified call frame, or zero if it
6486cannot be identified. The value returned by this intrinsic is likely to
6487be incorrect or 0 for arguments other than zero, so it should only be
6488used for debugging purposes.
6489
6490Note that calling this intrinsic does not prevent function inlining or
6491other aggressive transformations, so the value returned may not be that
6492of the obvious source-language caller.
6493
6494.. _int_stacksave:
6495
6496'``llvm.stacksave``' Intrinsic
6497^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6498
6499Syntax:
6500"""""""
6501
6502::
6503
6504 declare i8* @llvm.stacksave()
6505
6506Overview:
6507"""""""""
6508
6509The '``llvm.stacksave``' intrinsic is used to remember the current state
6510of the function stack, for use with
6511:ref:`llvm.stackrestore <int_stackrestore>`. This is useful for
6512implementing language features like scoped automatic variable sized
6513arrays in C99.
6514
6515Semantics:
6516""""""""""
6517
6518This intrinsic returns a opaque pointer value that can be passed to
6519:ref:`llvm.stackrestore <int_stackrestore>`. When an
6520``llvm.stackrestore`` intrinsic is executed with a value saved from
6521``llvm.stacksave``, it effectively restores the state of the stack to
6522the state it was in when the ``llvm.stacksave`` intrinsic executed. In
6523practice, this pops any :ref:`alloca <i_alloca>` blocks from the stack that
6524were allocated after the ``llvm.stacksave`` was executed.
6525
6526.. _int_stackrestore:
6527
6528'``llvm.stackrestore``' Intrinsic
6529^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6530
6531Syntax:
6532"""""""
6533
6534::
6535
6536 declare void @llvm.stackrestore(i8* %ptr)
6537
6538Overview:
6539"""""""""
6540
6541The '``llvm.stackrestore``' intrinsic is used to restore the state of
6542the function stack to the state it was in when the corresponding
6543:ref:`llvm.stacksave <int_stacksave>` intrinsic executed. This is
6544useful for implementing language features like scoped automatic variable
6545sized arrays in C99.
6546
6547Semantics:
6548""""""""""
6549
6550See the description for :ref:`llvm.stacksave <int_stacksave>`.
6551
6552'``llvm.prefetch``' Intrinsic
6553^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6554
6555Syntax:
6556"""""""
6557
6558::
6559
6560 declare void @llvm.prefetch(i8* <address>, i32 <rw>, i32 <locality>, i32 <cache type>)
6561
6562Overview:
6563"""""""""
6564
6565The '``llvm.prefetch``' intrinsic is a hint to the code generator to
6566insert a prefetch instruction if supported; otherwise, it is a noop.
6567Prefetches have no effect on the behavior of the program but can change
6568its performance characteristics.
6569
6570Arguments:
6571""""""""""
6572
6573``address`` is the address to be prefetched, ``rw`` is the specifier
6574determining if the fetch should be for a read (0) or write (1), and
6575``locality`` is a temporal locality specifier ranging from (0) - no
6576locality, to (3) - extremely local keep in cache. The ``cache type``
6577specifies whether the prefetch is performed on the data (1) or
6578instruction (0) cache. The ``rw``, ``locality`` and ``cache type``
6579arguments must be constant integers.
6580
6581Semantics:
6582""""""""""
6583
6584This intrinsic does not modify the behavior of the program. In
6585particular, prefetches cannot trap and do not produce a value. On
6586targets that support this intrinsic, the prefetch can provide hints to
6587the processor cache for better performance.
6588
6589'``llvm.pcmarker``' Intrinsic
6590^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6591
6592Syntax:
6593"""""""
6594
6595::
6596
6597 declare void @llvm.pcmarker(i32 <id>)
6598
6599Overview:
6600"""""""""
6601
6602The '``llvm.pcmarker``' intrinsic is a method to export a Program
6603Counter (PC) in a region of code to simulators and other tools. The
6604method is target specific, but it is expected that the marker will use
6605exported symbols to transmit the PC of the marker. The marker makes no
6606guarantees that it will remain with any specific instruction after
6607optimizations. It is possible that the presence of a marker will inhibit
6608optimizations. The intended use is to be inserted after optimizations to
6609allow correlations of simulation runs.
6610
6611Arguments:
6612""""""""""
6613
6614``id`` is a numerical id identifying the marker.
6615
6616Semantics:
6617""""""""""
6618
6619This intrinsic does not modify the behavior of the program. Backends
6620that do not support this intrinsic may ignore it.
6621
6622'``llvm.readcyclecounter``' Intrinsic
6623^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6624
6625Syntax:
6626"""""""
6627
6628::
6629
6630 declare i64 @llvm.readcyclecounter()
6631
6632Overview:
6633"""""""""
6634
6635The '``llvm.readcyclecounter``' intrinsic provides access to the cycle
6636counter register (or similar low latency, high accuracy clocks) on those
6637targets that support it. On X86, it should map to RDTSC. On Alpha, it
6638should map to RPCC. As the backing counters overflow quickly (on the
6639order of 9 seconds on alpha), this should only be used for small
6640timings.
6641
6642Semantics:
6643""""""""""
6644
6645When directly supported, reading the cycle counter should not modify any
6646memory. Implementations are allowed to either return a application
6647specific value or a system wide value. On backends without support, this
6648is lowered to a constant 0.
6649
6650Standard C Library Intrinsics
6651-----------------------------
6652
6653LLVM provides intrinsics for a few important standard C library
6654functions. These intrinsics allow source-language front-ends to pass
6655information about the alignment of the pointer arguments to the code
6656generator, providing opportunity for more efficient code generation.
6657
6658.. _int_memcpy:
6659
6660'``llvm.memcpy``' Intrinsic
6661^^^^^^^^^^^^^^^^^^^^^^^^^^^
6662
6663Syntax:
6664"""""""
6665
6666This is an overloaded intrinsic. You can use ``llvm.memcpy`` on any
6667integer bit width and for different address spaces. Not all targets
6668support all bit widths however.
6669
6670::
6671
6672 declare void @llvm.memcpy.p0i8.p0i8.i32(i8* <dest>, i8* <src>,
6673 i32 <len>, i32 <align>, i1 <isvolatile>)
6674 declare void @llvm.memcpy.p0i8.p0i8.i64(i8* <dest>, i8* <src>,
6675 i64 <len>, i32 <align>, i1 <isvolatile>)
6676
6677Overview:
6678"""""""""
6679
6680The '``llvm.memcpy.*``' intrinsics copy a block of memory from the
6681source location to the destination location.
6682
6683Note that, unlike the standard libc function, the ``llvm.memcpy.*``
6684intrinsics do not return a value, takes extra alignment/isvolatile
6685arguments and the pointers can be in specified address spaces.
6686
6687Arguments:
6688""""""""""
6689
6690The first argument is a pointer to the destination, the second is a
6691pointer to the source. The third argument is an integer argument
6692specifying the number of bytes to copy, the fourth argument is the
6693alignment of the source and destination locations, and the fifth is a
6694boolean indicating a volatile access.
6695
6696If the call to this intrinsic has an alignment value that is not 0 or 1,
6697then the caller guarantees that both the source and destination pointers
6698are aligned to that boundary.
6699
6700If the ``isvolatile`` parameter is ``true``, the ``llvm.memcpy`` call is
6701a :ref:`volatile operation <volatile>`. The detailed access behavior is not
6702very cleanly specified and it is unwise to depend on it.
6703
6704Semantics:
6705""""""""""
6706
6707The '``llvm.memcpy.*``' intrinsics copy a block of memory from the
6708source location to the destination location, which are not allowed to
6709overlap. It copies "len" bytes of memory over. If the argument is known
6710to be aligned to some boundary, this can be specified as the fourth
6711argument, otherwise it should be set to 0 or 1.
6712
6713'``llvm.memmove``' Intrinsic
6714^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6715
6716Syntax:
6717"""""""
6718
6719This is an overloaded intrinsic. You can use llvm.memmove on any integer
6720bit width and for different address space. Not all targets support all
6721bit widths however.
6722
6723::
6724
6725 declare void @llvm.memmove.p0i8.p0i8.i32(i8* <dest>, i8* <src>,
6726 i32 <len>, i32 <align>, i1 <isvolatile>)
6727 declare void @llvm.memmove.p0i8.p0i8.i64(i8* <dest>, i8* <src>,
6728 i64 <len>, i32 <align>, i1 <isvolatile>)
6729
6730Overview:
6731"""""""""
6732
6733The '``llvm.memmove.*``' intrinsics move a block of memory from the
6734source location to the destination location. It is similar to the
6735'``llvm.memcpy``' intrinsic but allows the two memory locations to
6736overlap.
6737
6738Note that, unlike the standard libc function, the ``llvm.memmove.*``
6739intrinsics do not return a value, takes extra alignment/isvolatile
6740arguments and the pointers can be in specified address spaces.
6741
6742Arguments:
6743""""""""""
6744
6745The first argument is a pointer to the destination, the second is a
6746pointer to the source. The third argument is an integer argument
6747specifying the number of bytes to copy, the fourth argument is the
6748alignment of the source and destination locations, and the fifth is a
6749boolean indicating a volatile access.
6750
6751If the call to this intrinsic has an alignment value that is not 0 or 1,
6752then the caller guarantees that the source and destination pointers are
6753aligned to that boundary.
6754
6755If the ``isvolatile`` parameter is ``true``, the ``llvm.memmove`` call
6756is a :ref:`volatile operation <volatile>`. The detailed access behavior is
6757not very cleanly specified and it is unwise to depend on it.
6758
6759Semantics:
6760""""""""""
6761
6762The '``llvm.memmove.*``' intrinsics copy a block of memory from the
6763source location to the destination location, which may overlap. It
6764copies "len" bytes of memory over. If the argument is known to be
6765aligned to some boundary, this can be specified as the fourth argument,
6766otherwise it should be set to 0 or 1.
6767
6768'``llvm.memset.*``' Intrinsics
6769^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6770
6771Syntax:
6772"""""""
6773
6774This is an overloaded intrinsic. You can use llvm.memset on any integer
6775bit width and for different address spaces. However, not all targets
6776support all bit widths.
6777
6778::
6779
6780 declare void @llvm.memset.p0i8.i32(i8* <dest>, i8 <val>,
6781 i32 <len>, i32 <align>, i1 <isvolatile>)
6782 declare void @llvm.memset.p0i8.i64(i8* <dest>, i8 <val>,
6783 i64 <len>, i32 <align>, i1 <isvolatile>)
6784
6785Overview:
6786"""""""""
6787
6788The '``llvm.memset.*``' intrinsics fill a block of memory with a
6789particular byte value.
6790
6791Note that, unlike the standard libc function, the ``llvm.memset``
6792intrinsic does not return a value and takes extra alignment/volatile
6793arguments. Also, the destination can be in an arbitrary address space.
6794
6795Arguments:
6796""""""""""
6797
6798The first argument is a pointer to the destination to fill, the second
6799is the byte value with which to fill it, the third argument is an
6800integer argument specifying the number of bytes to fill, and the fourth
6801argument is the known alignment of the destination location.
6802
6803If the call to this intrinsic has an alignment value that is not 0 or 1,
6804then the caller guarantees that the destination pointer is aligned to
6805that boundary.
6806
6807If the ``isvolatile`` parameter is ``true``, the ``llvm.memset`` call is
6808a :ref:`volatile operation <volatile>`. The detailed access behavior is not
6809very cleanly specified and it is unwise to depend on it.
6810
6811Semantics:
6812""""""""""
6813
6814The '``llvm.memset.*``' intrinsics fill "len" bytes of memory starting
6815at the destination location. If the argument is known to be aligned to
6816some boundary, this can be specified as the fourth argument, otherwise
6817it should be set to 0 or 1.
6818
6819'``llvm.sqrt.*``' Intrinsic
6820^^^^^^^^^^^^^^^^^^^^^^^^^^^
6821
6822Syntax:
6823"""""""
6824
6825This is an overloaded intrinsic. You can use ``llvm.sqrt`` on any
6826floating point or vector of floating point type. Not all targets support
6827all types however.
6828
6829::
6830
6831 declare float @llvm.sqrt.f32(float %Val)
6832 declare double @llvm.sqrt.f64(double %Val)
6833 declare x86_fp80 @llvm.sqrt.f80(x86_fp80 %Val)
6834 declare fp128 @llvm.sqrt.f128(fp128 %Val)
6835 declare ppc_fp128 @llvm.sqrt.ppcf128(ppc_fp128 %Val)
6836
6837Overview:
6838"""""""""
6839
6840The '``llvm.sqrt``' intrinsics return the sqrt of the specified operand,
6841returning the same value as the libm '``sqrt``' functions would. Unlike
6842``sqrt`` in libm, however, ``llvm.sqrt`` has undefined behavior for
6843negative numbers other than -0.0 (which allows for better optimization,
6844because there is no need to worry about errno being set).
6845``llvm.sqrt(-0.0)`` is defined to return -0.0 like IEEE sqrt.
6846
6847Arguments:
6848""""""""""
6849
6850The argument and return value are floating point numbers of the same
6851type.
6852
6853Semantics:
6854""""""""""
6855
6856This function returns the sqrt of the specified operand if it is a
6857nonnegative floating point number.
6858
6859'``llvm.powi.*``' Intrinsic
6860^^^^^^^^^^^^^^^^^^^^^^^^^^^
6861
6862Syntax:
6863"""""""
6864
6865This is an overloaded intrinsic. You can use ``llvm.powi`` on any
6866floating point or vector of floating point type. Not all targets support
6867all types however.
6868
6869::
6870
6871 declare float @llvm.powi.f32(float %Val, i32 %power)
6872 declare double @llvm.powi.f64(double %Val, i32 %power)
6873 declare x86_fp80 @llvm.powi.f80(x86_fp80 %Val, i32 %power)
6874 declare fp128 @llvm.powi.f128(fp128 %Val, i32 %power)
6875 declare ppc_fp128 @llvm.powi.ppcf128(ppc_fp128 %Val, i32 %power)
6876
6877Overview:
6878"""""""""
6879
6880The '``llvm.powi.*``' intrinsics return the first operand raised to the
6881specified (positive or negative) power. The order of evaluation of
6882multiplications is not defined. When a vector of floating point type is
6883used, the second argument remains a scalar integer value.
6884
6885Arguments:
6886""""""""""
6887
6888The second argument is an integer power, and the first is a value to
6889raise to that power.
6890
6891Semantics:
6892""""""""""
6893
6894This function returns the first value raised to the second power with an
6895unspecified sequence of rounding operations.
6896
6897'``llvm.sin.*``' Intrinsic
6898^^^^^^^^^^^^^^^^^^^^^^^^^^
6899
6900Syntax:
6901"""""""
6902
6903This is an overloaded intrinsic. You can use ``llvm.sin`` on any
6904floating point or vector of floating point type. Not all targets support
6905all types however.
6906
6907::
6908
6909 declare float @llvm.sin.f32(float %Val)
6910 declare double @llvm.sin.f64(double %Val)
6911 declare x86_fp80 @llvm.sin.f80(x86_fp80 %Val)
6912 declare fp128 @llvm.sin.f128(fp128 %Val)
6913 declare ppc_fp128 @llvm.sin.ppcf128(ppc_fp128 %Val)
6914
6915Overview:
6916"""""""""
6917
6918The '``llvm.sin.*``' intrinsics return the sine of the operand.
6919
6920Arguments:
6921""""""""""
6922
6923The argument and return value are floating point numbers of the same
6924type.
6925
6926Semantics:
6927""""""""""
6928
6929This function returns the sine of the specified operand, returning the
6930same values as the libm ``sin`` functions would, and handles error
6931conditions in the same way.
6932
6933'``llvm.cos.*``' Intrinsic
6934^^^^^^^^^^^^^^^^^^^^^^^^^^
6935
6936Syntax:
6937"""""""
6938
6939This is an overloaded intrinsic. You can use ``llvm.cos`` on any
6940floating point or vector of floating point type. Not all targets support
6941all types however.
6942
6943::
6944
6945 declare float @llvm.cos.f32(float %Val)
6946 declare double @llvm.cos.f64(double %Val)
6947 declare x86_fp80 @llvm.cos.f80(x86_fp80 %Val)
6948 declare fp128 @llvm.cos.f128(fp128 %Val)
6949 declare ppc_fp128 @llvm.cos.ppcf128(ppc_fp128 %Val)
6950
6951Overview:
6952"""""""""
6953
6954The '``llvm.cos.*``' intrinsics return the cosine of the operand.
6955
6956Arguments:
6957""""""""""
6958
6959The argument and return value are floating point numbers of the same
6960type.
6961
6962Semantics:
6963""""""""""
6964
6965This function returns the cosine of the specified operand, returning the
6966same values as the libm ``cos`` functions would, and handles error
6967conditions in the same way.
6968
6969'``llvm.pow.*``' Intrinsic
6970^^^^^^^^^^^^^^^^^^^^^^^^^^
6971
6972Syntax:
6973"""""""
6974
6975This is an overloaded intrinsic. You can use ``llvm.pow`` on any
6976floating point or vector of floating point type. Not all targets support
6977all types however.
6978
6979::
6980
6981 declare float @llvm.pow.f32(float %Val, float %Power)
6982 declare double @llvm.pow.f64(double %Val, double %Power)
6983 declare x86_fp80 @llvm.pow.f80(x86_fp80 %Val, x86_fp80 %Power)
6984 declare fp128 @llvm.pow.f128(fp128 %Val, fp128 %Power)
6985 declare ppc_fp128 @llvm.pow.ppcf128(ppc_fp128 %Val, ppc_fp128 Power)
6986
6987Overview:
6988"""""""""
6989
6990The '``llvm.pow.*``' intrinsics return the first operand raised to the
6991specified (positive or negative) power.
6992
6993Arguments:
6994""""""""""
6995
6996The second argument is a floating point power, and the first is a value
6997to raise to that power.
6998
6999Semantics:
7000""""""""""
7001
7002This function returns the first value raised to the second power,
7003returning the same values as the libm ``pow`` functions would, and
7004handles error conditions in the same way.
7005
7006'``llvm.exp.*``' Intrinsic
7007^^^^^^^^^^^^^^^^^^^^^^^^^^
7008
7009Syntax:
7010"""""""
7011
7012This is an overloaded intrinsic. You can use ``llvm.exp`` on any
7013floating point or vector of floating point type. Not all targets support
7014all types however.
7015
7016::
7017
7018 declare float @llvm.exp.f32(float %Val)
7019 declare double @llvm.exp.f64(double %Val)
7020 declare x86_fp80 @llvm.exp.f80(x86_fp80 %Val)
7021 declare fp128 @llvm.exp.f128(fp128 %Val)
7022 declare ppc_fp128 @llvm.exp.ppcf128(ppc_fp128 %Val)
7023
7024Overview:
7025"""""""""
7026
7027The '``llvm.exp.*``' intrinsics perform the exp function.
7028
7029Arguments:
7030""""""""""
7031
7032The argument and return value are floating point numbers of the same
7033type.
7034
7035Semantics:
7036""""""""""
7037
7038This function returns the same values as the libm ``exp`` functions
7039would, and handles error conditions in the same way.
7040
7041'``llvm.exp2.*``' Intrinsic
7042^^^^^^^^^^^^^^^^^^^^^^^^^^^
7043
7044Syntax:
7045"""""""
7046
7047This is an overloaded intrinsic. You can use ``llvm.exp2`` on any
7048floating point or vector of floating point type. Not all targets support
7049all types however.
7050
7051::
7052
7053 declare float @llvm.exp2.f32(float %Val)
7054 declare double @llvm.exp2.f64(double %Val)
7055 declare x86_fp80 @llvm.exp2.f80(x86_fp80 %Val)
7056 declare fp128 @llvm.exp2.f128(fp128 %Val)
7057 declare ppc_fp128 @llvm.exp2.ppcf128(ppc_fp128 %Val)
7058
7059Overview:
7060"""""""""
7061
7062The '``llvm.exp2.*``' intrinsics perform the exp2 function.
7063
7064Arguments:
7065""""""""""
7066
7067The argument and return value are floating point numbers of the same
7068type.
7069
7070Semantics:
7071""""""""""
7072
7073This function returns the same values as the libm ``exp2`` functions
7074would, and handles error conditions in the same way.
7075
7076'``llvm.log.*``' Intrinsic
7077^^^^^^^^^^^^^^^^^^^^^^^^^^
7078
7079Syntax:
7080"""""""
7081
7082This is an overloaded intrinsic. You can use ``llvm.log`` on any
7083floating point or vector of floating point type. Not all targets support
7084all types however.
7085
7086::
7087
7088 declare float @llvm.log.f32(float %Val)
7089 declare double @llvm.log.f64(double %Val)
7090 declare x86_fp80 @llvm.log.f80(x86_fp80 %Val)
7091 declare fp128 @llvm.log.f128(fp128 %Val)
7092 declare ppc_fp128 @llvm.log.ppcf128(ppc_fp128 %Val)
7093
7094Overview:
7095"""""""""
7096
7097The '``llvm.log.*``' intrinsics perform the log function.
7098
7099Arguments:
7100""""""""""
7101
7102The argument and return value are floating point numbers of the same
7103type.
7104
7105Semantics:
7106""""""""""
7107
7108This function returns the same values as the libm ``log`` functions
7109would, and handles error conditions in the same way.
7110
7111'``llvm.log10.*``' Intrinsic
7112^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7113
7114Syntax:
7115"""""""
7116
7117This is an overloaded intrinsic. You can use ``llvm.log10`` on any
7118floating point or vector of floating point type. Not all targets support
7119all types however.
7120
7121::
7122
7123 declare float @llvm.log10.f32(float %Val)
7124 declare double @llvm.log10.f64(double %Val)
7125 declare x86_fp80 @llvm.log10.f80(x86_fp80 %Val)
7126 declare fp128 @llvm.log10.f128(fp128 %Val)
7127 declare ppc_fp128 @llvm.log10.ppcf128(ppc_fp128 %Val)
7128
7129Overview:
7130"""""""""
7131
7132The '``llvm.log10.*``' intrinsics perform the log10 function.
7133
7134Arguments:
7135""""""""""
7136
7137The argument and return value are floating point numbers of the same
7138type.
7139
7140Semantics:
7141""""""""""
7142
7143This function returns the same values as the libm ``log10`` functions
7144would, and handles error conditions in the same way.
7145
7146'``llvm.log2.*``' Intrinsic
7147^^^^^^^^^^^^^^^^^^^^^^^^^^^
7148
7149Syntax:
7150"""""""
7151
7152This is an overloaded intrinsic. You can use ``llvm.log2`` on any
7153floating point or vector of floating point type. Not all targets support
7154all types however.
7155
7156::
7157
7158 declare float @llvm.log2.f32(float %Val)
7159 declare double @llvm.log2.f64(double %Val)
7160 declare x86_fp80 @llvm.log2.f80(x86_fp80 %Val)
7161 declare fp128 @llvm.log2.f128(fp128 %Val)
7162 declare ppc_fp128 @llvm.log2.ppcf128(ppc_fp128 %Val)
7163
7164Overview:
7165"""""""""
7166
7167The '``llvm.log2.*``' intrinsics perform the log2 function.
7168
7169Arguments:
7170""""""""""
7171
7172The argument and return value are floating point numbers of the same
7173type.
7174
7175Semantics:
7176""""""""""
7177
7178This function returns the same values as the libm ``log2`` functions
7179would, and handles error conditions in the same way.
7180
7181'``llvm.fma.*``' Intrinsic
7182^^^^^^^^^^^^^^^^^^^^^^^^^^
7183
7184Syntax:
7185"""""""
7186
7187This is an overloaded intrinsic. You can use ``llvm.fma`` on any
7188floating point or vector of floating point type. Not all targets support
7189all types however.
7190
7191::
7192
7193 declare float @llvm.fma.f32(float %a, float %b, float %c)
7194 declare double @llvm.fma.f64(double %a, double %b, double %c)
7195 declare x86_fp80 @llvm.fma.f80(x86_fp80 %a, x86_fp80 %b, x86_fp80 %c)
7196 declare fp128 @llvm.fma.f128(fp128 %a, fp128 %b, fp128 %c)
7197 declare ppc_fp128 @llvm.fma.ppcf128(ppc_fp128 %a, ppc_fp128 %b, ppc_fp128 %c)
7198
7199Overview:
7200"""""""""
7201
7202The '``llvm.fma.*``' intrinsics perform the fused multiply-add
7203operation.
7204
7205Arguments:
7206""""""""""
7207
7208The argument and return value are floating point numbers of the same
7209type.
7210
7211Semantics:
7212""""""""""
7213
7214This function returns the same values as the libm ``fma`` functions
7215would.
7216
7217'``llvm.fabs.*``' Intrinsic
7218^^^^^^^^^^^^^^^^^^^^^^^^^^^
7219
7220Syntax:
7221"""""""
7222
7223This is an overloaded intrinsic. You can use ``llvm.fabs`` on any
7224floating point or vector of floating point type. Not all targets support
7225all types however.
7226
7227::
7228
7229 declare float @llvm.fabs.f32(float %Val)
7230 declare double @llvm.fabs.f64(double %Val)
7231 declare x86_fp80 @llvm.fabs.f80(x86_fp80 %Val)
7232 declare fp128 @llvm.fabs.f128(fp128 %Val)
7233 declare ppc_fp128 @llvm.fabs.ppcf128(ppc_fp128 %Val)
7234
7235Overview:
7236"""""""""
7237
7238The '``llvm.fabs.*``' intrinsics return the absolute value of the
7239operand.
7240
7241Arguments:
7242""""""""""
7243
7244The argument and return value are floating point numbers of the same
7245type.
7246
7247Semantics:
7248""""""""""
7249
7250This function returns the same values as the libm ``fabs`` functions
7251would, and handles error conditions in the same way.
7252
7253'``llvm.floor.*``' Intrinsic
7254^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7255
7256Syntax:
7257"""""""
7258
7259This is an overloaded intrinsic. You can use ``llvm.floor`` on any
7260floating point or vector of floating point type. Not all targets support
7261all types however.
7262
7263::
7264
7265 declare float @llvm.floor.f32(float %Val)
7266 declare double @llvm.floor.f64(double %Val)
7267 declare x86_fp80 @llvm.floor.f80(x86_fp80 %Val)
7268 declare fp128 @llvm.floor.f128(fp128 %Val)
7269 declare ppc_fp128 @llvm.floor.ppcf128(ppc_fp128 %Val)
7270
7271Overview:
7272"""""""""
7273
7274The '``llvm.floor.*``' intrinsics return the floor of the operand.
7275
7276Arguments:
7277""""""""""
7278
7279The argument and return value are floating point numbers of the same
7280type.
7281
7282Semantics:
7283""""""""""
7284
7285This function returns the same values as the libm ``floor`` functions
7286would, and handles error conditions in the same way.
7287
7288'``llvm.ceil.*``' Intrinsic
7289^^^^^^^^^^^^^^^^^^^^^^^^^^^
7290
7291Syntax:
7292"""""""
7293
7294This is an overloaded intrinsic. You can use ``llvm.ceil`` on any
7295floating point or vector of floating point type. Not all targets support
7296all types however.
7297
7298::
7299
7300 declare float @llvm.ceil.f32(float %Val)
7301 declare double @llvm.ceil.f64(double %Val)
7302 declare x86_fp80 @llvm.ceil.f80(x86_fp80 %Val)
7303 declare fp128 @llvm.ceil.f128(fp128 %Val)
7304 declare ppc_fp128 @llvm.ceil.ppcf128(ppc_fp128 %Val)
7305
7306Overview:
7307"""""""""
7308
7309The '``llvm.ceil.*``' intrinsics return the ceiling of the operand.
7310
7311Arguments:
7312""""""""""
7313
7314The argument and return value are floating point numbers of the same
7315type.
7316
7317Semantics:
7318""""""""""
7319
7320This function returns the same values as the libm ``ceil`` functions
7321would, and handles error conditions in the same way.
7322
7323'``llvm.trunc.*``' Intrinsic
7324^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7325
7326Syntax:
7327"""""""
7328
7329This is an overloaded intrinsic. You can use ``llvm.trunc`` on any
7330floating point or vector of floating point type. Not all targets support
7331all types however.
7332
7333::
7334
7335 declare float @llvm.trunc.f32(float %Val)
7336 declare double @llvm.trunc.f64(double %Val)
7337 declare x86_fp80 @llvm.trunc.f80(x86_fp80 %Val)
7338 declare fp128 @llvm.trunc.f128(fp128 %Val)
7339 declare ppc_fp128 @llvm.trunc.ppcf128(ppc_fp128 %Val)
7340
7341Overview:
7342"""""""""
7343
7344The '``llvm.trunc.*``' intrinsics returns the operand rounded to the
7345nearest integer not larger in magnitude than the operand.
7346
7347Arguments:
7348""""""""""
7349
7350The argument and return value are floating point numbers of the same
7351type.
7352
7353Semantics:
7354""""""""""
7355
7356This function returns the same values as the libm ``trunc`` functions
7357would, and handles error conditions in the same way.
7358
7359'``llvm.rint.*``' Intrinsic
7360^^^^^^^^^^^^^^^^^^^^^^^^^^^
7361
7362Syntax:
7363"""""""
7364
7365This is an overloaded intrinsic. You can use ``llvm.rint`` on any
7366floating point or vector of floating point type. Not all targets support
7367all types however.
7368
7369::
7370
7371 declare float @llvm.rint.f32(float %Val)
7372 declare double @llvm.rint.f64(double %Val)
7373 declare x86_fp80 @llvm.rint.f80(x86_fp80 %Val)
7374 declare fp128 @llvm.rint.f128(fp128 %Val)
7375 declare ppc_fp128 @llvm.rint.ppcf128(ppc_fp128 %Val)
7376
7377Overview:
7378"""""""""
7379
7380The '``llvm.rint.*``' intrinsics returns the operand rounded to the
7381nearest integer. It may raise an inexact floating-point exception if the
7382operand isn't an integer.
7383
7384Arguments:
7385""""""""""
7386
7387The argument and return value are floating point numbers of the same
7388type.
7389
7390Semantics:
7391""""""""""
7392
7393This function returns the same values as the libm ``rint`` functions
7394would, and handles error conditions in the same way.
7395
7396'``llvm.nearbyint.*``' Intrinsic
7397^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7398
7399Syntax:
7400"""""""
7401
7402This is an overloaded intrinsic. You can use ``llvm.nearbyint`` on any
7403floating point or vector of floating point type. Not all targets support
7404all types however.
7405
7406::
7407
7408 declare float @llvm.nearbyint.f32(float %Val)
7409 declare double @llvm.nearbyint.f64(double %Val)
7410 declare x86_fp80 @llvm.nearbyint.f80(x86_fp80 %Val)
7411 declare fp128 @llvm.nearbyint.f128(fp128 %Val)
7412 declare ppc_fp128 @llvm.nearbyint.ppcf128(ppc_fp128 %Val)
7413
7414Overview:
7415"""""""""
7416
7417The '``llvm.nearbyint.*``' intrinsics returns the operand rounded to the
7418nearest integer.
7419
7420Arguments:
7421""""""""""
7422
7423The argument and return value are floating point numbers of the same
7424type.
7425
7426Semantics:
7427""""""""""
7428
7429This function returns the same values as the libm ``nearbyint``
7430functions would, and handles error conditions in the same way.
7431
7432Bit Manipulation Intrinsics
7433---------------------------
7434
7435LLVM provides intrinsics for a few important bit manipulation
7436operations. These allow efficient code generation for some algorithms.
7437
7438'``llvm.bswap.*``' Intrinsics
7439^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7440
7441Syntax:
7442"""""""
7443
7444This is an overloaded intrinsic function. You can use bswap on any
7445integer type that is an even number of bytes (i.e. BitWidth % 16 == 0).
7446
7447::
7448
7449 declare i16 @llvm.bswap.i16(i16 <id>)
7450 declare i32 @llvm.bswap.i32(i32 <id>)
7451 declare i64 @llvm.bswap.i64(i64 <id>)
7452
7453Overview:
7454"""""""""
7455
7456The '``llvm.bswap``' family of intrinsics is used to byte swap integer
7457values with an even number of bytes (positive multiple of 16 bits).
7458These are useful for performing operations on data that is not in the
7459target's native byte order.
7460
7461Semantics:
7462""""""""""
7463
7464The ``llvm.bswap.i16`` intrinsic returns an i16 value that has the high
7465and low byte of the input i16 swapped. Similarly, the ``llvm.bswap.i32``
7466intrinsic returns an i32 value that has the four bytes of the input i32
7467swapped, so that if the input bytes are numbered 0, 1, 2, 3 then the
7468returned i32 will have its bytes in 3, 2, 1, 0 order. The
7469``llvm.bswap.i48``, ``llvm.bswap.i64`` and other intrinsics extend this
7470concept to additional even-byte lengths (6 bytes, 8 bytes and more,
7471respectively).
7472
7473'``llvm.ctpop.*``' Intrinsic
7474^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7475
7476Syntax:
7477"""""""
7478
7479This is an overloaded intrinsic. You can use llvm.ctpop on any integer
7480bit width, or on any vector with integer elements. Not all targets
7481support all bit widths or vector types, however.
7482
7483::
7484
7485 declare i8 @llvm.ctpop.i8(i8 <src>)
7486 declare i16 @llvm.ctpop.i16(i16 <src>)
7487 declare i32 @llvm.ctpop.i32(i32 <src>)
7488 declare i64 @llvm.ctpop.i64(i64 <src>)
7489 declare i256 @llvm.ctpop.i256(i256 <src>)
7490 declare <2 x i32> @llvm.ctpop.v2i32(<2 x i32> <src>)
7491
7492Overview:
7493"""""""""
7494
7495The '``llvm.ctpop``' family of intrinsics counts the number of bits set
7496in a value.
7497
7498Arguments:
7499""""""""""
7500
7501The only argument is the value to be counted. The argument may be of any
7502integer type, or a vector with integer elements. The return type must
7503match the argument type.
7504
7505Semantics:
7506""""""""""
7507
7508The '``llvm.ctpop``' intrinsic counts the 1's in a variable, or within
7509each element of a vector.
7510
7511'``llvm.ctlz.*``' Intrinsic
7512^^^^^^^^^^^^^^^^^^^^^^^^^^^
7513
7514Syntax:
7515"""""""
7516
7517This is an overloaded intrinsic. You can use ``llvm.ctlz`` on any
7518integer bit width, or any vector whose elements are integers. Not all
7519targets support all bit widths or vector types, however.
7520
7521::
7522
7523 declare i8 @llvm.ctlz.i8 (i8 <src>, i1 <is_zero_undef>)
7524 declare i16 @llvm.ctlz.i16 (i16 <src>, i1 <is_zero_undef>)
7525 declare i32 @llvm.ctlz.i32 (i32 <src>, i1 <is_zero_undef>)
7526 declare i64 @llvm.ctlz.i64 (i64 <src>, i1 <is_zero_undef>)
7527 declare i256 @llvm.ctlz.i256(i256 <src>, i1 <is_zero_undef>)
7528 declase <2 x i32> @llvm.ctlz.v2i32(<2 x i32> <src>, i1 <is_zero_undef>)
7529
7530Overview:
7531"""""""""
7532
7533The '``llvm.ctlz``' family of intrinsic functions counts the number of
7534leading zeros in a variable.
7535
7536Arguments:
7537""""""""""
7538
7539The first argument is the value to be counted. This argument may be of
7540any integer type, or a vectory with integer element type. The return
7541type must match the first argument type.
7542
7543The second argument must be a constant and is a flag to indicate whether
7544the intrinsic should ensure that a zero as the first argument produces a
7545defined result. Historically some architectures did not provide a
7546defined result for zero values as efficiently, and many algorithms are
7547now predicated on avoiding zero-value inputs.
7548
7549Semantics:
7550""""""""""
7551
7552The '``llvm.ctlz``' intrinsic counts the leading (most significant)
7553zeros in a variable, or within each element of the vector. If
7554``src == 0`` then the result is the size in bits of the type of ``src``
7555if ``is_zero_undef == 0`` and ``undef`` otherwise. For example,
7556``llvm.ctlz(i32 2) = 30``.
7557
7558'``llvm.cttz.*``' Intrinsic
7559^^^^^^^^^^^^^^^^^^^^^^^^^^^
7560
7561Syntax:
7562"""""""
7563
7564This is an overloaded intrinsic. You can use ``llvm.cttz`` on any
7565integer bit width, or any vector of integer elements. Not all targets
7566support all bit widths or vector types, however.
7567
7568::
7569
7570 declare i8 @llvm.cttz.i8 (i8 <src>, i1 <is_zero_undef>)
7571 declare i16 @llvm.cttz.i16 (i16 <src>, i1 <is_zero_undef>)
7572 declare i32 @llvm.cttz.i32 (i32 <src>, i1 <is_zero_undef>)
7573 declare i64 @llvm.cttz.i64 (i64 <src>, i1 <is_zero_undef>)
7574 declare i256 @llvm.cttz.i256(i256 <src>, i1 <is_zero_undef>)
7575 declase <2 x i32> @llvm.cttz.v2i32(<2 x i32> <src>, i1 <is_zero_undef>)
7576
7577Overview:
7578"""""""""
7579
7580The '``llvm.cttz``' family of intrinsic functions counts the number of
7581trailing zeros.
7582
7583Arguments:
7584""""""""""
7585
7586The first argument is the value to be counted. This argument may be of
7587any integer type, or a vectory with integer element type. The return
7588type must match the first argument type.
7589
7590The second argument must be a constant and is a flag to indicate whether
7591the intrinsic should ensure that a zero as the first argument produces a
7592defined result. Historically some architectures did not provide a
7593defined result for zero values as efficiently, and many algorithms are
7594now predicated on avoiding zero-value inputs.
7595
7596Semantics:
7597""""""""""
7598
7599The '``llvm.cttz``' intrinsic counts the trailing (least significant)
7600zeros in a variable, or within each element of a vector. If ``src == 0``
7601then the result is the size in bits of the type of ``src`` if
7602``is_zero_undef == 0`` and ``undef`` otherwise. For example,
7603``llvm.cttz(2) = 1``.
7604
7605Arithmetic with Overflow Intrinsics
7606-----------------------------------
7607
7608LLVM provides intrinsics for some arithmetic with overflow operations.
7609
7610'``llvm.sadd.with.overflow.*``' Intrinsics
7611^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7612
7613Syntax:
7614"""""""
7615
7616This is an overloaded intrinsic. You can use ``llvm.sadd.with.overflow``
7617on any integer bit width.
7618
7619::
7620
7621 declare {i16, i1} @llvm.sadd.with.overflow.i16(i16 %a, i16 %b)
7622 declare {i32, i1} @llvm.sadd.with.overflow.i32(i32 %a, i32 %b)
7623 declare {i64, i1} @llvm.sadd.with.overflow.i64(i64 %a, i64 %b)
7624
7625Overview:
7626"""""""""
7627
7628The '``llvm.sadd.with.overflow``' family of intrinsic functions perform
7629a signed addition of the two arguments, and indicate whether an overflow
7630occurred during the signed summation.
7631
7632Arguments:
7633""""""""""
7634
7635The arguments (%a and %b) and the first element of the result structure
7636may be of integer types of any bit width, but they must have the same
7637bit width. The second element of the result structure must be of type
7638``i1``. ``%a`` and ``%b`` are the two values that will undergo signed
7639addition.
7640
7641Semantics:
7642""""""""""
7643
7644The '``llvm.sadd.with.overflow``' family of intrinsic functions perform
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00007645a signed addition of the two variables. They return a structure --- the
Sean Silvaf722b002012-12-07 10:36:55 +00007646first element of which is the signed summation, and the second element
7647of which is a bit specifying if the signed summation resulted in an
7648overflow.
7649
7650Examples:
7651"""""""""
7652
7653.. code-block:: llvm
7654
7655 %res = call {i32, i1} @llvm.sadd.with.overflow.i32(i32 %a, i32 %b)
7656 %sum = extractvalue {i32, i1} %res, 0
7657 %obit = extractvalue {i32, i1} %res, 1
7658 br i1 %obit, label %overflow, label %normal
7659
7660'``llvm.uadd.with.overflow.*``' Intrinsics
7661^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7662
7663Syntax:
7664"""""""
7665
7666This is an overloaded intrinsic. You can use ``llvm.uadd.with.overflow``
7667on any integer bit width.
7668
7669::
7670
7671 declare {i16, i1} @llvm.uadd.with.overflow.i16(i16 %a, i16 %b)
7672 declare {i32, i1} @llvm.uadd.with.overflow.i32(i32 %a, i32 %b)
7673 declare {i64, i1} @llvm.uadd.with.overflow.i64(i64 %a, i64 %b)
7674
7675Overview:
7676"""""""""
7677
7678The '``llvm.uadd.with.overflow``' family of intrinsic functions perform
7679an unsigned addition of the two arguments, and indicate whether a carry
7680occurred during the unsigned summation.
7681
7682Arguments:
7683""""""""""
7684
7685The arguments (%a and %b) and the first element of the result structure
7686may be of integer types of any bit width, but they must have the same
7687bit width. The second element of the result structure must be of type
7688``i1``. ``%a`` and ``%b`` are the two values that will undergo unsigned
7689addition.
7690
7691Semantics:
7692""""""""""
7693
7694The '``llvm.uadd.with.overflow``' family of intrinsic functions perform
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00007695an unsigned addition of the two arguments. They return a structure --- the
Sean Silvaf722b002012-12-07 10:36:55 +00007696first element of which is the sum, and the second element of which is a
7697bit specifying if the unsigned summation resulted in a carry.
7698
7699Examples:
7700"""""""""
7701
7702.. code-block:: llvm
7703
7704 %res = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %a, i32 %b)
7705 %sum = extractvalue {i32, i1} %res, 0
7706 %obit = extractvalue {i32, i1} %res, 1
7707 br i1 %obit, label %carry, label %normal
7708
7709'``llvm.ssub.with.overflow.*``' Intrinsics
7710^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7711
7712Syntax:
7713"""""""
7714
7715This is an overloaded intrinsic. You can use ``llvm.ssub.with.overflow``
7716on any integer bit width.
7717
7718::
7719
7720 declare {i16, i1} @llvm.ssub.with.overflow.i16(i16 %a, i16 %b)
7721 declare {i32, i1} @llvm.ssub.with.overflow.i32(i32 %a, i32 %b)
7722 declare {i64, i1} @llvm.ssub.with.overflow.i64(i64 %a, i64 %b)
7723
7724Overview:
7725"""""""""
7726
7727The '``llvm.ssub.with.overflow``' family of intrinsic functions perform
7728a signed subtraction of the two arguments, and indicate whether an
7729overflow occurred during the signed subtraction.
7730
7731Arguments:
7732""""""""""
7733
7734The arguments (%a and %b) and the first element of the result structure
7735may be of integer types of any bit width, but they must have the same
7736bit width. The second element of the result structure must be of type
7737``i1``. ``%a`` and ``%b`` are the two values that will undergo signed
7738subtraction.
7739
7740Semantics:
7741""""""""""
7742
7743The '``llvm.ssub.with.overflow``' family of intrinsic functions perform
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00007744a signed subtraction of the two arguments. They return a structure --- the
Sean Silvaf722b002012-12-07 10:36:55 +00007745first element of which is the subtraction, and the second element of
7746which is a bit specifying if the signed subtraction resulted in an
7747overflow.
7748
7749Examples:
7750"""""""""
7751
7752.. code-block:: llvm
7753
7754 %res = call {i32, i1} @llvm.ssub.with.overflow.i32(i32 %a, i32 %b)
7755 %sum = extractvalue {i32, i1} %res, 0
7756 %obit = extractvalue {i32, i1} %res, 1
7757 br i1 %obit, label %overflow, label %normal
7758
7759'``llvm.usub.with.overflow.*``' Intrinsics
7760^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7761
7762Syntax:
7763"""""""
7764
7765This is an overloaded intrinsic. You can use ``llvm.usub.with.overflow``
7766on any integer bit width.
7767
7768::
7769
7770 declare {i16, i1} @llvm.usub.with.overflow.i16(i16 %a, i16 %b)
7771 declare {i32, i1} @llvm.usub.with.overflow.i32(i32 %a, i32 %b)
7772 declare {i64, i1} @llvm.usub.with.overflow.i64(i64 %a, i64 %b)
7773
7774Overview:
7775"""""""""
7776
7777The '``llvm.usub.with.overflow``' family of intrinsic functions perform
7778an unsigned subtraction of the two arguments, and indicate whether an
7779overflow occurred during the unsigned subtraction.
7780
7781Arguments:
7782""""""""""
7783
7784The arguments (%a and %b) and the first element of the result structure
7785may be of integer types of any bit width, but they must have the same
7786bit width. The second element of the result structure must be of type
7787``i1``. ``%a`` and ``%b`` are the two values that will undergo unsigned
7788subtraction.
7789
7790Semantics:
7791""""""""""
7792
7793The '``llvm.usub.with.overflow``' family of intrinsic functions perform
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00007794an unsigned subtraction of the two arguments. They return a structure ---
Sean Silvaf722b002012-12-07 10:36:55 +00007795the first element of which is the subtraction, and the second element of
7796which is a bit specifying if the unsigned subtraction resulted in an
7797overflow.
7798
7799Examples:
7800"""""""""
7801
7802.. code-block:: llvm
7803
7804 %res = call {i32, i1} @llvm.usub.with.overflow.i32(i32 %a, i32 %b)
7805 %sum = extractvalue {i32, i1} %res, 0
7806 %obit = extractvalue {i32, i1} %res, 1
7807 br i1 %obit, label %overflow, label %normal
7808
7809'``llvm.smul.with.overflow.*``' Intrinsics
7810^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7811
7812Syntax:
7813"""""""
7814
7815This is an overloaded intrinsic. You can use ``llvm.smul.with.overflow``
7816on any integer bit width.
7817
7818::
7819
7820 declare {i16, i1} @llvm.smul.with.overflow.i16(i16 %a, i16 %b)
7821 declare {i32, i1} @llvm.smul.with.overflow.i32(i32 %a, i32 %b)
7822 declare {i64, i1} @llvm.smul.with.overflow.i64(i64 %a, i64 %b)
7823
7824Overview:
7825"""""""""
7826
7827The '``llvm.smul.with.overflow``' family of intrinsic functions perform
7828a signed multiplication of the two arguments, and indicate whether an
7829overflow occurred during the signed multiplication.
7830
7831Arguments:
7832""""""""""
7833
7834The arguments (%a and %b) and the first element of the result structure
7835may be of integer types of any bit width, but they must have the same
7836bit width. The second element of the result structure must be of type
7837``i1``. ``%a`` and ``%b`` are the two values that will undergo signed
7838multiplication.
7839
7840Semantics:
7841""""""""""
7842
7843The '``llvm.smul.with.overflow``' family of intrinsic functions perform
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00007844a signed multiplication of the two arguments. They return a structure ---
Sean Silvaf722b002012-12-07 10:36:55 +00007845the first element of which is the multiplication, and the second element
7846of which is a bit specifying if the signed multiplication resulted in an
7847overflow.
7848
7849Examples:
7850"""""""""
7851
7852.. code-block:: llvm
7853
7854 %res = call {i32, i1} @llvm.smul.with.overflow.i32(i32 %a, i32 %b)
7855 %sum = extractvalue {i32, i1} %res, 0
7856 %obit = extractvalue {i32, i1} %res, 1
7857 br i1 %obit, label %overflow, label %normal
7858
7859'``llvm.umul.with.overflow.*``' Intrinsics
7860^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7861
7862Syntax:
7863"""""""
7864
7865This is an overloaded intrinsic. You can use ``llvm.umul.with.overflow``
7866on any integer bit width.
7867
7868::
7869
7870 declare {i16, i1} @llvm.umul.with.overflow.i16(i16 %a, i16 %b)
7871 declare {i32, i1} @llvm.umul.with.overflow.i32(i32 %a, i32 %b)
7872 declare {i64, i1} @llvm.umul.with.overflow.i64(i64 %a, i64 %b)
7873
7874Overview:
7875"""""""""
7876
7877The '``llvm.umul.with.overflow``' family of intrinsic functions perform
7878a unsigned multiplication of the two arguments, and indicate whether an
7879overflow occurred during the unsigned multiplication.
7880
7881Arguments:
7882""""""""""
7883
7884The arguments (%a and %b) and the first element of the result structure
7885may be of integer types of any bit width, but they must have the same
7886bit width. The second element of the result structure must be of type
7887``i1``. ``%a`` and ``%b`` are the two values that will undergo unsigned
7888multiplication.
7889
7890Semantics:
7891""""""""""
7892
7893The '``llvm.umul.with.overflow``' family of intrinsic functions perform
Dmitri Gribenkoae4a9ae2013-01-19 20:34:20 +00007894an unsigned multiplication of the two arguments. They return a structure ---
7895the first element of which is the multiplication, and the second
Sean Silvaf722b002012-12-07 10:36:55 +00007896element of which is a bit specifying if the unsigned multiplication
7897resulted in an overflow.
7898
7899Examples:
7900"""""""""
7901
7902.. code-block:: llvm
7903
7904 %res = call {i32, i1} @llvm.umul.with.overflow.i32(i32 %a, i32 %b)
7905 %sum = extractvalue {i32, i1} %res, 0
7906 %obit = extractvalue {i32, i1} %res, 1
7907 br i1 %obit, label %overflow, label %normal
7908
7909Specialised Arithmetic Intrinsics
7910---------------------------------
7911
7912'``llvm.fmuladd.*``' Intrinsic
7913^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7914
7915Syntax:
7916"""""""
7917
7918::
7919
7920 declare float @llvm.fmuladd.f32(float %a, float %b, float %c)
7921 declare double @llvm.fmuladd.f64(double %a, double %b, double %c)
7922
7923Overview:
7924"""""""""
7925
7926The '``llvm.fmuladd.*``' intrinsic functions represent multiply-add
Lang Hamesb0ec16b2013-01-17 00:00:49 +00007927expressions that can be fused if the code generator determines that (a) the
7928target instruction set has support for a fused operation, and (b) that the
7929fused operation is more efficient than the equivalent, separate pair of mul
7930and add instructions.
Sean Silvaf722b002012-12-07 10:36:55 +00007931
7932Arguments:
7933""""""""""
7934
7935The '``llvm.fmuladd.*``' intrinsics each take three arguments: two
7936multiplicands, a and b, and an addend c.
7937
7938Semantics:
7939""""""""""
7940
7941The expression:
7942
7943::
7944
7945 %0 = call float @llvm.fmuladd.f32(%a, %b, %c)
7946
7947is equivalent to the expression a \* b + c, except that rounding will
7948not be performed between the multiplication and addition steps if the
7949code generator fuses the operations. Fusion is not guaranteed, even if
7950the target platform supports it. If a fused multiply-add is required the
7951corresponding llvm.fma.\* intrinsic function should be used instead.
7952
7953Examples:
7954"""""""""
7955
7956.. code-block:: llvm
7957
7958 %r2 = call float @llvm.fmuladd.f32(float %a, float %b, float %c) ; yields {float}:r2 = (a * b) + c
7959
7960Half Precision Floating Point Intrinsics
7961----------------------------------------
7962
7963For most target platforms, half precision floating point is a
7964storage-only format. This means that it is a dense encoding (in memory)
7965but does not support computation in the format.
7966
7967This means that code must first load the half-precision floating point
7968value as an i16, then convert it to float with
7969:ref:`llvm.convert.from.fp16 <int_convert_from_fp16>`. Computation can
7970then be performed on the float value (including extending to double
7971etc). To store the value back to memory, it is first converted to float
7972if needed, then converted to i16 with
7973:ref:`llvm.convert.to.fp16 <int_convert_to_fp16>`, then storing as an
7974i16 value.
7975
7976.. _int_convert_to_fp16:
7977
7978'``llvm.convert.to.fp16``' Intrinsic
7979^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7980
7981Syntax:
7982"""""""
7983
7984::
7985
7986 declare i16 @llvm.convert.to.fp16(f32 %a)
7987
7988Overview:
7989"""""""""
7990
7991The '``llvm.convert.to.fp16``' intrinsic function performs a conversion
7992from single precision floating point format to half precision floating
7993point format.
7994
7995Arguments:
7996""""""""""
7997
7998The intrinsic function contains single argument - the value to be
7999converted.
8000
8001Semantics:
8002""""""""""
8003
8004The '``llvm.convert.to.fp16``' intrinsic function performs a conversion
8005from single precision floating point format to half precision floating
8006point format. The return value is an ``i16`` which contains the
8007converted number.
8008
8009Examples:
8010"""""""""
8011
8012.. code-block:: llvm
8013
8014 %res = call i16 @llvm.convert.to.fp16(f32 %a)
8015 store i16 %res, i16* @x, align 2
8016
8017.. _int_convert_from_fp16:
8018
8019'``llvm.convert.from.fp16``' Intrinsic
8020^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8021
8022Syntax:
8023"""""""
8024
8025::
8026
8027 declare f32 @llvm.convert.from.fp16(i16 %a)
8028
8029Overview:
8030"""""""""
8031
8032The '``llvm.convert.from.fp16``' intrinsic function performs a
8033conversion from half precision floating point format to single precision
8034floating point format.
8035
8036Arguments:
8037""""""""""
8038
8039The intrinsic function contains single argument - the value to be
8040converted.
8041
8042Semantics:
8043""""""""""
8044
8045The '``llvm.convert.from.fp16``' intrinsic function performs a
8046conversion from half single precision floating point format to single
8047precision floating point format. The input half-float value is
8048represented by an ``i16`` value.
8049
8050Examples:
8051"""""""""
8052
8053.. code-block:: llvm
8054
8055 %a = load i16* @x, align 2
8056 %res = call f32 @llvm.convert.from.fp16(i16 %a)
8057
8058Debugger Intrinsics
8059-------------------
8060
8061The LLVM debugger intrinsics (which all start with ``llvm.dbg.``
8062prefix), are described in the `LLVM Source Level
8063Debugging <SourceLevelDebugging.html#format_common_intrinsics>`_
8064document.
8065
8066Exception Handling Intrinsics
8067-----------------------------
8068
8069The LLVM exception handling intrinsics (which all start with
8070``llvm.eh.`` prefix), are described in the `LLVM Exception
8071Handling <ExceptionHandling.html#format_common_intrinsics>`_ document.
8072
8073.. _int_trampoline:
8074
8075Trampoline Intrinsics
8076---------------------
8077
8078These intrinsics make it possible to excise one parameter, marked with
8079the :ref:`nest <nest>` attribute, from a function. The result is a
8080callable function pointer lacking the nest parameter - the caller does
8081not need to provide a value for it. Instead, the value to use is stored
8082in advance in a "trampoline", a block of memory usually allocated on the
8083stack, which also contains code to splice the nest value into the
8084argument list. This is used to implement the GCC nested function address
8085extension.
8086
8087For example, if the function is ``i32 f(i8* nest %c, i32 %x, i32 %y)``
8088then the resulting function pointer has signature ``i32 (i32, i32)*``.
8089It can be created as follows:
8090
8091.. code-block:: llvm
8092
8093 %tramp = alloca [10 x i8], align 4 ; size and alignment only correct for X86
8094 %tramp1 = getelementptr [10 x i8]* %tramp, i32 0, i32 0
8095 call i8* @llvm.init.trampoline(i8* %tramp1, i8* bitcast (i32 (i8*, i32, i32)* @f to i8*), i8* %nval)
8096 %p = call i8* @llvm.adjust.trampoline(i8* %tramp1)
8097 %fp = bitcast i8* %p to i32 (i32, i32)*
8098
8099The call ``%val = call i32 %fp(i32 %x, i32 %y)`` is then equivalent to
8100``%val = call i32 %f(i8* %nval, i32 %x, i32 %y)``.
8101
8102.. _int_it:
8103
8104'``llvm.init.trampoline``' Intrinsic
8105^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8106
8107Syntax:
8108"""""""
8109
8110::
8111
8112 declare void @llvm.init.trampoline(i8* <tramp>, i8* <func>, i8* <nval>)
8113
8114Overview:
8115"""""""""
8116
8117This fills the memory pointed to by ``tramp`` with executable code,
8118turning it into a trampoline.
8119
8120Arguments:
8121""""""""""
8122
8123The ``llvm.init.trampoline`` intrinsic takes three arguments, all
8124pointers. The ``tramp`` argument must point to a sufficiently large and
8125sufficiently aligned block of memory; this memory is written to by the
8126intrinsic. Note that the size and the alignment are target-specific -
8127LLVM currently provides no portable way of determining them, so a
8128front-end that generates this intrinsic needs to have some
8129target-specific knowledge. The ``func`` argument must hold a function
8130bitcast to an ``i8*``.
8131
8132Semantics:
8133""""""""""
8134
8135The block of memory pointed to by ``tramp`` is filled with target
8136dependent code, turning it into a function. Then ``tramp`` needs to be
8137passed to :ref:`llvm.adjust.trampoline <int_at>` to get a pointer which can
8138be :ref:`bitcast (to a new function) and called <int_trampoline>`. The new
8139function's signature is the same as that of ``func`` with any arguments
8140marked with the ``nest`` attribute removed. At most one such ``nest``
8141argument is allowed, and it must be of pointer type. Calling the new
8142function is equivalent to calling ``func`` with the same argument list,
8143but with ``nval`` used for the missing ``nest`` argument. If, after
8144calling ``llvm.init.trampoline``, the memory pointed to by ``tramp`` is
8145modified, then the effect of any later call to the returned function
8146pointer is undefined.
8147
8148.. _int_at:
8149
8150'``llvm.adjust.trampoline``' Intrinsic
8151^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8152
8153Syntax:
8154"""""""
8155
8156::
8157
8158 declare i8* @llvm.adjust.trampoline(i8* <tramp>)
8159
8160Overview:
8161"""""""""
8162
8163This performs any required machine-specific adjustment to the address of
8164a trampoline (passed as ``tramp``).
8165
8166Arguments:
8167""""""""""
8168
8169``tramp`` must point to a block of memory which already has trampoline
8170code filled in by a previous call to
8171:ref:`llvm.init.trampoline <int_it>`.
8172
8173Semantics:
8174""""""""""
8175
8176On some architectures the address of the code to be executed needs to be
8177different to the address where the trampoline is actually stored. This
8178intrinsic returns the executable address corresponding to ``tramp``
8179after performing the required machine specific adjustments. The pointer
8180returned can then be :ref:`bitcast and executed <int_trampoline>`.
8181
8182Memory Use Markers
8183------------------
8184
8185This class of intrinsics exists to information about the lifetime of
8186memory objects and ranges where variables are immutable.
8187
8188'``llvm.lifetime.start``' Intrinsic
8189^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8190
8191Syntax:
8192"""""""
8193
8194::
8195
8196 declare void @llvm.lifetime.start(i64 <size>, i8* nocapture <ptr>)
8197
8198Overview:
8199"""""""""
8200
8201The '``llvm.lifetime.start``' intrinsic specifies the start of a memory
8202object's lifetime.
8203
8204Arguments:
8205""""""""""
8206
8207The first argument is a constant integer representing the size of the
8208object, or -1 if it is variable sized. The second argument is a pointer
8209to the object.
8210
8211Semantics:
8212""""""""""
8213
8214This intrinsic indicates that before this point in the code, the value
8215of the memory pointed to by ``ptr`` is dead. This means that it is known
8216to never be used and has an undefined value. A load from the pointer
8217that precedes this intrinsic can be replaced with ``'undef'``.
8218
8219'``llvm.lifetime.end``' Intrinsic
8220^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8221
8222Syntax:
8223"""""""
8224
8225::
8226
8227 declare void @llvm.lifetime.end(i64 <size>, i8* nocapture <ptr>)
8228
8229Overview:
8230"""""""""
8231
8232The '``llvm.lifetime.end``' intrinsic specifies the end of a memory
8233object's lifetime.
8234
8235Arguments:
8236""""""""""
8237
8238The first argument is a constant integer representing the size of the
8239object, or -1 if it is variable sized. The second argument is a pointer
8240to the object.
8241
8242Semantics:
8243""""""""""
8244
8245This intrinsic indicates that after this point in the code, the value of
8246the memory pointed to by ``ptr`` is dead. This means that it is known to
8247never be used and has an undefined value. Any stores into the memory
8248object following this intrinsic may be removed as dead.
8249
8250'``llvm.invariant.start``' Intrinsic
8251^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8252
8253Syntax:
8254"""""""
8255
8256::
8257
8258 declare {}* @llvm.invariant.start(i64 <size>, i8* nocapture <ptr>)
8259
8260Overview:
8261"""""""""
8262
8263The '``llvm.invariant.start``' intrinsic specifies that the contents of
8264a memory object will not change.
8265
8266Arguments:
8267""""""""""
8268
8269The first argument is a constant integer representing the size of the
8270object, or -1 if it is variable sized. The second argument is a pointer
8271to the object.
8272
8273Semantics:
8274""""""""""
8275
8276This intrinsic indicates that until an ``llvm.invariant.end`` that uses
8277the return value, the referenced memory location is constant and
8278unchanging.
8279
8280'``llvm.invariant.end``' Intrinsic
8281^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8282
8283Syntax:
8284"""""""
8285
8286::
8287
8288 declare void @llvm.invariant.end({}* <start>, i64 <size>, i8* nocapture <ptr>)
8289
8290Overview:
8291"""""""""
8292
8293The '``llvm.invariant.end``' intrinsic specifies that the contents of a
8294memory object are mutable.
8295
8296Arguments:
8297""""""""""
8298
8299The first argument is the matching ``llvm.invariant.start`` intrinsic.
8300The second argument is a constant integer representing the size of the
8301object, or -1 if it is variable sized and the third argument is a
8302pointer to the object.
8303
8304Semantics:
8305""""""""""
8306
8307This intrinsic indicates that the memory is mutable again.
8308
8309General Intrinsics
8310------------------
8311
8312This class of intrinsics is designed to be generic and has no specific
8313purpose.
8314
8315'``llvm.var.annotation``' Intrinsic
8316^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8317
8318Syntax:
8319"""""""
8320
8321::
8322
8323 declare void @llvm.var.annotation(i8* <val>, i8* <str>, i8* <str>, i32 <int>)
8324
8325Overview:
8326"""""""""
8327
8328The '``llvm.var.annotation``' intrinsic.
8329
8330Arguments:
8331""""""""""
8332
8333The first argument is a pointer to a value, the second is a pointer to a
8334global string, the third is a pointer to a global string which is the
8335source file name, and the last argument is the line number.
8336
8337Semantics:
8338""""""""""
8339
8340This intrinsic allows annotation of local variables with arbitrary
8341strings. This can be useful for special purpose optimizations that want
8342to look for these annotations. These have no other defined use; they are
8343ignored by code generation and optimization.
8344
8345'``llvm.annotation.*``' Intrinsic
8346^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8347
8348Syntax:
8349"""""""
8350
8351This is an overloaded intrinsic. You can use '``llvm.annotation``' on
8352any integer bit width.
8353
8354::
8355
8356 declare i8 @llvm.annotation.i8(i8 <val>, i8* <str>, i8* <str>, i32 <int>)
8357 declare i16 @llvm.annotation.i16(i16 <val>, i8* <str>, i8* <str>, i32 <int>)
8358 declare i32 @llvm.annotation.i32(i32 <val>, i8* <str>, i8* <str>, i32 <int>)
8359 declare i64 @llvm.annotation.i64(i64 <val>, i8* <str>, i8* <str>, i32 <int>)
8360 declare i256 @llvm.annotation.i256(i256 <val>, i8* <str>, i8* <str>, i32 <int>)
8361
8362Overview:
8363"""""""""
8364
8365The '``llvm.annotation``' intrinsic.
8366
8367Arguments:
8368""""""""""
8369
8370The first argument is an integer value (result of some expression), the
8371second is a pointer to a global string, the third is a pointer to a
8372global string which is the source file name, and the last argument is
8373the line number. It returns the value of the first argument.
8374
8375Semantics:
8376""""""""""
8377
8378This intrinsic allows annotations to be put on arbitrary expressions
8379with arbitrary strings. This can be useful for special purpose
8380optimizations that want to look for these annotations. These have no
8381other defined use; they are ignored by code generation and optimization.
8382
8383'``llvm.trap``' Intrinsic
8384^^^^^^^^^^^^^^^^^^^^^^^^^
8385
8386Syntax:
8387"""""""
8388
8389::
8390
8391 declare void @llvm.trap() noreturn nounwind
8392
8393Overview:
8394"""""""""
8395
8396The '``llvm.trap``' intrinsic.
8397
8398Arguments:
8399""""""""""
8400
8401None.
8402
8403Semantics:
8404""""""""""
8405
8406This intrinsic is lowered to the target dependent trap instruction. If
8407the target does not have a trap instruction, this intrinsic will be
8408lowered to a call of the ``abort()`` function.
8409
8410'``llvm.debugtrap``' Intrinsic
8411^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8412
8413Syntax:
8414"""""""
8415
8416::
8417
8418 declare void @llvm.debugtrap() nounwind
8419
8420Overview:
8421"""""""""
8422
8423The '``llvm.debugtrap``' intrinsic.
8424
8425Arguments:
8426""""""""""
8427
8428None.
8429
8430Semantics:
8431""""""""""
8432
8433This intrinsic is lowered to code which is intended to cause an
8434execution trap with the intention of requesting the attention of a
8435debugger.
8436
8437'``llvm.stackprotector``' Intrinsic
8438^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8439
8440Syntax:
8441"""""""
8442
8443::
8444
8445 declare void @llvm.stackprotector(i8* <guard>, i8** <slot>)
8446
8447Overview:
8448"""""""""
8449
8450The ``llvm.stackprotector`` intrinsic takes the ``guard`` and stores it
8451onto the stack at ``slot``. The stack slot is adjusted to ensure that it
8452is placed on the stack before local variables.
8453
8454Arguments:
8455""""""""""
8456
8457The ``llvm.stackprotector`` intrinsic requires two pointer arguments.
8458The first argument is the value loaded from the stack guard
8459``@__stack_chk_guard``. The second variable is an ``alloca`` that has
8460enough space to hold the value of the guard.
8461
8462Semantics:
8463""""""""""
8464
8465This intrinsic causes the prologue/epilogue inserter to force the
8466position of the ``AllocaInst`` stack slot to be before local variables
8467on the stack. This is to ensure that if a local variable on the stack is
8468overwritten, it will destroy the value of the guard. When the function
8469exits, the guard on the stack is checked against the original guard. If
8470they are different, then the program aborts by calling the
8471``__stack_chk_fail()`` function.
8472
8473'``llvm.objectsize``' Intrinsic
8474^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8475
8476Syntax:
8477"""""""
8478
8479::
8480
8481 declare i32 @llvm.objectsize.i32(i8* <object>, i1 <min>)
8482 declare i64 @llvm.objectsize.i64(i8* <object>, i1 <min>)
8483
8484Overview:
8485"""""""""
8486
8487The ``llvm.objectsize`` intrinsic is designed to provide information to
8488the optimizers to determine at compile time whether a) an operation
8489(like memcpy) will overflow a buffer that corresponds to an object, or
8490b) that a runtime check for overflow isn't necessary. An object in this
8491context means an allocation of a specific class, structure, array, or
8492other object.
8493
8494Arguments:
8495""""""""""
8496
8497The ``llvm.objectsize`` intrinsic takes two arguments. The first
8498argument is a pointer to or into the ``object``. The second argument is
8499a boolean and determines whether ``llvm.objectsize`` returns 0 (if true)
8500or -1 (if false) when the object size is unknown. The second argument
8501only accepts constants.
8502
8503Semantics:
8504""""""""""
8505
8506The ``llvm.objectsize`` intrinsic is lowered to a constant representing
8507the size of the object concerned. If the size cannot be determined at
8508compile time, ``llvm.objectsize`` returns ``i32/i64 -1 or 0`` (depending
8509on the ``min`` argument).
8510
8511'``llvm.expect``' Intrinsic
8512^^^^^^^^^^^^^^^^^^^^^^^^^^^
8513
8514Syntax:
8515"""""""
8516
8517::
8518
8519 declare i32 @llvm.expect.i32(i32 <val>, i32 <expected_val>)
8520 declare i64 @llvm.expect.i64(i64 <val>, i64 <expected_val>)
8521
8522Overview:
8523"""""""""
8524
8525The ``llvm.expect`` intrinsic provides information about expected (the
8526most probable) value of ``val``, which can be used by optimizers.
8527
8528Arguments:
8529""""""""""
8530
8531The ``llvm.expect`` intrinsic takes two arguments. The first argument is
8532a value. The second argument is an expected value, this needs to be a
8533constant value, variables are not allowed.
8534
8535Semantics:
8536""""""""""
8537
8538This intrinsic is lowered to the ``val``.
8539
8540'``llvm.donothing``' Intrinsic
8541^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8542
8543Syntax:
8544"""""""
8545
8546::
8547
8548 declare void @llvm.donothing() nounwind readnone
8549
8550Overview:
8551"""""""""
8552
8553The ``llvm.donothing`` intrinsic doesn't perform any operation. It's the
8554only intrinsic that can be called with an invoke instruction.
8555
8556Arguments:
8557""""""""""
8558
8559None.
8560
8561Semantics:
8562""""""""""
8563
8564This intrinsic does nothing, and it's removed by optimizers and ignored
8565by codegen.