title: How to keep iterating over data structure after inserting elements into it?
body: <p>In the code snippet below, I insert <code>Instruction</code>'s into the <code>BasicBlock</code> pointed to by <code>Function::iterator bs</code>. The inner loop iterates over the instructions contained within this <code>BasicBlock</code>. </p>
  
  <p>Now, after the inner loop inserts these instructions, the program goes into an infinite loop with instruction sequence:</p>
  
  <pre><code>and
  mul
  xor
  and
  mul
  xor
  and
  mul
  xor
  and
  mul
  xor
  and
  mul
  xor
  and
  mul 
  ...
  </code></pre>
  
  <p>How would I insert into the data structure being iterated over, while avoiding going into an infinite loop?</p>
  
  <p>Somehow the iterator goes nuts (or it is invalidated). Is there a common idiom for how to tackle this problem?</p>
  
  <pre><code>for (Function::iterator bs = F.begin(), be = F.end(); bs != be; ++bs) {
      for (BasicBlock::iterator is = bs-&gt;begin(), ie = be-&gt;end(); is != ie; ++is) {
          Instruction&amp; inst  = *is;
          BinaryOperator* binop = dyn_cast&lt;BinaryOperator&gt;(&amp;inst);
  
          if (!binop) {
              continue;
          }
  
          unsigned opcode = binop-&gt;getOpcode();
          errs() &lt;&lt; binop-&gt;getOpcodeName() &lt;&lt; "\n";
  
          if (opcode != Instruction::Add) {
              continue;
          }
  
          IRBuilder&lt;&gt; builder(binop);
          Value* v = builder.CreateAdd(builder.CreateXor(binop-&gt;getOperand(0), binop-&gt;getOperand(1)), 
                                       builder.CreateMul(ConstantInt::get(binop-&gt;getType(), 2), 
                                                         builder.CreateAnd(binop-&gt;getOperand(0), binop-&gt;getOperand(1))));
  
          ReplaceInstWithValue(bs-&gt;getInstList(), is, v); // THINGS GO WRONG HERE!
      } 
  } 
  </code></pre>