How to know whether expression is derived from induction variable?

I am interested in knowing if an expression is derived from loop induction variable or not. As of now, I am able to inspect every expression after locating “if” statement in the code.

Assume following code:

for(int i=0;i<32;i++)


in above code, I am able to get access to the expression “i+2” but how should I analyze its LHS and RHS for induction variable?

Any help appreciated.

The simplest probably would be finding all relevant loop nodes, i.e. ForExpr-s, identifying the loop induction variable, i.e. the VarDecl-s (if any), and finally running a RecursiveASTVisitor on its body, looking for a DeclRefExpr referring to any of the VarDecl-s you identified in the previous step.

Ohk…this looks cool. Let me try that. Thanks.

I am very basic thing now
I inherited RecursiveASTVisitor Class and overloaded function VisitStmt as

bool VisitStmt(Stmt *s)
std::cout<<“For Statement found\n”;
VarDecl *D=cast(s)->getConditionVariable();

return true;
but I am facing runtime error.(seg fault) any clue?

It looks like you are calling the wrong function getConditionVariable(), which returns 0 most of time.


But then which function is expected? Only getConditionVariable() returns VarDecl.
I just want to know induction var and all vars which are derived from induction var.

I do not believe there is a direct method to achieve this. You’ll most likely have to look at the init expr for the ForStmt, and check if it is a DeclStmt (or maybe an assignment, if you’re interested in that, in which case check for BinaryOperator and CXXOperatorCallExpr), and if so, what is the variable being declared.

By the way, RecursiveASTVisitor is incredibly flexible, you can just use bool VisitForStmt() instead of using VisitStmt and dyn-casting around. RecursiveASTVisitor has Visit* and Traverse* methods for all AST nodes (it’s hacked together with macros and codegen).