Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erasing a first Instruction in Basic Block from LLVM IR?

Tags:

llvm

I have the followint LLVM IR file

  %1 = load i32* %i, align 4
  %2 = load i32* %j, align 4
  %3 = icmp sgt i32 %1, %2
  br i1 %3, label %4, label %6

; <label>:4                                       ; preds = %0
  %5 = load i32* %i, align 4
  store i32 %5, i32* %k, align 4
  br label %6

; <label>:6                                       ; preds = %5, %0
  ret i32 0

In it I am first loading vairable "i" in %1 and variable "j" in %2 then I am comparing the greater than condition that is (i>j). Based on that there is branch either to label 4 or label 6. My problem is that there are two load instruction for variable "i" one in first basic block and other in 2nd basic block. Here I want to remove 2nd load instruction. For it I am doing it as when I reach to 2nd load instruction for variable "i" I am replacing all uses of 2nd instruction by first instruction then I am erasing the current instruction i.e. 2nd. Here I am unable to set instruction iterator pointer. I do not want to set for next instruction(store i32 %5, i32* %k, align 4). Is there a other way? If you know please let me know.

like image 623
damrudhard Avatar asked Mar 14 '12 02:03

damrudhard


1 Answers

If I understand you correctly, all you want is just to erase an instruction and keep iterating over the code. If that's right, take a look at this example from the DeadInstElimintation pass (which lives in lib/Transforms/Scalar/DCE.cpp):

virtual bool runOnBasicBlock(BasicBlock &BB) {
  bool Changed = false;
  for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) {
    Instruction *Inst = DI++;
    if (isInstructionTriviallyDead(Inst)) {
      Inst->eraseFromParent();
      Changed = true;
      ++DIEEliminated;
    }
  }
  return Changed;
}

The interesting thing to note is how the iterator is incremented. The DI++ is not done inside the last clause of the for, but rather separately, with the current DI assigned to Inst. This ensures that even if you delete Inst, DI already points to the next instruction so the loop will keep running over the next instructions.

like image 52
Eli Bendersky Avatar answered Sep 28 '22 06:09

Eli Bendersky