IRBuilder

IRBuilder Class is a helper providing an API for LLVM IR generation. Instances of the IRBuilder class keep track of the current place to insert instructions and has member functions to create new instructions.

In order to better understand LLVM’s instructions and their uses, we strongly encourage you to checkout LLVM’s Instruction Reference. For in-depth explanations of the GEP instruction, see The Often Misunderstood GEP Instruction.

Insert points:

// Return pointer to the current Basic Block (attribute of IRBuilderBase class).
BasicBlock* GetInsertBlock() const;

// Insert and return the specified instruction.
InstTy* Insert(InstTy* I, const Twine &Name = "") const;

// Set the current insert point to a previously-saved location.
void restoreIP(InsertPoint IP);

// Return the current insert point.
InsertPoint saveIP() const;

// Specify that created instructions should be appended to the end of the specified block.
void SetInsertPoint(BasicBlock* TheBB);

Instruction creation member functions:

Create instructions:
// Create Instructions.
AllocaInst* CreateAlloca(Type* Ty, Value* ArraySize = nullptr, const Twine &Name = "");

CallInst* CreateMalloc(Type* IntPtrTy, Type* AllocTy, Value* AllocSize, Value* ArraySize, Function* MallocF = nullptr, const Twine &Name = "");

CallInst* CreateCall(FunctionCallee Callee, ArrayRef<Value* > Args = {}, const Twine &Name = "", MDNode* FPMathTag = nullptr);

BranchInst* CreateBr(BasicBlock* Dest);

BranchInst* CreateCondBr(Value* Cond, BasicBlock* True, BasicBlock* False, MDNode* BranchWeights = nullptr, MDNode* Unpredictable = nullptr);

LoadInst* CreateLoad(Type* Ty, Value* Ptr, const char* Name);

ReturnInst* CreateRet(Value* V);

ReturnInst* CreateRetVoid();

StoreInst* CreateStore(Value* Val, Value* Ptr, bool isVolatile = false);

llvm::IRBuilderBase::CreateAlloca

Create a memory allocation on the stack.

AllocaInst* CreateAlloca(Type* Ty,
                         Value* ArraySize = nullptr,
                         const Twine &Name = "");
Parameters:
  • Ty: This parameter specifies the type of the allocated memory.

  • ArraySize: This is an optional parameter that specifies the size of the array to be allocated. If you’re allocating memory for a single variable, you can pass nullptr or omit this parameter.

  • Name: This is an optional parameter that specifies the name of the alloca instruction.

llvm::IRBuilderBase::CreateMalloc

Create a malloc function call on the heap.
  • Compute the malloc call’s argument as the specified type’s size, possibly multiplied by the array size if the array size is not constant 1.

  • Call malloc with that argument.

CallInst* CreateMalloc(Type* IntPtrTy,
                       Type* AllocTy,
                       Value* AllocSize,
                       Value* ArraySize,
                       Function* MallocF = nullptr,
                       const Twine &Name = "");
Parameters:
  • IntPtrTy: This parameter specifies the type of the returned pointer tp allocated memory.

  • AllocTy: This parameter specifies the type of the allocated memory.

  • AllocSize: This parameter specifies the size of the value to be allocated.

  • ArraySize: This is an optional parameter that specifies the size of the array to be allocated. If you’re allocating memory for a single variable, you can pass nullptr.

  • MallocF: This is an optional parameter that specifies the malloc function to call.

  • Name: This is an optional parameter that specifies the name of the malloc instruction.

llvm::IRBuilderBase::CreateCall

Create a function call with or without arguments.

CallInst* CreateCall(FunctionCallee Callee,
                     ArrayRef<Value* > Args = {},
                     const Twine &Name = "",
                     MDNode* FPMathTag = nullptr);
Parameters:
  • Callee: This parameter specifies the function callee, which can be either a Function or a Value that represents a function pointer.

  • Args: This parameter specifies the arguments to be passed to the function call as an array of Value pointers.

  • Name: This is an optional parameter that specifies the name of the call instruction.

  • FPMathTag: This is an optional parameter that allows you to specify an optional metadata node for the call instruction, which can be used to attach additional information.

llvm::IRBuilderBase::CreateBr

Create a branching (jump) to another location (basic block).

Note

A basic block in LLVM IR is a sequence of instructions that are executed in a sequential order. A basic block ends with the first jump, whether conditional or not.

The CreateBr method allows you to create a basic block jump instruction with the provided destination basic block.

BranchInst* CreateBr(BasicBlock* Dest);
Parameters:
  • Dest: This parameter specifies the destination basic block to which the unconditional branch should jump.

llvm::IRBuilderBase::CreateCondBr

Create a conditional branching (jump conditionally) to another location (basic block), depending on the tested condition value.

BranchInst* CreateCondBr(Value* Cond,
                         BasicBlock* True,
                         BasicBlock* False,
                         MDNode* BranchWeights = nullptr,
                         MDNode* Unpredictable = nullptr);
Parameters:
  • Cond: This parameter specifies the condition value that determines whether the branch should take the true or false path. You can pass a pointer to a Value object, which represents a value in LLVM IR, as the condition for the branch instruction.

  • True: This parameter specifies the destination basic block to which the branch should jump if the condition is true.

  • False: This parameter specifies the destination basic block to which the branch should jump if the condition is false.

  • BranchWeights: This parameter is an optional metadata node that represents the branch weights for profile-guided optimization (PGO) purposes.

  • Unpredictable: This parameter is an optional metadata node that represents that the branch is considered unpredictable or hard to predict by the optimizer.

llvm::IRBuilderBase::LoadInst

Create a value load from memory.

LoadInst* CreateLoad(Type* Ty,
                     Value* Ptr,
                     const char* Name);
Parameters:
  • Ty: This parameter specifies the type of the structure whose member’s address you want to calculate.

  • Ptr: This parameter specifies the memory location from which the value should be loaded.

  • Name: This parameter is an optional string that specifies the name of the resulting load instruction.

llvm::IRBuilderBase::ReturnInst

Create a return value from a function.

ReturnInst* CreateRet(Value* V);
Parameters:
  • V: This parameter specifies the value that should be returned from the function.

llvm::IRBuilderBase::ReturnVoid

Create a void return from a function (return nothing).

ReturnInst* CreateRetVoid();

llvm::IRBuilderBase::StoreInst

Create a value store to memory.

StoreInst* CreateStore(Value* Val,
                       Value* Ptr,
                       bool isVolatile = false);
Parameters:
  • Val: This parameter specifies the value that should be stored to the memory location.

  • Ptr: This parameter specifies the memory location to which the value should be stored.

  • isVolatile: This parameter is an optional boolean flag that indicates whether the store operation should be marked as volatile.

Create Value:
// Create Value.
Value* CreateBitCast(Value* V, Type* DestTy, const Twine &Name = "");

Value* CreateGEP(Type* Ty, Value* Ptr, ArrayRef<Value* > IdxList, const Twine &Name = "", GEPNoWrapFlags NW = GEPNoWrapFlags::none());
Value* CreateStructGEP(Type* Ty, Value* Ptr, unsigned Idx, const Twine &Name = "");

// Create an 'ptrtoint' instruction to preserve type safety when handling
// addresses as integer and vectors of addresses as vectors of integers.
Value* CreatePtrToInt(Value* V, Type* DestTy, const Twine &Name = "");

Value* CreateZExtOrTrunc(Value* V, Type* DestTy, const Twine &Name = "");


Constant* CreateGlobalStringPtr(StringRef Str, const Twine &Name = "", unsigned AddressSpace = 0, Module* M = nullptr);

llvm::IRBuilderBase::CreateBitCast

Create a cast to the provided type, without changing any underlying bit.

Value* CreateBitCast(Value* V,
                     Type* DestTy,
                     const Twine &Name = "");
Parameters:
  • V: This parameter specifies the value to convert.

  • DestTy: This parameter specifies the target type of the conversion.

  • Name: This parameter is an optional string parameter that specifies the name of the created bitcast instruction.

llvm::IRBuilderBase::CreateGEP

Create a get element pointer, i.e safe pointer arithmetics to access an array element at a given index. Multiple indices may be used to access structures in depth or multidimensional arrays, etc.

Value* CreateGEP(Type* Ty,
                 Value* Ptr,
                 ArrayRef<Value* > IdxList,
                 const Twine &Name = "",
                 GEPNoWrapFlags NW = GEPNoWrapFlags::none());
Parameters:
  • Ty: This parameter specifies the type of the structure whose member’s address you want to calculate.

  • Ptr: This parameter specifies the base pointer whose address you want to calculate.

  • IdxList: This parameter specifies the indices for the pointer arithmetic operation.

  • Name: This parameter is an optional string parameter that specifies the name of the created GEP instruction.

  • NW: This parameter is an optional wrap strategy that can be used to optimize address computation with overflow checking.

llvm::IRBuilderBase::CreateStructGEP

Create a get structure element pointer, i.e safe pointer arithmetics to access a structure element, at a given index and according to its type.

Value* CreateStructGEP(Type* Ty,
                       Value* Ptr,
                       unsigned Idx,
                       const Twine &Name = "");
Parameters:
  • Ty: This parameter specifies the type of the structure whose member’s address you want to calculate.

  • Ptr: This parameter specifies the base pointer whose address you want to calculate.

  • Idx: This parameter specifies the index of the member whose address you want to calculate.

  • Name: This parameter is an optional string parameter that specifies the name of the created GEP instruction.

llvm::IRBuilderBase::CreatePtrToInt

Create an ptrtoint instruction to preserve type safety when handling addresses as integers and vectors of addresses as vectors of integers.

Value* CreatePtrToInt(Value* V,
                      Type* DestTy,
                      const Twine &Name = "");
Parameters:
  • V: This parameter specifies the value that you want to convert from a pointer to an integer.

  • DestTy: This parameter specifies the target type for the integer value that will be produced as the result of the conversion.

  • Name: This parameter is an optional string parameter that specifies

    the name of the created ptrtoint instruction.

llvm::IRBuilderBase::CreateZExtOrTrunc

Create an extended or truncated value according to the provided type.

Value* CreateZExtOrTrunc(Value* V,
                         Type* DestTy,
                         const Twine &Name = "");
Parameters:
  • V: This parameter specifies the value that you want to extend or truncate.

  • DestTy: This parameter specifies the target type for the result of the operation.

  • Name: This parameter is an optional string parameter that specifies the name of the extension/truncation instruction.

llvm::IRBuilderBase::CreateGlobalStringPtr

Constant* CreateGlobalStringPtr(StringRef Str,
                                const Twine &Name = "",
                                unsigned AddressSpace = 0,
                                Module* M = nullptr);
Parameters:
  • Str: This parameter specifies the string value to be created.

  • Name: This parameter is an optional string parameter that specifies the name of the global string pointer creation.

  • AddressSpace: This parameter specifies the address space to be used for the global string.

  • M: This parameter is an optional pointer to a Module object that represents the LLVM module in which the global string should be created & stored.

Create PHINode:

A phi node is used to represent a value that depends on the incoming values from multiple predecessor basic blocks in a control flow graph (CFG). It is often used in the context of representing variables that have different values depending on which path of execution was taken in a program with branches or loops.

Note

Phi node are used in a Static Single Assignment (SSA) context to maintain the ‘uniquely assigned’ constraint, while resolving different paths in the control flow (e.g. conditional constructs).

For a better understanding on how phi nodes work and how they should be used, you can take a look here.

llvm::IRBuilderBase::CreatePHI

Create a phi node with a provided number of incoming values.

PHINode* CreatePHI(Type* Ty,
                   unsigned NumReservedValues,
                   const Twine &Name = "");
Parameters:
  • Ty: This parameter specifies the type of the value that the phi node will represent.

  • NumReservedValues: This parameter specifies the number of incoming values that the phi node will have.

  • Name: This parameter is an optional string parameter that specifies the name.

llvm::PHINode::addIncoming

Add an incoming value and its associated basic block to the phi node.

void llvm::PHINode::addIncoming(Value* V,
                                BasicBlock* BB);
Parameters:
  • V: This parameter specifies the value that should be returned

  • BB: This parameter specifies he incoming basic block that leads to the returned value.

Comparison operators:

Create a comparison operation that holds the result of the values comparison.

// Comparisons.
Value* CreateICmpEQ(Value* LHS, Value* RHS, const Twine &Name = "");
Value* CreateICmpNE(Value* LHS, Value* RHS, const Twine &Name = "");
Value* CreateICmpSLT(Value* LHS, Value* RHS, const Twine &Name = "");
Value* CreateICmpSLE(Value* LHS, Value* RHS, const Twine &Name = "");
Value* CreateICmpSGT(Value* LHS, Value* RHS, const Twine &Name = "");
Value* CreateICmpSGE(Value* LHS, Value* RHS, const Twine &Name = "");
Parameters:
  • LHS: A pointer to a Value object that represents the left-hand side of the comparison.

  • RHS: A pointer to a Value object that represents the right-hand side of the comparison.

  • Name: An optional Twine object that specifies the name of the comparison.

Arithmetics operators:

Create a arithmetic operation that holds the result of the values computation.

// Binary operations.
Value* CreateAdd(Value* LHS, Value* RHS, const Twine &Name = "", bool HasNUW = false, bool HasNSW = false);
Value* CreateMul(Value* LHS, Value* RHS, const Twine &Name = "", bool HasNUW = false, bool HasNSW = false);
Value* CreateSub(Value* LHS, Value* RHS, const Twine &Name = "", bool asNUW = false, bool HasNSW = false);
Value* CreateSDiv(Value* LHS, Value* RHS, const Twine &Name = "", bool isExact = false);
Parameters:
  • LHS: A pointer to a Value object that represents the left-hand side of the arithmetic operation.

  • RHS: A pointer to a Value object that represents the right-hand side of the arithmetic operation.

  • Name: An optional Twine object that specifies the name of the arithmetic operation.

  • HasNUW: An optional boolean value that indicates whether the addition operation has no unsigned wrap-around (guaranteed not to overflow).

  • HasNSW: An optional boolean value that indicates whether the addition operation has no signed wrap-around (guaranteed not to overflow).

  • isExact: An optional boolean value that indicates whether the signed division operation should be performed with exact semantic.