Resolved: Segmentation Fault on eraseFromParent() LLVM


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});

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

  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.


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.

If you have better answer, please add a comment about this, thank you!