如何在 Clang 中获取调用者参数的源变量声明?

How to get the source Variable Declaration of an caller argument in Clang?

我对 clang 很陌生。如果这个问题听起来很愚蠢,请原谅。

我正在尝试编写一个简单的 Clang 检查器。

我有一个简单的程序。

void function(int a)
{
   printf("%d", a);
}

main()
{      
       static int A = 0; 
       //some computation
       //How to get the source of the variable declaration of A here? 
       func(A);    
}

我的尝试

void MyChecker::checkPreCall(const CallEvent &Call,
                                       CheckerContext &C) const {

   ParamVarDecl *VD = Call.parameters()[0];
   //this dumps the declaration of the callee function, i.e dest
   Call.parameters()[0]->dump();
   if(Call.parameters()[0]->isStaticLocal()){
        std::cout << "Static variable";
    }

}

我试图在调用func时获得A的变量声明。但是它得到被调用者参数的变量声明;即目的地。如何获取源的变量声明?

参数是函数声明的一部分,而参数是调用表达式的一部分。您可以在此阅读更多相关信息 question. Clang's documentation 还强调了 parameters 方法的差异:

Return call's formal parameters.

Remember that the number of formal parameters may not match the number of arguments for all calls. However, the first parameter will always correspond with the argument value returned by getArgSVal(0).

您需要改用 getArgExpr。另外我要注意任何表达式都可以用作调用参数,所以为了得到变量声明,你首先需要检查参数表达式是否确实引用了一个命名声明(即DeclRefExpr),然后去实际声明。

希望这些信息对您有所帮助。祝您使用 Clang 愉快!