可以指示GCC不要消除无效代码吗? [英] Can GCC be instructed not to eliminate dead code?

查看:61
本文介绍了可以指示GCC不要消除无效代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用现代版本的GCC来编译C程序.此外,请考虑我的程序包含陈旧的分支,但是我非常希望这些陈旧的分支中的无效代码可以编译并显示在最终程序中.请考虑以下程序:

Suppose that I'm using a modern version of GCC to compile a C program. Furthermore, consider that my program contain stale branches, but that I'd very much like the dead code in those stale branches to be compiled and present in the final program. Consider the following program:

int main(int argc, char** argv) {
    int a = 0;
    goto skip;
        a = -1;
    skip: ;
    return a;
}

很显然,如果我将GCC与默认优化设置一起使用,则第二个赋值将永远不会进入最终程序,因为编译器可以很容易地告知它永远不会执行.假设我不希望发生这种情况.

Clearly, if I use GCC with default optimization settings, the second assignment will never make it to the final program, as the compiler can easily tell that it'll never be executed. Suppose that I don't want this to happen.

GCC中,有许多标志与死代码有关(最明显的是-fdce),我可以选择相应地调用GCC来显式停用这些标志:

In GCC, there are a number of flags that dabble with dead code (most notably -fdce), and I can chose to explicitly deactivate these when invoking GCC accordingly:

-fno-dce
-fno-dse
-fno-tree-dce
-fno-tree-dse

据我所知,这应该指示GCC不要弄乱第二个分配.但是,相关代码似乎从未进入我的程序.

As far as I can tell, this should instruct GCC not to mess with the second assignment. Yet, the concerned code never seems to make it into my program.

为什么GCC坚持要删除无效代码,并且有一种方法可以指示GCC not 摆脱第二个分配?

Why does GCC insist on removing the dead code, and is there a way of instructing GCC not to get rid of the second assignment?

推荐答案

在gcc-4.9.2中,-fno-*选项对我也不起作用. 就是说,我认为以下内容应适用于所有gcc(4.5+)目标:

The -fno-* options don't work for me either with gcc-4.9.2. That said, I think the following should be portable for all gcc (4.5+) targets:

__asm__ goto (""::::no_skip);
goto skip;

no_skip:
    a = -1;

skip:;

手册中的内容:一个asm goto语句始终被隐式认为是易失的."

From the manual: "an asm goto statement is always implicitly considered volatile."

此外,对于gcc-4.8及更高版本,您可以考虑添加一个属性,以使编译器知道这是不太可能"的路径.这有助于防止采用预期"路径时可能发生的分支惩罚等.

Furthermore, with gcc-4.8 and above, you might consider adding an attribute to let the compiler know that this is an 'unlikely' path. This helps prevent branching penalties, etc., that might otherwise occur when taking the 'expected' path:

no_skip: __attribute__ ((cold));

理所当然,您也可以使用:

It stands to reason that you could also use:

skip: __attribute__ ((hot));

这篇关于可以指示GCC不要消除无效代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆