Bso
Bso

Reputation: 41

Clang AST: Evaluate the expression

Suppose we have a c++ code as below

int main()
{
    int val = 4 + 5;
}

For above code, corresponding AST will look like as below with the command clang++ -cc1 -ast-dump ConsoleApplication1.cpp

TranslationUnitDecl 0x6822f40 <<invalid sloc>> <invalid sloc>
|-TypedefDecl 0x6823628 <<invalid sloc>> <invalid sloc> implicit __NSConstantString '__NSConstantString_tag'
| `-RecordType 0x6823450 '__NSConstantString_tag'
|   `-CXXRecord 0x68233f0 '__NSConstantString_tag'
|-TypedefDecl 0x6823690 <<invalid sloc>> <invalid sloc> implicit __builtin_va_list 'char *'
| `-PointerType 0x6823660 'char *'
|   `-BuiltinType 0x6822fa0 'char'
`-FunctionDecl 0x6823718 <ConsoleApplication1/ConsoleApplication1.cpp:2:1, line:5:1> line:2:5 main 'int ()'
  `-CompoundStmt 0x68238ac <line:3:1, line:5:1>
    `-DeclStmt 0x6823898 <line:4:5, col:20>
      `-VarDecl 0x68237f0 <col:5, col:19> col:9 val 'int' cinit
        `-BinaryOperator 0x6823880 <col:15, col:19> 'int' '+'
          |-IntegerLiteral 0x6823830 <col:15> 'int' 4
          `-IntegerLiteral 0x6823858 <col:19> 'int' 5

What I was looking for is that, is there any options I could set while generating the AST, so that AST will evaluate the expression (4+5 to 9) and AST will look like as below. Last 3 line of above AST is replaced by last line of below AST.

TranslationUnitDecl 0x67a0390 <<invalid sloc>> <invalid sloc>
|-TypedefDecl 0x67a0a78 <<invalid sloc>> <invalid sloc> implicit __NSConstantString '__NSConstantString_tag'
| `-RecordType 0x67a08a0 '__NSConstantString_tag'
|   `-CXXRecord 0x67a0840 '__NSConstantString_tag'
|-TypedefDecl 0x67a0ae0 <<invalid sloc>> <invalid sloc> implicit __builtin_va_list 'char *'
| `-PointerType 0x67a0ab0 'char *'
|   `-BuiltinType 0x67a03f0 'char'
`-FunctionDecl 0x67a0b68 <ConsoleApplication1/ConsoleApplication1.cpp:2:1, line:5:1> line:2:5 main 'int ()'
  `-CompoundStmt 0x67a0cbc <line:3:1, line:5:1>
    `-DeclStmt 0x67a0ca8 <line:4:5, col:16>
      `-VarDecl 0x67a0c40 <col:5, col:15> col:9 val 'int' cinit
        `-IntegerLiteral 0x67a0c80 <col:15> 'int' 9

Thanks a lot in advance.

Upvotes: 0

Views: 541

Answers (2)

D Asp
D Asp

Reputation: 145

As far as I know, the Abstract Syntax Tree does keep track of information from source file. As a result, what you mentioned:

-IntegerLiteral 0x67a0c80 col:15 'int' 9

may be unexpected, because there isn't such information("9" in column 15) in source file.

If you want to do the constant-folding work, you may try "Expr->EvaluateAsInt()" from Expr.h in clang lib.

Upvotes: 0

Bernard Nongpoh
Bernard Nongpoh

Reputation: 1058

It looks like you're trying to do an optimization pass at Clang AST. However, this step is done at the LLVM IR pass (Constant Propagation). Maybe I am wrong, but you can find the relevant answer here Generate an optimized AST using clang and libclang

Upvotes: 1

Related Questions