【问题标题】:Is this strange inlining behavior of Visual C++ expected?Visual C++ 的这种奇怪的内联行为是预期的吗?
【发布时间】:2011-12-09 02:15:12
【问题描述】:

我有这个(相当无用的)代码:

 __declspec(noinline)
 int foo( char* ptr, int offset )
 {
    if( 5 / offset == 3 ) {
      return 1;
    }
    if( ptr != ptr + offset ) {
      return 2;
    }
    return 0;
 }

 int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
 {
    if( foo( 0, 0 ) ) {
       rand();
    }
 }

我通过优化编译它并得到这个反汇编:

    141: __declspec(noinline)
    142: int foo( char* ptr, int offset )
    143: {
    144:   if( 5 / offset == 3 ) {
00401000  push        5  
00401002  pop         eax  
00401003  cdq  
00401004  xor         ecx,ecx  
00401006  idiv        eax,ecx  
00401008  sub         eax,3  
0040100B  neg         eax  
0040100D  sbb         eax,eax  
0040100F  inc         eax  
    145:     return 1;
    146:   }
    147:   if( ptr != ptr + offset ) {
    148:     return 2;
    149:   }
    150:   return 0;
    151: }
00401010  ret  
    152: 
    153: int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
    154: {
    155:    if( foo( 0, 0 ) ) {
00401011  call        foo (401000h)  
00401016  test        eax,eax  
00401018  je          wmain+0Fh (401020h)  
    156:        rand();
0040101A  call        dword ptr [__imp__rand (4020A0h)]  
    157:    }
    158: }
00401020  xor         eax,eax  
00401022  ret

编译器保留了foo() 函数调用,但通过将编译时已知的参数传播到函数体并优化代码来编译foo()。它甚至发出了

警告 C4723:电位除以 0

这是 Visual C++ 的预期行为吗?

【问题讨论】:

  • 嗯.... 是吗?我不太确定你在寻找什么答案。
  • 仅供参考,此代码用作除零示例:stackoverflow.com/questions/7790272/…
  • 闻起来像 LTO/Whole program optimization,这是 MSVC 的特定选项

标签: c++ function visual-c++ inline compiler-optimization


【解决方案1】:

我想是的。你告诉它不要内联函数,但你没有说它不能根据函数的使用方式修改函数。可以看到该函数只被称为foo(0,0),那么为什么不为此优化函数呢?

除了(0,0) 调用之外,尝试插入类似foo(1,2) 的调用,看看会发生什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多