[LLVMdev] The use iterator not working...

Daniel Berlin dberlin at dberlin.org
Tue Jun 9 19:16:05 PDT 2015


On Tue, Jun 9, 2015 at 7:02 PM, Zack Waters <zswaters at gmail.com> wrote:
> Hi,
>
> I'm having a problem with the use iterator. Each "use" that I see, when
> using the use_iterator, is the same as the "def". Meaning, in the code below
> the pDef is always equal to pUse pointer for every instruction in all basic
> blocks (except terminators).
>
>             for (auto i = inst_begin(f), ie = inst_end(f); i != ie; ++i)
>
>                 Instruction* pDef = &(*i);
>                 errs() << "Def: " << *pDef << "\n";
>
>                 for (auto ui = pDef->use_begin(), uie = pDef->use_end(); ui
> != uie; ++ui)
>                 {
>                     Instruction* pUse = dyn_cast<Instruction>(*ui);

This doesn't do what you think it does.

This gives you the places the instruction i occurs in some other
instruction.  Those places are in fact, pointers to i already.

You are then calling operator *, which will return i, and then
dyn_casting it to an instruction, which is still i.

If you want the *instruction that uses i* (not the pointer to the
place in that instruction that *is* i), then you want the users, not
the uses.
IE this would be Instruction* pUse = dyn_cast<Instruction>(ui->getUser())

Or just iterator over the users, not the uses.


>                     errs() << "  Use: \t" << *pUse << "\n";
>                 }
>             }
>
> However, everything works as expected when using the range-based use
> iterator with the following code.
>
>             for (auto i = inst_begin(f), ie = inst_end(f); i != ie; ++i)
>             {
>                 Instruction* pDef = &(*i);
>                 errs() << "Def: " << *pDef << "\n";
>
>                 for (User* pUser : pDef->users())
>                 {

This is not a use iterator, it is a user iterator, which is giving you
*the instructions that contain the uses*.


To illustrate the difference.

given
a = foo
b = a + c

(I'm simplifying, since LLVM does not represent LHS'en or have copies)

if you ask for a use iterator of a,

you will get &(operand 1 of b, which is a pointer to a).
If you dereference it, you will get "a" (and if you dyn_cast that to
an instruction, it will give you a = foo)
if you ask for it's user, you will get "a + c"

If you ask for a user iterator of a
you will get a + c






>                     Instruction* pUse = dyn_cast<Instruction>(pUser);
>                     errs() << "  Use: \t" << *pUse << "\n";
>                 }
>             }
>
> Also, the code is executed inside a function pass. So was initially thinking
> I somehow screwed up the use information in a previous pass. However, I
> would assume the range-based iterator would not work as well but it does.
>

Because it is not, in fact, giving you uses :)



More information about the llvm-dev mailing list