'eraseFromParent() Error

I'm trying to delete some instructions in IR. For analysis purpose, these instructions are inserted before, and now I need to delete them.

  BasicBlock::reverse_iterator I = (*b).rbegin();
  BasicBlock::reverse_iterator Ie = (*b).rend();
  int i=0;
  for ( ; I != Ie;I++)
    {
     if(i>0&&i<4){
       errs()<<" Instruction "<<*I<<"\n";
       I->eraseFromParent();
       i++;
    }
     else{
       i++;
     }
   }

This code is used in Transformation pass. When I run it, the output error are:

       #0 0x00000000032bff15 (opt+0x32bff15)
       #1 0x00000000032bffa6 (opt+0x32bffa6)
       #2 0x00000000032be43e (opt+0x32be43e)
       #3 0x00000000032bf8ac (opt+0x32bf8ac)
       #4 0x00007f26cfa81330 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x10330)
       #5 0x00007f26ce81a89a   llvm::PointerIntPair<llvm::ilist_node_base<true>*, 1u, unsigned int, llvm::PointerLikeTypeTraits<llvm::ilist_node_base<true>*>, llvm::PointerIntPairInfo<llvm::ilist_node_base<true>*, 1u, llvm::PointerLikeTypeTraits<llvm::ilist_node_base<true>*> > >::getInt() const /home/rasha/llvm/llvm/include/llvm/ADT/PointerIntPair.h:59:0
       #6 0x00007f26ce813516 llvm::ilist_node_base<true>::isSentinel() const /home/rasha/llvm/llvm/include/llvm/ADT/ilist_node_base.h:46:0
       #7 0x00007f26ce813536 llvm::ilist_node_base<true>::isKnownSentinel() const /home/rasha/llvm/llvm/include/llvm/ADT/ilist_node_base.h:47:0
       #8 0x00007f 26ce81e1d9 llvm::ilist_iterator<llvm::ilist_detail::node_options<llvm::Instruction, true, false, void>, true, false>::operator*() const /home/rasha/llvm/llvm/include/llvm/ADT/ilist_iterator.h:139:0
       #9 0x00007f26ce812d6f (anonymous namespace)::BBRemove::runOnModule(llvm::Module&) /home/rasha/llvm/llvm/lib/Transforms/BBRemove/BBRemove.cpp:79:0
       #10 0x0000000002c4a2dc (opt+0x2c4a2dc)
       #11 0x0000000002c4aa2c (opt+0x2c4aa2c)
       #12 0x0000000002c4ac6d (opt+0x2c4ac6d)
       #13 0x0000000001512cd4 (opt+0x1512cd4)
       #14 0x00007f26cea6cf45 __libc_start_main /build/eglibc-ripdx6/eglibc-2.19/csu/libc-start.c:321:0
       #15 0x00000000014f7a19 (opt+0x14f7a19)
       Stack dump:

This error is issued after the first call of eraseFromParent.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source