Is there a way to get a CallExpr * call in the VisitCallExpr method with clang?

The getDirectCallee() method can get the called call (called the method / function) of the call expression, but is there a way to get the calling (method / function that called it) CallExpr* in the VisitCallExpr() method?

Are there other ways to recognize the caller of a single call expression?

+7
c ++ recursion clang abstract-syntax-tree
source share
2 answers

The best way to handle this is to use AST algorithms. you can basically search for all callExpr nodes in the AST method and bind them and at the same time bind the corresponding caller nodes (CXXRecordDecl) with another string as well.

Example:

 CallBackFunc callBackFunc; Matchers.addMatcher(callExpr(isExpansionInMainFile(), callee(), hasAncestor(recordDecl().bind("caller"))).bind("callee"), &callBackFunc); 

Then in the callBack function you can get theses of the called and calling functions, like this:

 class CallBackFunc : public MatchFinder::MatchCallBack { public: virtual void run(const MatcherFinder::MatchResult &Results) { auto callee = Results.Nodes.getNodeAs<clang::CallExpr>("callee"); auto caller = Results.Nodes.getNodeAs<clang::CXXRecordDecl>("caller"); // Do what is required with callee and caller. } }; 

(if necessary, I can provide additional information)

+4
source share

My answer may not be perfect, but it works.

There is no direct method that gives you a direct call expression call. But if we look at how the AST traverse goes when entering the call function, if we somehow save the last visited FunctionDecl name, it will give you a direct CallExpr* object.

Example

 string CallerFunc = ""; //declared in class (private/public) virtual bool VisitFunctionDecl(FunctionDecl *func) { CallerFunc = func->getNameInfo().getName().getAsString(); return true; } virtual bool VisitCallExpr(CallExpr *E) { if (E != NULL){ QualType q = E->getType(); const Type *t = q.getTypePtrOrNull(); if(t != NULL) { FunctionDecl *func = E->getDirectCallee(); //gives you callee function string callee = func->getNameInfo().getName().getAsString(); cout << callee << " is called by " << CallerFunc; } } } 
+1
source share

All Articles