【发布时间】:2014-03-20 12:34:01
【问题描述】:
拥有这段代码:
int main(){
int x = 13;
goto f;
asm __volatile__ (".byte 0xff");
f:
return 0;
}
我不明白为什么g++优化它并且不包含操作码(在反汇编中):
# 5 "q.c" 1
.byte 0xff
# 0 "" 2
即使我在没有任何优化的情况下进行编译:
g++ -g -O0 -S q.c。我尝试单独使用g++ -g 和g++ -O0,因为我读到它在某些情况下可能不兼容。
如果我评论goto f; 行,它将插入操作码。
.file "q.c"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $13, -4(%rbp)
#APP
# 5 "q.c" 1<<<<<<<<<<
.byte 0xff<<<<<<<<<<
# 0 "" 2<<<<<<<<<<
.L2:
#NO_APP
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section .note.GNU-stack,"",@progbits
问题是:
g++ 是否不包含一段代码,即使我完全没有优化编译也不会使用它?
我想知道为什么它不包含没有找到其他解决方案的那段代码。
更新
我在 cmets 中读到:这是糟糕的代码。但如果我想拥有它怎么办?如果我想在那里注入一段代码,它本身不做任何事情怎么办? g++ 会限制我吗?
更新 2
因为它的死代码不是解释。我在 Windows VS2012 上编译了这段代码
int main() {
std::cout << "something ";
goto foo;
__asm _emit 0xff
__asm _emit 0xfe;
foo :
std::cout << "other thing";
}
你猜怎么着?当它使用 Debug 配置编译时,asm 代码包含在二进制文件中:
.text:00414ECE push offset aSomething ; "something "
.text:00414ED3 mov eax, ds:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::basic_ostream<char,std::char_traits<char>> std::cout
.text:00414ED8 push eax
.text:00414ED9 call loc_41129E
.text:00414EDE add esp, 8
.text:00414EE1 jmp short loc_414EE7
.text:00414EE1 ; ---------------------------------------------------------------------------
.text:00414EE3 db 0EBh ; d
.text:00414EE4 db 2
.text:00414EE5 db 0FFh<<<<<<<<<<<<<<
.text:00414EE6 db 0FEh ; ¦<<<<<<<<<<<<
.text:00414EE7 ; ---------------------------------------------------------------------------
.text:00414EE7
.text:00414EE7 loc_414EE7: ; CODE XREF: main+31j
.text:00414EE7 push offset aOtherThing ; "other thing"
.text:00414EEC mov eax, ds:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::basic_ostream<char,std::char_traits<char>> std::cout
.text:00414EF1 push eax
.text:00414EF2 call loc_41129E
.text:00414EF7 add esp, 8
.text:00414EFA jmp short loc_414EFE
【问题讨论】:
-
因为它是死代码?
-
但是如果我想注入那个代码并且我希望它在那里呢?
-
我和埃米尔在这里;确定 volatile 的全部意义在于阻止它进行优化?另外,@EmilCondrea,您是否尝试过使用
volatile而不是__volatile__? -
尝试使用
-fno-dce(无死代码消除)标志。 -
@OMGtechy 是的,我试过了