如何使用LLVM函数传递找出调用站点的循环深度?

时间:2016-05-13 19:35:15

标签: llvm llvm-c++-api

我需要使用LLVM函数传递找出函数调用站点(或任何指令)的嵌套级别。我已经编写了下面的代码,但它总是以嵌套级别返回0。

virtual bool runOnFunction(Function &F) {
  LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  errs() << "Function: " << F.getName() << "\n";

  for (User *U : F.users()) {
    CallSite CS(dyn_cast<Instruction>(U));
    Function *callerFn = CS.getCaller();
    if (callerFn && !callerFn->isDeclaration()) {
      errs() <<callerFn->getName() << "--> " << F.getName()<<"\n";
      Instruction *callInstr = CS.getInstruction();
      BasicBlock *callerBB = callInstr->getParent();
      callerBB->dump();
      bool isLoop = LI.getLoopFor(callerBB);
      errs()<<"Is Loop: "<<isLoop<<"\n";
      int LoopDepth = LI.getLoopDepth(callerBB);
      errs()<<"Loop Depth: "<< LoopDepth <<"\n";

    }

  }

1 个答案:

答案 0 :(得分:1)

  

我需要找出一个函数调用站点(或任何一个)的嵌套级别   指示,就此而言)

For循环,您可以通过以下方式编辑传递:

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

    void getAnalysisUsage(AnalysisUsage &AU) const override {
      AU.setPreservesCFG();
      AU.addRequired<LoopInfoWrapperPass>();
    }

    bool runOnFunction(Function& F) override {
      LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
      for (LoopInfo::iterator LIT = LI.begin(); LIT != LI.end(); ++LIT) {
        Loop* ll = *LIT;  
        ll->dump();
      }
      return false;
    }
};

使用opt命令执行此传递。

假设以下示例输入:

int main(int argc, char* argv[]) {
  int a;

  for (int i = 0; i < 1000; i++){
    for (int j = 0; j < 1000; j++)
      a = i + j;
  }
  return 0;
}

输出结果为:

Loop at depth 1 containing: %for.cond<header><exiting>,%for.body,%for.cond.1,%for.end,%for.inc.7<latch>,%for.body.4,%for.inc
    Loop at depth 2 containing: %for.cond.1<header><exiting>,%for.body.4,%for.inc<latch>

我已打印出loop->dump(),您也可以轻松地将其改编为另一个属性。