Fee
Fee

Reputation: 851

LLVM insert if/else into existing basic block

I want to check the value of some instruction at runtime. Therefore, I create a compare instruction and a branch instruction which branches to either the "then" basic block or the "else" basic block. However, I am not sure how I can insert the created basic block after the conditional branch and how the splitting of the existing basic block works.

Instruction* someInst;
IRBuilder<> B(someInst);

Value* condition = B.CreateICmp(CmpInst::ICMP_UGT, someInst, someValue);

BasicBlock* thenBB = BasicBlock::Create(*ctx, "then");
BasicBlock* elseBB = BasicBlock::Create(*ctx, "else");

B.CreateCondBr(condition, thenBB, elseBB);

B.SetInsertPoint(thenBB);
//insert stuff

B.SetInsertPoint(elseBB);
//insert stuff

How can I insert an if/else in the middle of an existing basic block?

Upvotes: 4

Views: 6886

Answers (2)

Alan Green
Alan Green

Reputation: 124

Short answer: you can probably use llvm::SplitBlockAndInsertIfThenElse. Don't forget your PHI node.

According to Wikipedia, a basic block:

is a straight-line code sequence with no branches in except to the entry and no branches out except at the exit.

An if-then-else therefore involves several blocks:

  1. The block that contains the condition,
  2. The then block
  3. The else block
  4. Optionally, the block after the then and else blocks (if then and else don't return or branch elsewhere).

To insert an if-then-else, the original Basic Block must be split into (1) and (4). The condition checking and conditional branching go into (1), and (2) and (3) finish with a branch to (4). The SplitBlockAndInsertIfThenElse function (docs) will do this for you in simple cases. If you have more complicated requirements - such as then or else containing their own control flow - you may need to do the splitting yourself.

If your then or else blocks modify variables, you will need a PHI node. The Kaleidoscope tutorial explains why PHI nodes are needed and how to use them. The tutorial references the Single Static Assignment Wikipedia article, which is useful background.

Upvotes: 5

Ismail Badawi
Ismail Badawi

Reputation: 37177

There is a helper function you can use called llvm::SplitBlockAndInsertIfThenElse. You'll need to #include "llvm/Transforms/Utils/BasicBlockUtils.h".

Upvotes: 2

Related Questions