[cfe-dev] Extracting variable name from VarDecl* Clang

Jonathan Roelofs via cfe-dev cfe-dev at lists.llvm.org
Sat Jun 4 06:56:13 PDT 2016



On 6/4/16 6:38 AM, Dhriti Khanna via cfe-dev wrote:
> Here is my sample code:
>
> int x=0;
> if(x == 0)
> cout << "Hey" << endl;
>
> I want to get 'x'.

getConditionVariable() will only return x if it is written this way:

if (int x = ... )
   ...

You need to do something more like this:

if (IfStmt *ifS = dyn_cast<IfStmt>(st))
{
   if (BinaryOperator *binOp = dyn_cast<BinaryOperator>(ifS->getCond()))
   {
      if (binOp->getOpcode() == BO_Assign)
      {
         if (DeclRefExpr *Decl = 
dyn_cast<DeclRefExpr*>(binOp->getLHS()->IgnoreParenCasts()))
         {
             ...
         }
      }
   }
}

It helps a *lot* to look at the AST dump for the examples you're 
interested in matching. To do that, run:

   $ ./bin/clang-check -ast-dump foo.c --

If you're going to be doing heavy matching of ASTs, I recommend looking 
into using this: http://clang.llvm.org/docs/LibASTMatchersReference.html 
instead of open-coding them.


Jon

>
> On Sat, Jun 4, 2016 at 6:06 PM, Miklos Vajna via cfe-dev
> <cfe-dev at lists.llvm.org <mailto:cfe-dev at lists.llvm.org>> wrote:
>
>     On Sat, Jun 04, 2016 at 05:32:37PM +0530, Dhriti Khanna via cfe-dev
>     <cfe-dev at lists.llvm.org <mailto:cfe-dev at lists.llvm.org>> wrote:
>     > This code:
>     >
>     >  if (IfStmt* ifS = dyn_cast<IfStmt>(st)) {
>     >    errs() << "Found an IF statement ";
>     >    VarDecl* var = ifS->getConditionVariable();
>     >    errs() << var->getNameAsString();
>     >  }
>     >
>     > produces cannot initialize object parameter of type 'const
>     > clang::NamedDecl' with an expression of type 'clang::VarDecl' error on errs()
>     > << var->getNameAsString(); line and the program crashes with a seg fault. I
>     > can't find what's wrong with this? Please help.
>
>     Please post some sample source code (from which the AST is generated),
>     without that it's quite hard to help. But in general I guess you can't
>     assume that you can get a single variable out of an if statement, if you
>     have "if (Foo && Bar)", which one would be returned by the API?
>
>     _______________________________________________
>     cfe-dev mailing list
>     cfe-dev at lists.llvm.org <mailto:cfe-dev at lists.llvm.org>
>     http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
>
>
>
>
> --
> Regards,
> Dhriti Khanna
> PhD Scholar
> IIIT Delhi
>
>
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
>

-- 
Jon Roelofs
jonathan at codesourcery.com
CodeSourcery / Mentor Embedded



More information about the cfe-dev mailing list