问题
I want to insert a block in between two basic blocks in LLVM. So for example, if a basic block A was jumping to basic block B, I want to insert a basic block C in between them such that A jumps to C and C jumps to B. How can I do that? I do have the basic idea that I need to change the terminating instruction of Basic Block A, such that the target B is replaced by C, but how do I go on adding the new basic block C in between?
回答1:
Yes, you need to change (or replace) the terminating instruction of basic block A - for example, if it's a branch, you can use BranchInst::setSuccessor()
. You then create basic block C and make sure that its terminating instruction jumps to B, which will make it in-between.
All you need to do is to change the terminators' targets - you don't need to rearrange the block order in the memory or anything like that.
However, you must be aware that there are two special instructions you need to worry about - phi nodes and landing pads.
Phi nodes only refer to the block's immediate predecessor. That means that if you insert C between A and B, you must fix all the phi nodes in B by either removing them or making them refer to C instead of A.
If B is a landingpad block (contains a landingpad instruction), it is only legal to jump into it directly from the unwind target of an invoke instruction. If the jump from A to B is through the unwind target, you can't add a basic block in-between unless you make C itself into a landingpad and remove the landingpad from B.
回答2:
There is a function called llvm::splitEdge
. It does exactly what the question asked for.
来源:https://stackoverflow.com/questions/13275577/inserting-a-block-between-two-blocks-in-llvm