gcc does not reduce to call result if called function is not static in
-O2 (will do with -O2)
clang and msvc does it also in -O2 regardless of the function beeing
static or not

can someone explain to me why the -O2 optimizer is not able(allowed) to
reduce this small sample the same way as clang/msvc?

x86-64 gcc 10.2 and trunk -O2: https://godbolt.org/z/r3GM57
x86-64 clang trunk and 11.0.0 -O2: https://godbolt.org/z/8hqbz5
x64 msvc v19.27 -O2: https://godbolt.org/z/nv3rWq

code to reproduce

---------------------------
#include <cstdint>

// part of run length encoding...

static void v32(uint32_t v_, uint8_t* b_, int& s_)
{
  if (v_ <= 0x0000007FU)
  {
    s_ = 1;
    b_[0] = (uint8_t)v_;
    return;
  }
  if (v_ <= 0x00003FFFU)
  {
    s_ = 2;
    b_[1] = (uint8_t)(v_ & 0x7F);
    b_[0] = (uint8_t)((v_ >> 7) | 0x80);
    return;
  }

  s_ = 3;
  b_[2] = (uint8_t)(v_ & 0x7F);
  b_[1] = (uint8_t)((v_ >> 7) | 0x80);
  b_[0] = (uint8_t)((v_ >> 14) | 0x80);
  return;
}

int test(uint32_t v_)
{
  uint8_t b[3]{};
  int s=0;
  v32(v_, b, s);
  return s+b[0]+b[1]+b[2];
}

int main(int argc, char** argv)
{
  return test(1337); // results in 197

  // clang reduces the call down to 197    regardless of test beeing
static or not
  //main:                                   # @main
  //  mov eax, 197
  //  ret

  // gcc reduces the call only if test is static
  //main:
  //  mov edi, 1337
  //  jmp test(unsigned int)
}
------------------------------------

Reply via email to