Search code examples
compiler-constructionllvm

Pass finding number of methods calls


I'm very new to writing LLVM passes, and I'm wondering what I should add to my pass if I want to calculate how many times my main function calls printf() (as an example).

Say I have this super exciting main:

#include <stdio.h>

int main() {
  printf("hello world\n");
  return 0;
}

And I want my pass to see if printf() gets called and how many times it gets called (if it was in a loop of some sorts for example).

This is what I have in my pass so far:

namespace {
  struct SkeletonPass : public FunctionPass {
    static char ID;
    SkeletonPass() : FunctionPass(ID) {}

    virtual bool runOnFunction(Function &F) {
      errs() << "I saw a function called " << F.getName() << "!\n";
      errs() << "It uses printf()" << F. //I'd like to write out how many     times printf() is used here
      return false;
    }
  };
}

Solution

  • If you only want to check printf is called or not, and not go through CFG.

    llvm subclass runOnFunction runs for per function body, you can iterate over function instruction and check if they are CallInst or not and call to particularly printf.

    inst_iterator inst = inst_begin(&F);
    inst_iterator instEnd = inst_end(&F);
    for(; inst != instEnd; ++inst)
    {
        if (CallInst* psCall = dyn_cast<CallInst>(&*inst))
        {
            StringRef name = psCall->getCalledFunction()->getName();
            /* check name */
        }
    }
    

    now to check if it is in loop. there is a subclass runOnLoop but LPPassManager interface should be used to update loop nest.(if you want to update it)

    for Control flow search,

    BasicBlocks are already organised in CFG way, they have successor and predecessor, so you dont have to build new graph. you can use simple recursive DFS algorithm to go through cfg.

    look here http://eli.thegreenplace.net/2013/09/16/analyzing-function-cfgs-with-llvm this guy have explained a lot better.

    also look in llvm manuals to find better interfaces and procedures. http://llvm.org/docs/WritingAnLLVMPass.html