How to create a new llvm BasicBlock and insert after the other Block?

Viewed 1944

I am writing some codes to insert some Instructions in a llvm BasicBlock,and I need to create a new BasicBlock to insert after a block,I have tried

LLVM::BasicBlock b=LLVM::BasicBlock()

But I don't know what parameters should be written inLLVM::BasicBlock,and I don't know how to name the BasicBlock

So could you help me to create a new llvm BasicBlock and insert it after the other Block?

1 Answers

In llvm hierarchy, instructions are associated with a basic block, basic blocks associated with a function, and functions with a module. To create a basic block,

BasicBlock* mainblock = BasicBlock::Create(context, "entrypoint", mainFunction); 

Where entrypoint is the name of block and mainfunction is the function containing the block (which you should have already declared of course).

Emitting instructions in llvm is achieved with an instance of the IRBuilder<> class whose constructor takes an llvm::LLVMContext instance. i.e

llvm::LLVMContext context;
IRBuilder<> builder(context);

This builder instance is like your pen for emitting llvm ir. To place the tip of the pen in a particular page i.e specify in which basic block it emits, just call

builder.SetInsertPoint(mainblock);

Where mainblock is the basic block we want to write to. Henceforth all calls to builder will emit instructions in this block.

Related