Question

I have to instrument certain statements in clang by adding a statement just before it. I have a pointer to an Expr object using which I need to insert another statement just before the statement containing it. Right now I am using a hacky approach which just moves back the SourceLocation pointer till I see a ; or } or {. But this does not work for all cases. eg when I try to instrument a for statement, it fails. Is there any class in clang which provides a method to do this in a more cleaner way?

EDIT: Here is snippet of my code. I need to insert an assert just before the statement containing a pointer dereference.

bool MyRecursiveASTVisitor::VisitUnaryOperator(UnaryOperator *E){
    if (E->getOpcode() == UO_Deref ){
        Expr *e1 = E->getSubExpr();
        SourceLocation SL = E->getLocStart();
    }
    return true;
}
Was it helpful?

Solution

You can use getSourceRange() on the statement which returns SourceRange SourceRange Class has getBegin() which will return SourceLocation.

you can checkout https://github.com/eschulte/clang-mutate and see an example there...

EDIT:

In order to extract Expr out of Stmt you can checkout this SO question How to get Stmt class object from Expr object in Clang

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top