Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSVC and optimizing out constant expressions

The project that I'm working on is written in C and uses a pre-processor macro to handle errors.

The macro looks something like:

#define logevent(level, msg) \
    do {
        int _level = level; \
        somefunction(_level, msg); \
        someotherfunction(_level, msg); \
        if (_level >= ERROR) \
          __assume(0); \
    } while(0)

Let's say that someotherfunction does exit(1) if the level >= ERROR and we never make it to the if condition when we call logevent(ERROR, "something"); where ERROR is a defined constant. The problem is that MSVC does not seem to be able to optimize away the if condition due to the if condition being based on the _level variable rather than the level constant. The _level variable is required to stop multiple evaluations of the level expression.

Certain other compilers seem to be able to optimize away the if, but I'm wondering if this a limitation of the MSVC compiler or is there something I can enable to get the compiler to optimize these if conditions away?

like image 940
user3187015 Avatar asked Mar 22 '23 00:03

user3187015


1 Answers

MSVC 2013 will optimize our expression. The following input

#define ERROR 1

void somefunction(int level, char const* msg) {
  printf("FUNC1 %d: %s\n", level, msg);
}

void someotherfunction(int level, char const* msg) {
  printf("FUNC2 %d: %s\n", level, msg);

  if (level >= ERROR) {
    exit(1);
  }
}

#define logevent(level, msg) \
  do { \
    int _level = level; \
    somefunction(_level, msg); \
    someotherfunction(_level, msg); \
    if (_level >= ERROR) \
      __assume(0); \
    } while (0)

int _tmain(int argc, _TCHAR* argv[])
{
  logevent(ERROR, "HALLO");
  printf("Hallo\n");
  getchar();
  return 0;
}

will compile to

00CB1000  push        0CB2120h  
00CB1005  push        1  
00CB1007  push        0CB2100h  
00CB100C  call        dword ptr ds:[0CB2090h]  
00CB1012  push        0CB2120h  
00CB1017  push        1  
00CB1019  push        0CB2110h  
00CB101E  call        dword ptr ds:[0CB2090h]  
00CB1024  add         esp,18h  
00CB1027  push        1  
00CB1029  call        dword ptr ds:[0CB208Ch] 
like image 107
weinberger Avatar answered Mar 31 '23 10:03

weinberger