lgbo
lgbo

Reputation: 221

How to find which global variables are used in a function by using LLVM API?

I want to collect all the global variables used in a function for LLVm IR code. Is there any LLVM API can do this? For example,`as the following code.

int a,b;
int fun(){return a+b;}

global variables a and b are used in fun(), I need to collect a and b in a set.

Upvotes: 3

Views: 2665

Answers (2)

Eli Bendersky
Eli Bendersky

Reputation: 273726

Oak's solution should work. I'll just add that for a more efficient approach (in a typical translation unit), what I'd do is walk the users() list of each global var (see this section in the LLVM programmer manual) and note the functions it appears in, and then would infer from that.

But this is, admittedly, a tradeoff. If you have an (non-typical) translation unit with little code and a lot of globals, Oak's solution will be better.

Upvotes: 4

Oak
Oak

Reputation: 26898

I don't know of any single API method that does that, but writing one should be straightforward:

void getGlobalsUsedByFunction(const Function &F, set<GlobalValue*> *Globals) {
  for (const BasicBlock &BB : F)
    for (const Instruction &I : BB)
      for (const Value *Op : I.operands())
        if (const GlobalValue* G = dyn_cast<GlobalValue>(*Op))
          Globals->insert(G);
}

Upvotes: 4

Related Questions