1
bool runOnFunction(Function &F) override {
  outs() << "Inside Function: "<<F.getName()<<"\n";
  int i = 0;
  map<int, Instruction*> work;
  for(BasicBlock &BB : F)
      for(Instruction &I : BB){
          if(i == 15)
              work.insert({i, &I});
          i++;
      }

  std::map<int, Instruction*>::iterator it = work.begin();
  it->second->eraseFromParent();

  return true;
}

The above is my code snippet. Here, in the above code, I would like to remove an instruction randomly.. just for the sake of knowing how to use this api. But, It is ending up with segmentation fault!!, no matter what I try. Need some guidance, here please

Inside Function: change_g
While deleting: i32 %
Use still stuck around after Def is destroyed:  %add = add nsw i32 <badref>, %l
opt: /home/user/llvm-project/llvm/lib/IR/Value.cpp:103: llvm::Value::~Value(): Assertion `materialized_use_empty() && "Uses remain when a value is destroyed!"' failed.
yugr
  • 19,769
  • 3
  • 51
  • 96
  • @yugr is right. There's a chance that you wanted to call [removeFromParent()](https://llvm.org/doxygen/classllvm_1_1Instruction.html#a0fd53f63d349dc8a7c5fc0cdd7a94c8d) though, if you just wanted to experiment. (And call [verifyFunction()](https://llvm.org/doxygen/namespacellvm.html#a26389c546573f058ad8ecbdc5c1933cf) too to learn about any accidental mistakes.) – arnt Feb 07 '22 at 11:03

1 Answers1

2

First of all, it's not a segmentation fault but an assertion which tells you that something went wrong. In particular the message explains that you can not erase an instruction until any of its uses is still present in function.

Usually you'd first create a new instruction, replace all uses of to-be-removed instruction with new result (via Value::replaceAllUsesWith()) and only then erase.

yugr
  • 19,769
  • 3
  • 51
  • 96
  • So suppose if I wanna do arithmetic identity optimization i.e x=x+0; to be removed. What should i do with replaceAllUsesWith for the uses of this particular + operator?? – Abilesh Sundarasamy Feb 07 '22 at 13:08
  • You won't have `x = x + 0` in SSA representation like LLVM IR. You'll have `x1 = x2 + 0` instead. In that case you'll `replaceAllUsesWith(x1, x2)` to get rid of `x1` uses and then remove the instruction. – yugr Feb 07 '22 at 13:37
  • @AbileshSundarasamy you are welcome. If the answer is ok, you can consider accepting it. – yugr Feb 07 '22 at 15:09