Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selectively inline functions (for debugging purposes)?

Tags:

c++

inline

What I'd love to have is a build configuration where functions are not inlined, except some selected functions (that may or may not be inlined, that would be up to the compiler).

Even better would be some kind of an "inlining level", where I could specify such a level for each function, plus a minimum level when building, and only functions above the min level would be allowed to be inlined. I know there's no standard solution for this, but compiler-specific hacks would be just as welcome.

I'd like to be able to step through most of my functions non-inlined in a debugger, but a selected few of them should be inlined, partly for performance reasons, and partly to avoid crazy-deep call stacks. The code involves some pretty nasty template metaprogramming, but that part is mostly done, so I'd like to concentrate on the rest. So it would be nice to have the functions that belong to the template metaprograms inlined, but not the other inline functions.

Is there any way to achieve something like this?

like image 984
imre Avatar asked Jan 17 '23 10:01

imre


2 Answers

Depending on your compiler, yes. For g++, the following will work:

void foo() __attribute__ ((noinline));
void foo() __attribute__ ((always_inline));

On MSVC++:

__declspec(noinline) void foo();
__forceinline void foo();

Note that g++ requires that the attributes be applied only to prototypes, not definitions. So if your function is definition-only (no separate prototype) then you must create a prototype in order to apply the attribute. MSVC does not have this requirement.

__forceinline specifically has some exceptions. Make sure you read them carefully so you know whether or not it will have any effect in your particular situation. g++ does not document any exceptions to the always_inline attribute, but some things are readily apparent (inlining a call to a virtual method will only work when the method is called statically, for example).

You can generalize this with macros:

#ifdef _MSC_VER
 #define NOINLINE(x) __declspec(noinline) x
 #define INLINE(X) __forceinline x
#else
 #ifdef __GNUC__
  #define NOINLINE(x) x __attribute__ ((noinline))
  #define INLINE(x) x __attribute__ ((always_inline))
 #else
  #error "I don't know how to force inline/noinline on your compiler."
 #endif
#endif

INLINE(void foo());
NOINLINE(void foo());
like image 108
cdhowie Avatar answered Jan 19 '23 00:01

cdhowie


If there are a set of functions you want inlined, you can #define some macro (assuming GCC or Clang) to __attribute__(__always_inline__), which will

  1. Always inline the function
  2. give a compile error if that's not possible for technical reasons.
like image 22
rubenvb Avatar answered Jan 18 '23 23:01

rubenvb