[LLVMdev] insertions with inst_iterators?

David Blaikie dblaikie at gmail.com
Mon Aug 29 12:59:09 PDT 2011


On Mon, Aug 29, 2011 at 12:38 PM, ret val <retval386 at gmail.com> wrote:

> I am looping through all instructions in a Function and depending on
> what I found I may or may not insert code. Despite the fact that I'm
> only actually inserting *before* instruction I have a infinite loop
> when I do something like below. For awhile it was simple enough to
> just increment i enough times but now I need something better.
>
> for(inst_iterator i = inst_begin(F); i != inst_end(F); ++i) {
>         ...
>         // possible insertions of unknown size
>         ...
> }
>
> I tried storing the storing the initial iterator and reverting back to
> it(along with storing the next element) and I am still left with a
> infinite loop. I see some discussion online about weather insertions
> with iterators in C++ is allowed period, so what is the correct way to
> do something like this in LLVM? This must be a common problem.
>

In general, this sort of thing depends on the container you're iterating
over. Different containers have different iterator invalidation semantics.

In this case, probably what you need to do is:

i = insert(i, ...);

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.

(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)

[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]

- David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20110829/c8193bcd/attachment.html>


More information about the llvm-dev mailing list