使用 Clang 转储源代码的 Block Liveness

Dump Block Liveness of source code using Clang

我需要使用 clang 的 API 转储源代码的块活性。我尝试打印块活性但没有成功。下面是我试过的代码

bool MyASTVisitor::VisitFunctionDecl(FunctionDecl *f) {

    std::cout<<"Dump Liveness\n";
    clang::AnalysisDeclContextManager adcm;
    clang::AnalysisDeclContext *adc = adcm.getContext(llvm::cast<clang::Decl>(f));
    //clang::LiveVariables *lv = clang::LiveVariables::create(*adc);
    //clang::LiveVariables *lv = clang::LiveVariables::computeLiveness(*adc,false);
    clang::LiveVariables *lv = adc->getAnalysis<LiveVariables>();
    clang::LiveVariables::Observer *obs = new clang::LiveVariables::Observer();

    lv->runOnAllBlocks(*obs);

    lv->dumpBlockLiveness((f->getASTContext()).getSourceManager());

    return true;
}

我已经覆盖访问者函数并尝试打印函数的活跃度。我曾尝试使用 create、computeLiveness 和 getAnalysis 方法来获取 LiveVariables 对象,但所有方法都失败了。但是,除了块号之外,没有显示任何活动信息。

当我使用 clang 的命令行参数打印 liveness 时,它会正确显示输出。

我使用以下源代码作为测试用例取自 Live Variable Analysis Wikipedia .

    int main(int argc, char *argv[])
{
  int a,b,c,d,x;

  a = 3;  
  b = 5;
  d = 4;
  x = 100;

  if(a>b){
    c = a+b;
    d = 2;
  }

  c = 4; 
  return b * d + c;
}

有人可以指出我哪里错了吗? 提前致谢。

我遇到了同样的问题,经过一些调试clang -cc1 -analyze -analyzer-checker=debug.DumpLiveVars我终于找到了答案!

问题在于 LiveVariables 分析本身并不探索子表达式(例如 DeclRefExpr)。它仅依赖于 CFG 枚举。默认情况下,CFG 仅枚举顶级语句。

在从 AnalysisDeclContext 获得任何分析之前,您必须先致电 adc->getCFGBuildOptions().setAllAlwaysAdd()。这将为控制流图的 CFGBlocks 中的所有子表达式创建元素。