|
|
Subscribe / Log in / New account

A guide to inline assembly code in GCC

A guide to inline assembly code in GCC

Posted May 2, 2016 18:03 UTC (Mon) by gutschke (subscriber, #27910)
Parent article: A guide to inline assembly code in GCC

While the article provides a good high-level overview, it skips a couple of the details that are needed in real-life programming. It's been a while since I had to write assembly, so I have probably forgotten a lot of the details that caused me confusion.

The two issues the I do recall are 1) how to deal with register constraints that don't have an architecture-specific register name, and 2) how to deal with more than 10 input/output constraints.

The former can be solved by assigning variables to named registers; here is an example of what you would do, if you needed an input to be in %r10:

int main() {
  register int a __asm__("r10") = 5;
  int b;
  __asm__("movl %1, %0" : "=r"(b) : "r"(a));
  return b;
}

And the best solution for providing more than 10 parameters is to place them into a temporarily allocated struct on the stack. This can be a little ugly, as you often have to hard-code offsets into the structure, and it can also result in slightly less efficient code. But in practice that often doesn't matter too horribly.

Finally, specifying correct clobber constraints can be surprisingly counter-intuitive unless you have a really firm grasp of the C language standard. If in doubt, it is always safe to mark the __asm__ statement as volatile and to state that is clobbers memory. This results in slightly less efficient code, but it is a lot more likely that the optimizer doesn't interfere in ways that the programmer didn't anticipate.


to post comments

A guide to inline assembly code in GCC

Posted May 3, 2016 1:43 UTC (Tue) by pbonzini (subscriber, #60935) [Link] (1 responses)

GCC now has named asm operands, they can be used to bypass the 10 operand limit.

A guide to inline assembly code in GCC

Posted May 3, 2016 1:49 UTC (Tue) by gutschke (subscriber, #27910) [Link]

That's awesome news. Can't wait for this feature being universally available in the majority of compilers that people actually use.

Named parameters are going to make the code much more readable too.


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds