Why do "Uses" always point to self?


I use the code from the LLVM programmer manual


for (llvm::Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) {

to iterate over Function ‘_Z2tcv’ uses in the trivial module

; ModuleID = ‘module’
target datalayout = “e-m:w-p:32:32-i64:64-f80:32-n8:16:32-S32”
target triple = “i686-pc-windows-gnu”

; Function Attrs: nounwind
define void @_Z2tcv() #0 {
ret void

; Function Attrs: nounwind
define i32 @main() #0 {
call void @_Z2tcv()
ret i32 0

attributes #0 = { nounwind “less-precise-fpmad”=“false” “no-frame-pointer-elim”=“true” “no-frame-pointer-elim-non-leaf”
“no-infs-fp-math”=“false” “no-nans-fp-math”=“false” “stack-protector-buffer-size”=“8” “unsafe-fp-math”=“false” “use-soft
-float”=“false” }

!llvm.ident = !{!0}

!0 = metadata !{metadata !“clang version 3.5.0 (207351)”}

_Z2tcv has indeed one use, as expected, but the use is not a call instruction as in main as expected so

llvm::Instruction *Inst = dyn_castllvm::Instruction(*i)

results in NULL.

Examining the use value with the code

const llvm::Use &U = (*i);

indeed shows that U is same value as F, so F uses itself??

I have seen this in more complicated cases, the number of uses is as expected but the uses always point to the function or variable and not the real users.

What is wrong?

Thanks, Yaron

Hi Yaron,

A Use is an edge between a Value and its users. If you dereference a Use, you get the Value it points to (which of course is your function - the thing that “is being used” is F). What you want is the user of that use, so you need to call U.getUser().




Thanks, using getUser() indeed works. I am still confused by the example in the LLVM Programmer’s Manual that says


Finding all of the instructions that use foo is as simple as iterating over the def-use chain of F:

Function *F = ...;

for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i)
  if (Instruction *Inst = dyn_cast<Instruction>(__*i__)) {

won’t (*i) get us back the llvm::Value (def) which is F ?
should the example code read

  if (Instruction *Inst = dyn_cast<Instruction>(**i->getUser()**)) {

I think so. Chandler, is this changed in r203364, no?


The for code could be ranged

for (llvm::user i : F->users())
  if (Instruction *Inst = dyn_cast<Instruction>(i)) {

and the next code segment could be

for (llvm::use i : pi->uses()) {

Nice. That code lives in docs/ProgrammersManual.rst. Could you send a
patch to llvm-commits?