Search code examples
c++llvmclangabstract-syntax-treeformat-string

Print arguments of a function using Clang AST


I want to get the arguments passed to a function. for example, if I have the call

printf("%d%d", i, j);

the output should be

%d%d
i
j

I am able to get to function calls using VisitCallExpr() in RecursiveASTVisitor. Also able to get the number of arguments and the argument types. But I don't know how to get the arguments.

bool MyRecursiveASTVisitor::VisitCallExpr (clang::CallExpr *E)  
{
    for(int i=0, j=E->getNumArgs(); i<j; i++)
    {
        llvm::errs() << "argType: " << E->getArg(i)->getType().getAsString() << "\n";
    }
    return true;
}

Output:

argType: char *
argType: int
argType: int

Please help me getting the arguments.


Solution

  • You are calling E->getArg(i)->getType() - but that is type of argument. Use E->getArg(i) to get Expr* representing value of argument. Then use printPretty(...) method to pretty-print it to string, if you need string value.