Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instrument a statement just before another statement using clang

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;
}
like image 786
anirudh Avatar asked Feb 19 '14 17:02

anirudh


People also ask

Does clang define __ GNUC __?

(GNU C is a language, GCC is a compiler for that language.Clang defines __GNUC__ / __GNUC_MINOR__ / __GNUC_PATCHLEVEL__ according to the version of gcc that it claims full compatibility with.

What is clang ++ command?

DESCRIPTION. clang is a C, C++, and Objective-C compiler which encompasses preprocessing, parsing, optimization, code generation, assembly, and linking. Depending on which high-level mode setting is passed, Clang will stop before doing a full link.

What is clang tidy?

clang-tidy is a clang-based C++ “linter” tool. Its purpose is to provide an extensible framework for diagnosing and fixing typical programming errors, like style violations, interface misuse, or bugs that can be deduced via static analysis.

Is clang better than G ++?

Clang is much faster and uses far less memory than GCC. Clang aims to provide extremely clear and concise diagnostics (error and warning messages), and includes support for expressive diagnostics. GCC's warnings are sometimes acceptable, but are often confusing and it does not support expressive diagnostics.


1 Answers

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

like image 198
ekeren Avatar answered Sep 28 '22 04:09

ekeren