【问题标题】:Basic source-to-source transformation with Clang使用 Clang 进行基本的源到源转换
【发布时间】:2012-06-18 06:39:25
【问题描述】:

我已经成功构建了sample code

现在我有一个要求,如果我有如下示例代码:

int inc(int& p)
{
        p++;
        printf("In inc [%d]\n", p);
        return p;
}
int main()
{
        int i = 0;
        int y,z;
        if(y == 0)
                print(inc(i) , inc(i));
        else
        {
                print(inc(i) , inc(i));
        }
        printf("y = [%d] z = [%d]\n", y , z);
        return 0;
}

代码应该转换为

int inc(int& p)
{
        p++;
        printf("%s %d", __FILE__, __LINE__);
        printf("In inc [%d]\n", p);
        printf("%s %d", __FILE__, __LINE__);
        return p;
}

int main()
{
        int i = 0;
        printf("%s %d", __FILE__, __LINE__);
        int y,z;
        printf("%s %d", __FILE__, __LINE__);
        if(y == 0)
                print(inc(i) , inc(i));
        else
        {
                print(inc(i) , inc(i));
                printf("%s %d", __FILE__, __LINE__);
        }
        printf("y = [%d] z = [%d]\n", y , z);
        printf("%s %d", __FILE__, __LINE__);
        return 0;
}

我尝试了以下代码更改:

bool VisitStmt(Stmt *s) {
    // Only care about If statements.
    if (isa<CompoundStmt>(s)) {
        CompoundStmt *Statement = cast<CompoundStmt>(s);
        TheRewriter.InsertText(Statement->getLocStart(),
                               "printf(\"%s %d\", __FILE__, __LINE__);\n",
                               true, true);
    }

但输出如下:

// Begin function inc returning int
int inc(int& p)
printf("%s %d", __FILE__, __LINE__);
{
        p++;
        printf("In inc [%d]\n", p);
        return p;
}
// End function inc

// Begin function main returning int
int main()
printf("%s %d", __FILE__, __LINE__);
{
        int i = 0;
        int y,z;
        if(y == 0)
                print(inc(i) , inc(i));
        else
        {
                print(inc(i) , inc(i));
        }
        printf("y = [%d] z = [%d]\n", y , z);
        return 0;
}
// End function main

请告诉我如何实现目标?

我也得到如下输出:

test.cpp:4:26: error: use of undeclared identifier 'p'
        printf("In inc [%d]\n", p);
                                ^
test.cpp:5:9: error: use of undeclared identifier 'p'
        return p;

如何停止代码呈现相同的内容?只是复合块中的语句应该添加额外的语句。

【问题讨论】:

  • 您的 VisitStmt 函数似乎没有返回合理的布尔值,我怀疑访问取决于这种布尔结果来决定它是否应该下降到子树中。只是猜测。

标签: gcc llvm clang llvm-gcc llvm-clang


【解决方案1】:

如果您查看生成的代码,那是非法的混乱。奇迹编译器不会让你的耳朵尖叫;-)

显然 LLVM(使用您的 VisitStmt)仅将“{...}”视为“复合语句”,并且输出发生在语句本身之前。仔细检查这些穿插的动作何时完成(我怀疑是在之前或之后,而不是在中间)。

【讨论】:

    【解决方案2】:

    如果我理解正确并添加到@vonbrand,您不应该使用复合语句的开始和结束,因为它们代表语句块。 相反,您应该在通用的 VisitStmt 正文中插入文本(打印语句)来替换上面的内容。请注意,我不清楚您要完成什么,因为您在 if/else 语句之后没有立即打印语句。 我认为,如果您只是列出要处理的语句,然后在您的访问者实现中使用“isa”条件来处理每种情况,这会有所帮助。这样,您实际上就正确地使用了访问者模式。 希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2016-12-28
      • 2014-04-20
      • 2013-12-07
      • 1970-01-01
      相关资源
      最近更新 更多