如何将PHI节点添加到每个基本块的开头

How to add PHI node to the beginning of each basicblock

我想为每个有多个前驱的基本块添加一个 phi 节点。比如在store前加一个phi节点。我对 llvm IR 很陌生,我知道有一些像 replaceAllUsesWith() 这样的函数调用可以用来做类似的事情。但我不知道我究竟该如何使用它。非常感谢任何帮助!

 <label>:7:                                      ; preds = %6, %0
 store i32 999, i32* %3, align 4
 ret i32 0

将 phi 节点添加到基本块的开头非常简单:Find the first instruction and create a phi node before that instruction. That creates a new phi after any existing phis, but before any "real" instructions. It'll fail of the basic block is empty, which I presume it isn't in your case. You have to call addIncomingValue() 视情况而定。

我想您随后会想在该块中使用 phi。您可以遍历 BasicBlock::getInstList() and check each instruction using getNumOperands() and getOperand(), and change the relevant instruction operands using setOperand()。这就是 replaceAllUsesOf() 所做的,只是它替换了所有用途,甚至是您的 phi 和其他块中的用途。