Do any C ++ compilers remove if statements that always have the same answer when inline?

If I have, for example, the following function:

void foo(DoThisSometimes, DoThisAlways)
{
  if (DoThisSometimes == 1)
    {
      //Do stuff
    }
  //Do other stuff
{

      

And the inline part of the code calls this function with DoThisSometimes

as 0, are there any compilers that would remove this part of the code from the inline function:

if (DoThisSometimes == 1)
    {
      //Do stuff
    }

      

+3


source to share


2 answers


A good compiler should certainly do this optimization, and GCC does. Next source:

#include <cstdio>

inline void foo(bool maybe)
{
    if (maybe) {
        printf("Maybe\n");
    }
    printf("Always\n");
}

int main()
{
    foo(true);
    foo(false);
}

      

compiles (optimized -O3

) to:



0000000000400410 <main>:
  400410:   48 83 ec 08             sub    $0x8,%rsp
  400414:   bf e4 05 40 00          mov    $0x4005e4,%edi
  400419:   e8 d2 ff ff ff          callq  4003f0 <puts@plt>
  40041e:   bf ea 05 40 00          mov    $0x4005ea,%edi
  400423:   e8 c8 ff ff ff          callq  4003f0 <puts@plt>
  400428:   bf ea 05 40 00          mov    $0x4005ea,%edi
  40042d:   e8 be ff ff ff          callq  4003f0 <puts@plt>
  400432:   31 c0                   xor    %eax,%eax
  400434:   48 83 c4 08             add    $0x8,%rsp
  400438:   c3                      retq   
  400439:   0f 1f 00                nopl   (%rax)

      

call puts

three times, unconditionally.

+6


source


Yes, most likely. If the compiler can figure out the meaning, it will often remove all or parts of the if-statement.

Piece by piece, I mean if you do:

 if (DoThisSometimes == 1 || foo == 0)

      



the compiler may remove DoThisSometimes==1

, but not part foo == 0

, as it foo

may not have a known value at the point of insertion.

Keep in mind that these are implementation details of the compiler, so the compiler is NOT GUARANTEED to remove the instruction, and it certainly won't if it can't figure out what that value is. He may also decide not to include the function when it has an if statement because it thinks the function is too long, and then when the if statement is gone, ok. So while you can expect it to happen, you certainly shouldn't treat it if it is super critical - in that case, do two functions: one for "DoThisSometimes == 1" and one for "DoThisSometimes! = 1".

+1


source







All Articles