How to get the Instruction where one function use the global variable.

Hi, all
I try to get the Instructions where one function use the global variable.

for (llvm::Module::global_iterator gvar_iter = M.global_begin(); gvar_iter != M.global_end(); gvar_iter++)
llvm::GlobalVariable *gvar = &*gvar_iter;
llvm::errs() << "const global var: " << gvar->getName() << “\n”;

for ( llvm::GlobalVariable::use_iterator iter = gvar->use_begin(); iter != gvar->use_end(); iter++ )
llvm::User *user = llvm::dyn_castllvm::User(*iter);

&nbs! p; if ( llvm::isallvm::Constant(user))
llvm::errs() << “isa Constant :”;
else if (llvm::isallvm::Instruction(user))
llvm::errs() << “isa Instruction”;
else if (llvm::isallvm::Operator(user))
&nbs! p; &n bsp; llvm::errs() << “isa Operator”;

if ( llvm::isallvm::Instruction(user))
llvm::Instruction *instr = llvm::dyn_castllvm::Instruction(*iter);
llvm::errs() << instr << “\n”;
! ; }
else if ( llvm::isallvm::ConstantExpr(user))
llvm::ConstantExpr const_expr = llvm::dyn_castllvm::ConstantExpr(iter);
llvm::errs() <<const_expr << “\n”;
! }
&nbs p; }
llvm::errs() << “\n”;
by this method ,I want to get the instruction in the function,but there will be retrun constantExp.
for example:
in the IR:
@gNoise = common global %struct.rs_allocation.0 zeroinitializer, align 4
tail call void @_Z13rsClearObjectP13rs_allocation(%struct.rs_allocation.0
@gNoise) nounwind
%7 = load [1 x i32]
bitcast (%struct.rs_allocation.0
@gNoise to [1 x i32]
), align 4

but the user will return the use as follows:
1.tail call void @_Z13rsClearObjectP13rs_allocation(%struct.rs_allocation.0* @gNoise) #0
2. [1 x i32]* bitcast (%struct.rs_allocation.0* @gNoise to [1 x i32])
I want to get the " instruction %7 = load [1 x i32]
! bitcast (%struct.rs_allocation.0* @gNoise to [1 x i32]), align 4",
not "[1 x i32]
bitcast (%struct.rs_allocation.0* @gNoise to [1 x i32]*)"
How could I get this?

Your example is a little difficult to follow due (I think) to line-wrapping in your email. However, the problem seems to be that you have a load instruction that uses a constant expression that uses the global.

What it sounds like you want to do is to find all transitive uses of the global (i.e., if a ConstantExpr uses a Global, and an Instruction uses the ConstantExpr, then you want to find the Instruction, too).

In that case, you can’t just find all direct uses of the global. You have to iterate through all uses of the ConstantExpr as well (and potentially Constants and Instructions, depending on what you consider to be a “use” of the Global).

– John T.