IRBuilder
public class IRBuilder
An IRBuilder is a helper object that generates LLVM instructions.
IR builders keep track of a position (the “insertion point”) within a
module, function, or basic block and has methods to insert instructions at
that position. Other features include conveniences to insert calls to
C standard library functions like malloc and free, the creation of
global entities like © strings, and inline assembly.
Threading Considerations
An IRBuilder object is not thread safe. It is associated with a single
module which is, in turn, associated with a single LLVM context object.
In concurrent environments, exactly one IRBuilder should be created per
thread, and that thread should be the one that ultimately created its parent
module and context. Inserting instructions into the same IR builder object
in a concurrent manner will result in malformed IR being generated in
non-deterministic ways. If concurrent codegen is needed, a separate LLVM
context, module, and IRBuilder should be created on each thread.
Once each thread has finished generating code, the resulting modules should
be merged together. See Module.link(_:) for more information.
IR Navigation
By default, the insertion point of a builder is undefined. To move the IR builder’s cursor, a basic block must be created, but not necessarily inserted into a function.
let module = Module(name: "Example")
let builder = IRBuilder(module: module)
// Create a freestanding basic block and insert an `ret`
// instruction into it.
let freestanding = BasicBlock(name: "freestanding")
// Move the IR builder to the end of the block's instruction list.
builder.positionAtEnd(of: freestanding)
let ret = builder.buildRetVoid()
Instructions serve as a way to position the IR builder to a point before their creation. This allows for instructions to be inserted before a given instruction rather than at the very end of a basic block.
// Move before the `ret` instruction
builder.positionBefore(ret)
// Insert an `alloca` instruction before the `ret`.
let intAlloca = builder.buildAlloca(type: IntType.int8)
// Move before the `alloca`
builder.positionBefore(intAlloca)
// Insert an `malloc` call before the `alloca`.
let intMalloc = builder.buildMalloc(IntType.int8)
To insert this block into a function, see Function.append.
Sometimes it is necessary to reset the insertion point. When the insertion
point is reset, instructions built with the IR builder are still created,
but are not inserted into a basic block. To clear the insertion point, call
IRBuilder.clearInsertionPosition().
Building LLVM IR
All functions that build instructions are prefixed with build. Invoking
these functions inserts the appropriate LLVM instruction at the insertion
point, assuming it points to a valid location.
let module = Module(name: "Example")
let builder = IRBuilder(module: module)
let fun = builder.addFunction("test",
type: FunctionType([
IntType.int8,
IntType.int8,
], FloatType.float))
let entry = fun.appendBasicBlock(named: "entry")
// Set the insertion point to the entry block of this function
builder.positionAtEnd(of: entry)
// Build an `add` instruction at the insertion point
let result = builder.buildAdd(fun.parameters[0], fun.parameters[1])
Customizing LLVM IR
To be well-formed, certain instructions may involve more setup than just
being built. In such cases, LLVMSwift will yield a specific instance of
IRInstruction that will allow for this kind of configuration.
A prominent example of this is the PHI node. Building a PHI node produces
an empty PHI node - this is not a well-formed instruction. A PHI node must
have its incoming basic blocks attached. To do so, PhiNode.addIncoming(_:)
is called with a list of pairs of incoming values and their enclosing
basic blocks.
// Build a function that selects one of two floating parameters based
// on a given boolean value.
let module = Module(name: "Example")
let builder = IRBuilder(module: module)
let select = builder.addFunction("select",
type: FunctionType([
IntType.int1,
FloatType.float,
FloatType.float,
], FloatType.float))
let entry = select.appendBasicBlock(named: "entry")
builder.positionAtEnd(of: entry)
let thenBlock = select.appendBasicBlock(named: "then")
let elseBlock = select.appendBasicBlock(named: "else")
let mergeBB = select.appendBasicBlock(named: "merge")
let branch = builder.buildCondBr(condition: select.parameters[0],
then: thenBlock,
else: elseBlock)
builder.positionAtEnd(of: thenBlock)
let opThen = builder.buildAdd(select.parameters[1], select.parameters[2])
builder.buildBr(mergeBB)
builder.positionAtEnd(of: elseBlock)
let opElse = builder.buildSub(select.parameters[1], select.parameters[2])
builder.buildBr(mergeBB)
builder.positionAtEnd(of: mergeBB)
// Build the PHI node
let phi = builder.buildPhi(FloatType.float)
// Attach the incoming blocks.
phi.addIncoming([
(opThen, thenBlock),
(opElse, elseBlock),
])
builder.buildRet(phi)
-
Repositions the IR Builder at the end of the given basic block.
Declaration
Swift
public func positionAtEnd(of block: BasicBlock)Parameters
blockThe basic block to reposition the IR Builder after.
-
Repositions the IR Builder before the start of the given instruction.
Declaration
Swift
public func positionBefore(_ inst: IRInstruction)Parameters
instThe instruction to reposition the IR Builder before.
-
Repositions the IR Builder at the point specified by the given instruction in the given basic block.
This is equivalent to calling
positionAtEnd(of:)with the given basic block then callingpositionBefore(_:)with the given instruction.Declaration
Swift
public func position(_ inst: IRInstruction, block: BasicBlock)Parameters
instThe instruction to reposition the IR Builder before.
blockThe basic block to reposition the IR builder in.
-
Clears the insertion point.
Subsequent instructions will not be inserted into a block.
Declaration
Swift
public func clearInsertionPosition() -
Gets the basic block built instructions will be inserted into.
Declaration
Swift
public var insertBlock: BasicBlock? { get } -
Gets the function this builder is building into.
Declaration
Swift
public var currentFunction: Function? { get } -
Inserts the given instruction into the IR Builder.
Declaration
Swift
public func insert(_ inst: IRInstruction, name: String? = nil)Parameters
instThe instruction to insert.
nameThe name for the newly inserted instruction.
-
Access location information used by debugging information.
Declaration
Swift
public var currentDebugLocation: DebugLocation? { get set } -
Set the floating point math metadata to be used for floating-point operations.
Declaration
Swift
public var defaultFloatingPointMathTag: MDNode? { get set }
-
Builds the specified binary operation instruction with the given arguments.
Declaration
Parameters
opThe operation to build.
lhsThe first operand.
rhsThe second operand.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of perfomring the given binary operation with the given values as arguments.
-
Builds the specified cast operation instruction with the given value and destination type.
Declaration
Parameters
opThe cast operation to build.
valueThe value to cast.
typeThe destination type to cast to.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of casting the given value to the given destination type using the given operation.
-
Builds a cast operation from a value of pointer type to any other integral, pointer, or vector of integral/pointer type.
There are a number of restrictions on the form of the input value and destination type. The source value of a pointer cast must be either a pointer or a vector of pointers. The destination type must either be an integer type, a pointer type, or a vector type with integral or pointer element type.
If the destination type is an integral type or a vector of integral elements, this builds a
ptrtointinstruction. Else, if the destination is a pointer type or vector of pointer type, and it has an address space that differs from the address space of the source value, anaddrspacecastinstruction is built. If none of these are true, abitcastinstruction is built.Declaration
Parameters
valueThe value to cast. The value must have pointer type.
typeThe destination type to cast to. This must be a pointer type, integer type, or vector of the same.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of casting the given value to the given destination type using the appropriate pointer cast operation.
-
Builds a cast operation from a value of integral type to given integral type by zero-extension, sign-extension, bitcast, or truncation as necessary.
Declaration
Parameters
valueThe value to cast.
typeThe destination integer type to cast to.
signedIf true, if an extension is required it will be a sign-extension. Else, all required extensions will be zero-extensions.
nameThe name for the newly inserted instruction.
Return Value
A value reprresenting the result of casting the given value to the given destination integer type using the appropriate integral cast operation.
-
Build a negation instruction with the given value as an operand.
Whether an integer or floating point negate instruction is built is determined by the type of the given value. Providing an operand that is neither an integer nor a floating value is a fatal condition.
Declaration
Swift
public func buildNeg(_ value: IRValue, overflowBehavior: OverflowBehavior = .default, name: String = "") -> IRValueParameters
valueThe value to negate.
overflowBehaviorShould overflow occur, specifies the behavior of the program.
nameThe name for the newly inserted instruction.
Return Value
A value representing the negation of the given value.
-
Build an add instruction with the given values as operands.
Whether an integer or floating point add instruction is built is determined by the type of the first given value. Providing operands that are neither integers nor floating values is a fatal condition.
Declaration
Swift
public func buildAdd(_ lhs: IRValue, _ rhs: IRValue, overflowBehavior: OverflowBehavior = .default, name: String = "") -> IRValueParameters
lhsThe first summand value (the augend).
rhsThe second summand value (the addend).
overflowBehaviorShould overflow occur, specifies the behavior of the program.
nameThe name for the newly inserted instruction.
Return Value
A value representing the sum of the two operands.
-
Build a subtract instruction with the given values as operands.
Whether an integer or floating point subtract instruction is built is determined by the type of the first given value. Providing operands that are neither integers nor floating values is a fatal condition.
Declaration
Swift
public func buildSub(_ lhs: IRValue, _ rhs: IRValue, overflowBehavior: OverflowBehavior = .default, name: String = "") -> IRValueParameters
lhsThe first value (the minuend).
rhsThe second value (the subtrahend).
overflowBehaviorShould overflow occur, specifies the behavior of the program.
nameThe name for the newly inserted instruction.
Return Value
A value representing the difference of the two operands.
-
Build a multiply instruction with the given values as operands.
Whether an integer or floating point multiply instruction is built is determined by the type of the first given value. Providing operands that are neither integers nor floating values is a fatal condition.
Declaration
Swift
public func buildMul(_ lhs: IRValue, _ rhs: IRValue, overflowBehavior: OverflowBehavior = .default, name: String = "") -> IRValueParameters
lhsThe first factor value (the multiplier).
rhsThe second factor value (the multiplicand).
overflowBehaviorShould overflow occur, specifies the behavior of the program.
nameThe name for the newly inserted instruction.
Return Value
A value representing the product of the two operands.
-
Build a remainder instruction that provides the remainder after divison of the first value by the second value.
Whether an integer or floating point remainder instruction is built is determined by the type of the first given value. Providing operands that are neither integers nor floating values is a fatal condition.
Declaration
Parameters
lhsThe first value (the dividend).
rhsThe second value (the divisor).
signedWhether to emit a signed or unsigned remainder instruction. Defaults to emission of a signed remainder instruction.
nameThe name for the newly inserted instruction.
Return Value
A value representing the remainder of division of the first operand by the second operand.
-
Build a division instruction that divides the first value by the second value.
Whether an integer or floating point divide instruction is built is determined by the type of the first given value. Providing operands that are neither integers nor floating values is a fatal condition.
Declaration
Parameters
lhsThe first value (the dividend).
rhsThe second value (the divisor).
signedWhether to emit a signed or unsigned remainder instruction. Defaults to emission of a signed divide instruction.
exactWhether this division must be exact. Defaults to inexact.
nameThe name for the newly inserted instruction.
Return Value
A value representing the quotient of the first and second operands.
-
Build an integer comparison between the two provided values using the given predicate.
Precondition
Arguments must be integer or pointer or integer vector typedPrecondition
lhs.type == rhs.type
Declaration
Swift
public func buildICmp(_ lhs: IRValue, _ rhs: IRValue, _ predicate: IntPredicate, name: String = "") -> IRValueParameters
lhsThe first value to compare.
rhsThe second value to compare.
predicateThe method of comparison to use.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of the comparision of the given operands.
-
Build a floating comparison between the two provided values using the given predicate.
Attempting to compare operands that are not floating is a fatal condition.
Declaration
Swift
public func buildFCmp(_ lhs: IRValue, _ rhs: IRValue, _ predicate: RealPredicate, name: String = "") -> IRValueParameters
lhsThe first value to compare.
rhsThe second value to compare.
predicateThe method of comparison to use.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of the comparision of the given operands.
-
Build a bitwise logical not with the given value as an operand.
Parameters
valThe value to negate.
nameThe name for the newly inserted instruction.
Return Value
A value representing the logical negation of the given operand.
-
Build a bitwise logical exclusive OR with the given values as operands.
Declaration
Parameters
lhsThe first operand.
rhsThe second operand.
nameThe name for the newly inserted instruction.
Return Value
A value representing the exclusive OR of the values of the two given operands.
-
Build a bitwise logical OR with the given values as operands.
Parameters
lhsThe first operand.
rhsThe second operand.
nameThe name for the newly inserted instruction.
Return Value
A value representing the logical OR of the values of the two given operands.
-
Build a bitwise logical AND with the given values as operands.
Declaration
Parameters
lhsThe first operand.
rhsThe second operand.
nameThe name for the newly inserted instruction.
Return Value
A value representing the logical AND of the values of the two given operands.
-
Build a left-shift instruction of the first value by an amount in the second value.
Declaration
Parameters
lhsThe first operand.
rhsThe number of bits to shift the first operand left by.
nameThe name for the newly inserted instruction.
Return Value
A value representing the value of the first operand shifted left by the number of bits specified in the second operand.
-
Build a right-shift instruction of the first value by an amount in the second value. If
isArithmeticis true the value of the first operand is bitshifted with sign extension. Else the value is bitshifted with zero-fill.Declaration
Parameters
lhsThe first operand.
rhsThe number of bits to shift the first operand right by.
isArithmeticWhether this instruction performs an arithmetic or logical right-shift. The default is a logical right-shift.
nameThe name for the newly inserted instruction.
Return Value
A value representing the value of the first operand shifted right by the numeber of bits specified in the second operand.
-
Build a phi node with the given type acting as the result of any incoming basic blocks.
Parameters
typeThe type of incoming values.
nameThe name for the newly inserted instruction.
Return Value
A value representing the newly inserted phi node.
-
Build a select instruction to choose a value based on a condition without IR-level branching.
Declaration
Swift
public func buildSelect(_ cond: IRValue, then: IRValue, else: IRValue, name: String = "") -> IRInstructionParameters
condThe condition to evaluate. It must have type
i1or be a vector ofi1.thenThe value to select if the given condition is true.
elseThe value to select if the given condition is false.
nameThe name for the newly inserted instruction.
Return Value
A value representing the value selected for by the condition.
-
Build a branch table that branches on the given value with the given default basic block.
The
switchinstruction is used to transfer control flow to one of several different places. It is a generalization of thebrinstruction, allowing a branch to occur to one of many possible destinations.This function returns a value that acts as a representation of the branch table for the
switchinstruction. When theswitchinstruction is executed, this table is searched for the given value. If the value is found, control flow is transferred to the corresponding destination; otherwise, control flow is transferred to the default destination specified by theelseblock.To add branches to the
switchtable, seeSwitch.addCase(_:_:).Declaration
Swift
public func buildSwitch(_ value: IRValue, else: BasicBlock, caseCount: Int) -> SwitchParameters
valueThe value to compare.
elseThe default destination for control flow should the value not match a case in the branch table.
caseCountThe number of cases in the branch table.
Return Value
A value representing the newly inserted
switchinstruction.
-
Build a named function body with the given type.
Declaration
Swift
public func addFunction(_ name: String, type: FunctionType) -> FunctionParameters
nameThe name of the newly defined function.
typeThe type of the newly defined function.
Return Value
A value representing the newly inserted function definition.
-
Build a named structure definition.
Declaration
Swift
public func createStruct(name: String, types: [IRType]? = nil, isPacked: Bool = false) -> StructTypeParameters
nameThe name of the structure.
typesThe type of fields that make up the structure’s body.
isPackedWhether this structure should be 1-byte aligned with no padding between elements.
Return Value
A value representing the newly declared named structure.
-
Build an unconditional branch to the given basic block.
The
brinstruction is used to cause control flow to transfer to a different basic block in the current function. There are two forms of this instruction, corresponding to a conditional branch and an unconditional branch. To build a conditional branch, seebuildCondBr(condition:then:else:).Declaration
Swift
@discardableResult public func buildBr(_ block: BasicBlock) -> IRInstructionParameters
blockThe target block to transfer control flow to.
Return Value
A value representing
void. -
Build a condition branch that branches to the first basic block if the provided condition is
true, otherwise to the second basic block.The
brinstruction is used to cause control flow to transfer to a different basic block in the current function. There are two forms of this instruction, corresponding to a conditional branch and an unconditional branch. To build an unconditional branch, seebuildBr(_:).Declaration
Swift
@discardableResult public func buildCondBr( condition: IRValue, then: BasicBlock, `else`: BasicBlock) -> IRInstructionParameters
conditionA value of type
i1that determines which basic block to transfer control flow to.thenThe basic block to transfer control flow to if the condition evaluates to
true.elseThe basic block to transfer control flow to if the condition evaluates to
false.Return Value
A value representing
void. -
Build an indirect branch to a label within the current function.
The
indirectbrinstruction implements an indirect branch to a label within the current function, whose address is specified by theaddressparameter.All possible destination blocks must be listed in the
destinationslist, otherwise this instruction has undefined behavior. This implies that jumps to labels defined in other functions have undefined behavior as well.Declaration
Swift
@discardableResult public func buildIndirectBr(address: BasicBlock.Address, destinations: [BasicBlock]) -> IRInstructionParameters
addressThe address of the label to branch to.
destinationsThe set of possible destinations the address may point to. The same block may appear multiple times in this list, though this isn’t particularly useful.
Return Value
An IRValue representing
void. -
Build a return from the current function back to the calling function with the given value.
Returning a value with a type that does not correspond to the return type of the current function is a fatal condition.
There are two forms of the
retinstruction: one that returns a value and then causes control flow, and one that just causes control flow to occur. To build theretthat does not return a value usebuildRetVoid().Declaration
Swift
@discardableResult public func buildRet(_ val: IRValue) -> IRInstructionParameters
valThe value to return from the current function.
Return Value
A value representing
void. -
Build a void return from the current function.
If the current function does not have a
Voidreturn value, failure to return a falue is a fatal condition.There are two forms of the
retinstruction: one that returns a value and then causes control flow, and one that just causes control flow to occur. To build theretthat returns a value usebuildRet(_:).Declaration
Swift
@discardableResult public func buildRetVoid() -> IRInstructionReturn Value
A value representing
void. -
Build an unreachable instruction in the current function.
The
unreachableinstruction has no defined semantics. This instruction is used to inform the optimizer that a particular portion of the code is not reachable. This can be used to indicate that the code after a no-return function cannot be reached, and other facts.Declaration
Swift
@discardableResult public func buildUnreachable() -> IRInstructionReturn Value
A value representing
void. -
Build a return from the current function back to the calling function with the given array of values as members of an aggregate.
Declaration
Swift
@discardableResult public func buildRetAggregate(of values: [IRValue]) -> IRInstructionParameters
valuesThe values to insert as members of the returned aggregate.
Return Value
A value representing
void. -
Build a call to the given function with the given arguments to transfer control to that function.
Parameters
fnThe function to invoke.
argsA list of arguments.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of returning from the callee.
-
Build a call to the given function with the given arguments with the possibility of control transfering to either the
nextbasic block or thecatchbasic block if an exception occurs.If the callee function returns with the
retinstruction, control flow will return to thenextlabel. If the callee (or any indirect callees) returns via theresumeinstruction or other exception handling mechanism, control is interrupted and continued at the dynamically nearestexceptionlabel.The
catchblock is a landing pad for the exception. As such, the first instruction of that block is required to be thelandingpadinstruction, which contains the information about the behavior of the program after unwinding happens.Declaration
Swift
public func buildInvoke(_ fn: IRValue, args: [IRValue], next: BasicBlock, catch: BasicBlock, name: String = "") -> InvokeParameters
fnThe function to invoke.
argsA list of arguments.
nextThe destination block if the invoke succeeds without exceptions.
catchThe destination block if the invoke encounters an exception.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of returning from the callee under normal circumstances. Under exceptional circumstances, the value represents the value of any
resumeinstruction in thecatchblock. -
Build a landing pad to specify that a basic block is where an exception lands, and corresponds to the code found in the
catchportion of atry/catchsequence.The clauses are applied in order from top to bottom. If two landing pad instructions are merged together through inlining, the clauses from the calling function are appended to the list of clauses. When the call stack is being unwound due to an exception being thrown, the exception is compared against each clause in turn. If it doesn’t match any of the clauses, and the cleanup flag is not set, then unwinding continues further up the call stack.
The landingpad instruction has several restrictions:
- A landing pad block is a basic block which is the unwind destination of
an
invokeinstruction. - A landing pad block must have a
landingpadinstruction as its first non-PHI instruction. - There can be only one
landingpadinstruction within the landing pad block. A basic block that is not a landing pad block may not include a
landingpadinstruction.
Declaration
Swift
public func buildLandingPad(returning type: IRType, personalityFn: Function? = nil, clauses: [LandingPadClause], cleanup: Bool = false, name: String = "") -> IRInstructionParameters
typeThe type of the resulting value from the landing pad.
personalityFnThe personality function.
clausesA list of
catchandfilterclauses. This list must either be non-empty or the landing pad must be marked as a cleanup instruction.cleanupA flag indicating whether the landing pad is a cleanup.
nameThe name for the newly inserted instruction.
Return Value
A value of the given type representing the result of matching a clause during unwinding.
- A landing pad block is a basic block which is the unwind destination of
an
-
Build a resume instruction to resume propagation of an existing (in-flight) exception whose unwinding was interrupted with a
landingpadinstruction.When all cleanups are finished, if an exception is not handled by the current function, unwinding resumes by calling the resume instruction, passing in the result of the
landingpadinstruction for the original landing pad.Return Value
A value representing
void. -
Build a
va_arginstruction to access arguments passed through the “variable argument” area of a function call.This instruction is used to implement the
va_argmacro in C.Declaration
Parameters
listA value of type
va_list*typeThe type of values in the variable argument area.
nameThe name for the newly inserted instruction.
Return Value
A value of the specified argument type. In addition, the
va_listpointer is incremented to point to the next argument.
-
Build an
allocato allocate stack memory to hold a value of the given type.The
allocainstruction allocatessizeof(<type>)*countbytes of memory on the runtime stack, returning a pointer of the appropriate type to the program. Ifcountis specified, it is the number of elements allocated, otherwisecountis defaulted to be one. If a constant alignment is specified, the value result of the allocation is guaranteed to be aligned to at least that boundary. The alignment may not be greater than1 << 29. If not specified, or if zero, the target will choose a default value that is convenient and compatible with the type.The returned value is allocated in the address space specified in the data layout string for the target. If no such value is specified, the value is allocated in the default address space.
Declaration
Swift
public func buildAlloca(type: IRType, count: IRValue? = nil, alignment: Alignment = .zero, name: String = "") -> IRInstructionParameters
typeThe sized type used to determine the amount of stack memory to allocate.
countAn optional number of slots to allocate, to simulate a C array.
alignmentThe alignment of the access.
nameThe name for the newly inserted instruction.
Return Value
A value representing
void. -
Build a store instruction that stores the first value into the location given in the second value.
If alignment is not specified, or if zero, the target will choose a default value that is convenient and compatible with the type.
Declaration
Swift
@discardableResult public func buildStore(_ val: IRValue, to ptr: IRValue, ordering: AtomicOrdering = .notAtomic, volatile: Bool = false, alignment: Alignment = .zero) -> IRInstructionParameters
valThe source value.
ptrThe destination pointer to store into.
orderingThe ordering effect of the fence for this store, if any. Defaults to a nonatomic store.
volatileWhether this is a store to a volatile memory location.
alignmentThe alignment of the access.
Return Value
A value representing
void. -
Build a load instruction that loads a value from the location in the given value.
If alignment is not specified, or if zero, the target will choose a default value that is convenient and compatible with the type.
Declaration
Swift
public func buildLoad(_ ptr: IRValue, type: IRType, ordering: AtomicOrdering = .notAtomic, volatile: Bool = false, alignment: Alignment = .zero, name: String = "") -> IRInstructionParameters
ptrThe pointer value to load from.
typeThe type of value loaded from the given pointer.
orderingThe ordering effect of the fence for this load, if any. Defaults to a nonatomic load.
volatileWhether this is a load from a volatile memory location.
alignmentThe alignment of the access.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of a load from the given pointer value.
-
Build a
GEP(Get Element Pointer) instruction with a resultant value that is undefined if the address is outside the actual underlying allocated object and not the address one-past-the-end.The
GEPinstruction is often the source of confusion. LLVM provides a document to answer questions around its semantics and correct usage.Declaration
Parameters
ptrThe base address for the index calculation.
typeThe type used to calculate pointer offsets.
indicesA list of indices that indicate which of the elements of the aggregate object are indexed.
nameThe name for the newly inserted instruction.
Return Value
A value representing the address of a subelement of the given aggregate data structure value.
-
Build a GEP (Get Element Pointer) instruction.
The
GEPinstruction is often the source of confusion. LLVM provides a document to answer questions around its semantics and correct usage.Declaration
Parameters
ptrThe base address for the index calculation.
typeThe type used to calculate pointer offsets.
indicesA list of indices that indicate which of the elements of the aggregate object are indexed.
nameThe name for the newly inserted instruction.
Return Value
A value representing the address of a subelement of the given aggregate data structure value.
-
Build a GEP (Get Element Pointer) instruction suitable for indexing into a struct of a given type.
Declaration
Parameters
ptrThe base address for the index calculation.
typeThe type of the struct to index into.
indexThe offset from the base for the index calculation.
nameThe name for the newly inserted instruction.
Return Value
A value representing the address of a subelement of the given struct value.
-
Build an ExtractValue instruction to retrieve an indexed value from a struct or array value.
extractvaluefunction like a GEP, but has different indexing semantics:Since
Since the value being indexed is not a pointer, the first index is omitted and assumed to be zero.Not only struct indices but also array indices must be in bounds.
Declaration
Parameters
valueThe struct or array you’re indexing into.
indexThe index at which to extract.
Return Value
The value in the struct at the provided index.
-
Build a comparision instruction that returns whether the given operand is
null.Parameters
valThe value to test.
nameThe name for the newly inserted instruction.
Return Value
An
i1value representing the result of a test to see if the value isnull`. -
Build a comparision instruction that returns whether the given operand is not
null.Parameters
valThe value to test.
nameThe name for the newly inserted instruction.
Return Value
An
i1value representing the result of a test to see if the value is notnull`.
-
Build an instruction that either performs a truncation or a bitcast of the given value to a value of the given type.
Declaration
Parameters
valThe value to cast or truncate.
typeThe destination type.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of truncating or bitcasting the given value to fit the given type.
-
Build an instruction that either performs a zero extension or a bitcast of the given value to a value of the given type with a wider width.
Declaration
Parameters
valThe value to zero extend.
typeThe destination type.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of zero extending or bitcasting the given value to fit the given type.
-
Build a bitcast instruction to convert the given value to a value of the given type by just copying the bit pattern.
The
bitcastinstruction is always a no-op cast because no bits change with this conversion. The conversion is done as if the value had been stored to memory and read back as the given type. Pointer (or vector of pointer) types may only be converted to other pointer (or vector of pointer) types with the same address space through this instruction. To convert pointers to other types, seebuildIntToPtr(_:type:name:)orbuildPtrToInt(_:type:name:).Declaration
Parameters
valThe value to bitcast.
typeThe destination type.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of bitcasting the given value to fit the given type.
-
Build a cast instruction to convert the given floating-point value to a value of the given type.
Declaration
Parameters
valThe value to cast.
typeThe destination type.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of casting the given value to fit the given type.
-
Build an address space cast instruction that converts a pointer value to a given type in a different address space.
The
addrspacecastinstruction can be a no-op cast or a complex value modification, depending on the target and the address space pair. Pointer conversions within the same address space must be performed with thebitcastinstruction. Note that if the address space conversion is legal then both result and operand refer to the same memory location.This instruction must be used in lieu of a
bitcasteven if the cast is between types of the same size.The address spaces of the value and the destination pointer types must be distinct.
-
Build a truncate instruction to truncate the given value to the given type with a shorter width.
Declaration
Parameters
valThe value to truncate.
typeThe destination type.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of truncating the given value to fit the given type.
-
Build a sign extension instruction to sign extend the given value to the given type with a wider width.
Parameters
valThe value to sign extend.
typeThe destination type.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of sign extending the given value to fit the given type.
-
Build a zero extension instruction to zero extend the given value to the given type with a wider width.
Parameters
valThe value to zero extend.
typeThe destination type.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of zero extending the given value to fit the given type.
-
Build an integer-to-pointer instruction to convert the given value to the given pointer type.
The
inttoptrinstruction converts the given value to the given pointer type by applying either a zero extension or a truncation depending on the size of the integer value. If value is larger than the size of a pointer then a truncation is done. If value is smaller than the size of a pointer then a zero extension is done. If they are the same size, nothing is done (no-op cast).Declaration
Swift
public func buildIntToPtr(_ val: IRValue, type: PointerType, name: String = "") -> IRValueParameters
valThe integer value.
typeThe destination pointer type.
nameThe name for the newly inserted instruction.
Return Value
A pointer value representing the value of the given integer converted to the given pointer type.
-
Build a pointer-to-integer instruction to convert the given pointer value to the given integer type.
The
ptrtointinstruction converts the given pointer value to the given integer type by interpreting the pointer value as an integer and either truncating or zero extending that value to the size of the integer type. If the pointer value is smaller than the integer type then a zero extension is done. If the pointer value is larger than the integer type then a truncation is done. If they are the same size, then nothing is done (no-op cast) other than a type change.Declaration
Parameters
valThe pointer value.
typeThe destination integer type.
nameThe name for the newly inserted instruction.
Return Value
An integer value representing the value of the given pointer converted to the given integer type.
-
Build an integer-to-floating instruction to convert the given integer value to the given floating type.
Declaration
Parameters
valThe integer value.
typeThe destination integer type.
signedWhether the destination is a signed or unsigned integer.
nameThe name for the newly inserted instruction.
Return Value
A floating value representing the value of the given integer converted to the given floating type.
-
Build a floating-to-integer instruction to convert the given floating value to the given integer type.
Declaration
Parameters
valThe floating value.
typeThe destination integer type.
signedWhether the destination is a signed or unsigned integer.
nameThe name for the newly inserted instruction.
Return Value
An integer value representing the value of the given float converted to the given integer type.
-
Build an expression that returns the difference between two pointer values, dividing out the size of the pointed-to objects.
This is intended to implement C-style pointer subtraction. As such, the pointers must be appropriately aligned for their element types and pointing into the same object.
Declaration
Parameters
lhsThe first pointer (the minuend).
rhsThe second pointer (the subtrahend).
nameThe name for the newly inserted instruction.
Return Value
A IRValue representing a 64-bit integer value of the difference of the two pointer values modulo the size of the pointed-to objects.
-
Build a fence instruction that introduces “happens-before” edges between operations.
A fence
Awhich has (at least)releaseordering semantics synchronizes with a fenceBwith (at least)acquireordering semantics if and only if there exist atomic operations X and Y, both operating on some atomic objectM, such thatAis sequenced beforeX,XmodifiesM(either directly or through some side effect of a sequence headed byX),Yis sequenced beforeB, andYobservesM. This provides a happens-before dependency betweenAandB. Rather than an explicit fence, one (but not both) of the atomic operationsXorYmight provide a release or acquire (resp.) ordering constraint and still synchronize-with the explicit fence and establish the happens-before edge.A fence which has
sequentiallyConsistentordering, in addition to having bothacquireandreleasesemantics specified above, participates in the global program order of othersequentiallyConsistentoperations and/or fences.Declaration
Swift
@discardableResult public func buildFence(ordering: AtomicOrdering, singleThreaded: Bool = false, name: String = "") -> IRInstructionParameters
orderingDefines the kind of “synchronizes-with” edge this fence adds.
singleThreadedSpecifies that the fence only synchronizes with other atomics in the same thread. (This is useful for interacting with signal handlers.) Otherwise this fence is atomic with respect to all other code in the system.
nameThe name for the newly inserted instruction.
Return Value
A value representing
void. -
Build an atomic compare-and-exchange instruction to atomically modify memory. It loads a value in memory and compares it to a given value. If they are equal, it tries to store a new value into the memory.
Declaration
Swift
public func buildAtomicCmpXchg( ptr: IRValue, of old: IRValue, to new: IRValue, successOrdering: AtomicOrdering, failureOrdering: AtomicOrdering, singleThreaded: Bool = false ) -> IRValueParameters
ptrThe address of data to update atomically.
oldThe value to base the comparison on.
newThe new value to write if comparison with the old value returns true.
successOrderingSpecifies how this cmpxchg synchronizes with other atomic operations when it succeeds.
failureOrderingSpecifies how this cmpxchg synchronizes with other atomic operations when it fails.
singleThreadedSpecifies that this cmpxchg only synchronizes with other atomics in the same thread. (This is useful for interacting with signal handlers.) Otherwise this cmpxchg is atomic with respect to all other code in the system.
Return Value
A value representing the original value at the given location is together with a flag indicating success (true) or failure (false).
-
Build an atomic read-modify-write instruction to atomically modify memory.
Declaration
Swift
public func buildAtomicRMW( atomicOp: AtomicReadModifyWriteOperation, ptr: IRValue, value: IRValue, ordering: AtomicOrdering, singleThreaded: Bool = false ) -> IRValueParameters
atomicOpThe atomic operation to perform.
ptrThe address of a value to modify.
valueThe second argument to the given operation.
orderingDefines the kind of “synchronizes-with” edge this atomic operation adds.
singleThreadedSpecifies that this atomicRMW instruction only synchronizes with other atomics in the same thread. (This is useful for interacting with signal handlers.) Otherwise this atomicRMW is atomic with respect to all other code in the system.
Return Value
A value representing the old value of the given pointer before the atomic operation was executed.
-
Build a call to the C standard library
mallocinstruction.(type *)malloc(sizeof(type));If
countis provided, it is equivalent to:(type *)malloc(sizeof(type) * count);Declaration
Swift
public func buildMalloc(_ type: IRType, count: IRValue? = nil, name: String = "") -> IRInstructionParameters
typeThe intended result type being allocated. The result of the
mallocwill be a pointer to this type.countAn optional number of slots to allocate, to simulate a C array.
nameThe intended name for the
malloc‘d value. -
Build a call to the C standard library
freefunction, with the provided pointer.Declaration
Swift
@discardableResult public func buildFree(_ ptr: IRValue) -> IRInstructionParameters
ptrThe pointer to
free.Return Value
The
freeinstruction.
-
Builds a call to the
llvm.memset.*family of intrinsics to fill a given block of memory with a given byte value.Note
Unlike the standard function
memsetdefined in libc,llvm.memsetdoes not return a value and may be volatile. The address space of the source and destination values need not match.Declaration
Swift
@discardableResult public func buildMemset( to dest: IRValue, of value: IRValue, length: IRValue, alignment: Alignment, volatile: Bool = false ) -> IRInstructionParameters
destA pointer value to the destination that will be filled.
valueA byte value to fill the destination with.
lengthThe number of bytes to fill.
alignmentThe alignment of the destination pointer value.
volatileIf true, builds a volatile
llvm.memsetintrinsic, else builds a non-volatilellvm.memsetinstrinsic. The exact behavior of volatile memory intrinsics is platform-dependent and should not be relied upon to perform consistently. For more information, see the language reference’s section on Volatile Memory Access. -
Builds a call to the
llvm.memcpy.*family of intrinsics to copy a block of memory to a given destination memory location from a given source memory location.Warning
It is illegal for the destination and source locations to overlap each other.
Note
Unlike the standard function
memcpydefined in libc,llvm.memcpydoes not return a value and may be volatile. The address space of the source and destination values need not match.Declaration
Parameters
destA pointer to the destination that will be filled.
destAlignThe alignment of the destination pointer value.
srcA pointer to the source that will be copied from.
srcAlignThe alignment of the source pointer value.
lengthThe number of bytes to fill.
volatileIf true, builds a volatile
llvm.memcpyintrinsic, else builds a non-volatilellvm.memcpyinstrinsic. The exact behavior of volatile memory intrinsics is platform-dependent and should not be relied upon to perform consistently. For more information, see the language reference’s section on Volatile Memory Access. -
Builds a call to the
llvm.memmove.*family of intrinsics to move a block of memory to a given destination memory location from a given source memory location.Unlike
llvm.memcpy.*, the destination and source memory locations may overlap with each other.Note
Unlike the standard function
memmovedefined in libc,llvm.memmovedoes not return a value and may be volatile. The address space of the source and destination values need not match.Declaration
Parameters
destA pointer to the destination that will be filled.
destAlignThe alignment of the destination pointer value.
srcA pointer to the source that will be copied from.
srcAlignThe alignment of the source pointer value.
lengthThe number of bytes to fill.
volatileIf true, builds a volatile
llvm.memmoveintrinsic, else builds a non-volatilellvm.memmoveinstrinsic. The exact behavior of volatile memory intrinsics is platform-dependent and should not be relied upon to perform consistently. For more information, see the language reference’s section on Volatile Memory Access.
-
Build an instruction to insert a value into a member field in an aggregate value.
Declaration
Parameters
aggregateA value of array or structure type.
elementThe value to insert.
indexThe index at which at which to insert the value.
nameThe name for the newly inserted instruction.
Return Value
A value representing an aggregate that has been updated with the given value at the given index.
-
Build an instruction to extract a value from a member field in an aggregate value.
An
extract valueinstruction differs from aget element pointerinstruction because the value being indexed is not a pointer and the first index is unnecessary (as it is assumed to be zero).Declaration
Parameters
aggregateA value of array or structure type.
indexThe index at which at which to extract a value.
nameThe name for the newly inserted instruction.
Return Value
A value representing an aggregate that has been updated with the given value at the given index.
-
Build a vector insert instruction to nondestructively insert the given value into the given vector.
Declaration
Parameters
vectorA value of vector type.
elementThe value to insert.
indexThe index at which to insert the value.
nameThe name for the newly inserted instruction.
Return Value
A value representing a vector that has been updated with the given value at the given index.
-
Build an instruction to extract a single scalar element from a vector at a specified index.
Declaration
Parameters
vectorA value of vector type.
indexThe index at which to insert the value.
nameThe name for the newly inserted instruction.
Return Value
A value representing a scalar at the given index.
-
Build a vector shuffle instruction to construct a permutation of elements from the two given input vectors, returning a vector with the same element type as the inputs and length that is the same as the shuffle mask.
The elements of the two input vectors are numbered from left to right across both of the vectors. The shuffle mask operand specifies, for each element of the result vector, which element of the two input vectors the result element gets. If the shuffle mask is
undef, the result vector is alsoundef. If any element of the mask operand isundef, that element of the result isundef. If the shuffle mask selects anundefelement from one of the input vectors, the resulting element isundef.Declaration
Parameters
vector1The first vector to shuffle.
vector2The second vector to shuffle.
maskA constant vector of
i32values that acts as a mask for the shuffled vectors.Return Value
A value representing a vector with the same element type as the inputs and length that is the same as the shuffle mask.
-
Build a named global of the given type.
Declaration
Swift
public func addGlobal(_ name: String, type: IRType, addressSpace: AddressSpace = .zero) -> GlobalParameters
nameThe name of the newly inserted global value.
typeThe type of the newly inserted global value.
addressSpaceThe optional address space where the global variable resides.
Return Value
A value representing the newly inserted global variable.
-
Build a named global of the given type.
Declaration
Swift
public func addGlobal(_ name: String, initializer: IRValue, addressSpace: AddressSpace = .zero) -> GlobalParameters
nameThe name of the newly inserted global value.
initializerThe initial value for the global variable.
addressSpaceThe optional address space where the global variable resides.
Return Value
A value representing the newly inserted global variable.
-
Build a named global string consisting of an array of
i8type filled in with the nul terminated string value.Declaration
Swift
public func addGlobalString(name: String, value: String) -> GlobalParameters
nameThe name of the newly inserted global string value.
valueThe character contents of the newly inserted global.
Return Value
A value representing the newly inserted global string variable.
-
Build a named global variable containing the characters of the given string value as an array of
i8type filled in with the nul terminated string value.Declaration
Swift
public func buildGlobalString(_ string: String, name: String = "") -> GlobalParameters
stringThe character contents of the newly inserted global.
nameThe name for the newly inserted instruction.
Return Value
A value representing the newly inserted global string variable.
-
Build a named global variable containing a pointer to the contents of the given string value.
Declaration
Swift
public func buildGlobalStringPtr(_ string: String, name: String = "") -> IRValueParameters
stringThe character contents of the newly inserted global.
nameThe name for the newly inserted instruction.
Return Value
A value representing a pointer to the newly inserted global string variable.
-
Build a named alias to a global value or a constant expression.
Aliases, unlike function or variables, don’t create any new data. They are just a new symbol and metadata for an existing position.
Parameters
nameThe name of the newly inserted alias.
aliaseeThe value or constant to alias.
typeThe type of the aliased value or expression.
Return Value
A value representing the newly created alias.
-
Build a value representing an inline assembly expression (as opposed to module-level inline assembly).
LLVM represents inline assembler as a template string (containing the instructions to emit), a list of operand constraints (stored as a string), and some flags.
The template string supports argument substitution of the operands using “$” followed by a number, to indicate substitution of the given register/memory location, as specified by the constraint string. “${NUM:MODIFIER}” may also be used, where MODIFIER is a target-specific annotation for how to print the operand (see Asm Template Argument Modifiers).
LLVM’s support for inline asm is modeled closely on the requirements of Clang’s GCC-compatible inline-asm support. Thus, the feature-set and the constraint and modifier codes are similar or identical to those in GCC’s inline asm support.
However, the syntax of the template and constraint strings is not the same as the syntax accepted by GCC and Clang, and, while most constraint letters are passed through as-is by Clang, some get translated to other codes when converting from the C source to the LLVM assembly.
Declaration
Swift
public func buildInlineAssembly( _ asm: String, dialect: InlineAssemblyDialect, type: FunctionType, constraints: String = "", hasSideEffects: Bool = true, needsAlignedStack: Bool = true ) -> IRValueParameters
asmThe inline assembly expression template string.
typeThe type of the parameters and return value of the assembly expression string.
constraintsA comma-separated string, each element containing one or more constraint codes.
hasSideEffectsWhether this inline asm expression has side effects. Defaults to
false.needsAlignedStackWhether the function containing the asm needs to align its stack conservatively. Defaults to
true.Return Value
A representation of the newly created inline assembly expression.
-
Build a load instruction that loads a value from the location in the given value.
If alignment is not specified, or if zero, the target will choose a default value that is convenient and compatible with the type.
Declaration
Swift
@available(*, deprecated, message: "Use buildLoad(_:type:ordering:volatile:alignment:name﹚ instead") public func buildLoad(_ ptr: IRValue, ordering: AtomicOrdering = .notAtomic, volatile: Bool = false, alignment: Alignment = .zero, name: String = "") -> IRInstructionParameters
ptrThe pointer value to load from.
orderingThe ordering effect of the fence for this load, if any. Defaults to a nonatomic load.
volatileWhether this is a load from a volatile memory location.
alignmentThe alignment of the access.
nameThe name for the newly inserted instruction.
Return Value
A value representing the result of a load from the given pointer value.
-
Build a GEP (Get Element Pointer) instruction suitable for indexing into a struct.
Declaration
Parameters
ptrThe base address for the index calculation.
indexThe offset from the base for the index calculation.
nameThe name for the newly inserted instruction.
Return Value
A value representing the address of a subelement of the given struct value.
-
Build a GEP (Get Element Pointer) instruction.
The
GEPinstruction is often the source of confusion. LLVM provides a document to answer questions around its semantics and correct usage.Declaration
Parameters
ptrThe base address for the index calculation.
indicesA list of indices that indicate which of the elements of the aggregate object are indexed.
nameThe name for the newly inserted instruction.
Return Value
A value representing the address of a subelement of the given aggregate data structure value.
-
Build a
GEP(Get Element Pointer) instruction with a resultant value that is undefined if the address is outside the actual underlying allocated object and not the address one-past-the-end.The
GEPinstruction is often the source of confusion. LLVM provides a document to answer questions around its semantics and correct usage.Declaration
Parameters
ptrThe base address for the index calculation.
indicesA list of indices that indicate which of the elements of the aggregate object are indexed.
nameThe name for the newly inserted instruction.
Return Value
A value representing the address of a subelement of the given aggregate data structure value.
IRBuilder Class Reference