<br><br><div class="gmail_quote">On Mon, Aug 29, 2011 at 12:38 PM, ret val <span dir="ltr"><<a href="mailto:retval386@gmail.com">retval386@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
I am looping through all instructions in a Function and depending on<br>
what I found I may or may not insert code. Despite the fact that I'm<br>
only actually inserting *before* instruction I have a infinite loop<br>
when I do something like below. For awhile it was simple enough to<br>
just increment i enough times but now I need something better.<br>
<br>
for(inst_iterator i = inst_begin(F); i != inst_end(F); ++i) {<br>
        ...<br>
        // possible insertions of unknown size<br>
        ...<br>
}<br>
<br>
I tried storing the storing the initial iterator and reverting back to<br>
it(along with storing the next element) and I am still left with a<br>
infinite loop. I see some discussion online about weather insertions<br>
with iterators in C++ is allowed period, so what is the correct way to<br>
do something like this in LLVM? This must be a common problem.<br></blockquote><div><br></div><div>In general, this sort of thing depends on the container you're iterating over. Different containers have different iterator invalidation semantics.</div>
<div><br></div><div>In this case, probably what you need to do is:<br><br>i = insert(i, ...);<br><br>containers backed by contiguous sequences (like std::vector, and I assume the inst list - but I could be wrong) can invalidate all iterators on insertion (since they might need to reallocate memory - moving all the contents of the vector to a new, larger, buffer) - so generally they give you a new, valid iterator as a return result from any insertion operation.</div>
<div><br></div><div>(I assume your infinite loop that occured when you reset the iterator back to the start was caused by your own algorithm repeatedly inserting/restarting over and over again, and not by weirdness surrounding insertion iterator invalidation semantics)</div>
<div><br></div><div>[also note that the LLVM coding guidelines suggest storing end once & then using that in eahc loop iteration - you should do this, but you'll hit iterator invalidation on insertion for the end iterator too, so you'll have to re-initialize it after any insertion that might invalidate the end iterator]</div>
<div><br></div><div>- David</div><div><br></div></div>