Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to force an assembly listing for a specific inlined function, a better way?

Tags:

c++

gcc

I need to be able to look at the assembly output of a specific function using GCC. I use -S, but sometimes if the function is inlined no seperate assembly code for the function is outputted. I don't want to prevent the inlining alltogether, because I'm also doing performance benchmarks, and I want inlining for that.

I am aware of the option -fkeep-inline-functions, but sadly this applies to every function, and I don't want to bloat my assembly output file with thousands of lines of assembly code for the standard library.

I did find out that if you take the address of the function it will not be optimized away from the assembly output. Knowing this I hacked the following macro together:

#define DONT_OPT_OUT_CONCAT1(a, b) DONT_OPT_OUT_CONCAT2(a, b)
#define DONT_OPT_OUT_CONCAT2(a, b) a ## b

#define DONT_OPT_OUT(x) \
    int DONT_OPT_OUT_CONCAT1(DONT_OPT_OUT_BLACK_HOLE, __COUNTER__) = (&x, 0);

Usage:

int f(int x) { return x*x; }
DONT_OPT_OUT(f);

Now, this works, but it has two problems:

  1. It pollutes the global namespace with throwaway variables that may or may not get optimized out.
  2. It does not work for overloaded functions.

Is there any better way?

like image 843
orlp Avatar asked Oct 03 '22 05:10

orlp


1 Answers

From the gcc onlinedocs under Function Attributes:

used

This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.

So one idea you can try is to do something like this:

int __attribute__ ((used)) f(int x) { return x*x; }

Initial testing shows that this seems to work:

g++ -Wall -pedantic -O2 -masm=intel -S example.cpp

; example.S
  .globl    __Z1fi
  .def  __Z1fi; .scl    2;  .type   32; .endef
__Z1fi:
  mov   eax, DWORD PTR [esp+4]
  imul  eax, eax
  ret
like image 164
greatwolf Avatar answered Oct 13 '22 12:10

greatwolf