lllllllllllll
lllllllllllll

Reputation: 9110

GCC Assembly Inline: Function Body with Only Inlined Assembly Code

I am trying to reuse some assembly code in my C project. Suppose I have a sequence of instructions, and I would like to organize them as a function:

void foo() {
  __asm__ (
   "mov %eax, %ebx"
   "push %eax"
   ...
   );
}

However, one obstacle is that in the compiled assembly code of function foo, besides the inlined assembly code, compiler would also generate some prologue instructions for this function, and the whole assembly program would become something like:

foo:
   push %ebp          <---- routine code generated by compilers
   mov  %ebp, %esp    <---- routine code generated by compilers
   mov %eax, %ebx
   push %eax

Given my usage scenario, such routine code actually breaks the original semantics of the inlined assembly.

So here is my question, is there any way that I can prevent compiler from generating those function prologue and epilogue instructions, and only include the inlined assembly code?

Upvotes: 3

Views: 4539

Answers (2)

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

You mention that you use gcc for compiling. In this case you can use -O2 optimization level. This will cause the compiler to do stack optimization and if your inline assembly is simple, it won't insert the prologue and epilogue. Although, this might not be guaranteed in every case because optimizations keep changing. (My gcc with -O2 does it).

Another option is that you can put the entire function (including the foo:) inside an assembly block as

__asm__ (
    "foo:\n"
    "mov ..."
);

With this option you need to know the name mangling specifications if any. You will also have to add .globl foo before the function start if you want the function to be non static.

Lastly you can check the gcc __attribute__ ((naked)) attribute on the function declaration. But as mentioned by MichaelPetch, this is not available for the X86 target.

Upvotes: 5

Chris Dodd
Chris Dodd

Reputation: 126130

The whole point of inline asm code is to interface with the C compiler's scheduler and register allocator in a sane way, by giving you a way to specify how to hook up the assembly code to the compiler's constraint solving machinery. That's why it rarely makes sense to have inline asm code with specific registers in it; you instead want to use constraints to allocate some registers and have the compiler tell you what they are.

If you really want to write stand-alone asm code that communicates with the rest of you program by the system ABI, write that code in a separate .s (or .S) file that you include in your project, rather than trying to use inline asm code.

Upvotes: 2

Related Questions