0

Env: i386 32-bit Assembly: AT&T OS: Linux

I just want to ask that is there any rule on the sequence of using %eax, %edx, %ecx register when you use them with in the same function frame.

As my observation, they often showed up on my environment with the sequence of %ecx, %edx and then %eax to store the local variables or other temporary variables.

Thanks to you all.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Edee
  • 1,746
  • 2
  • 6
  • 14
  • 2
    There is no such rule. However, keep in mind that some registers are *callee-saved* and must be restored to their original values on exit from the function. On i386 Linux, these are `rbx`, `rsi`, `rdi`, `rsp`, and `rbp`; the floating point stack must be empty, too (except if you return a floating point number that is). – fuz Jul 14 '20 at 09:39
  • got it, thank you. – Edee Jul 14 '20 at 09:40
  • Refer to the i386 SysV ABI for further reading. That documents specifies all rules you need to obey when writing i386 assembly functions for Linux. – fuz Jul 14 '20 at 09:40
  • 2
    @fuz You mean `ebx`, `esi`, `edi`, `esp` and `rbp`? I don't think 64-bit registers are available on the 80386. – fcdt Jul 14 '20 at 09:54
  • @fcdt Yes, indeed. Brainfart... – fuz Jul 14 '20 at 09:54
  • 1
    @fcdt You mean `ebp`? I don't think 64-bit registers are available on the 80386. ;-) – Tommylee2k Jul 14 '20 at 10:28

1 Answers1

4

As mentioned in the comments, is has to do with the i386 System V ABI (more links in the x86 tag wiki):

eax, ecx and edx are scratch registers, they don't have to be preserved across function calls. All other 32-bit general-purpose registers must be saved on the stack, which costs additional instructions.

Therefore it is best to initially use eax, ecx and edx first in the same function and only afterwards ebx, esi, edi, esp and ebp.

(I have omitted the percent signs here for the sake of legibility)

fcdt
  • 2,371
  • 5
  • 14
  • 26
  • 1
    Re: omitting the `%` signs: the register names don't contain `%`. AT&T syntax uses `%` decorations on reg names to avoid ambiguity between register names and symbol names, but that doesn't mean the decoration is part of the register name proper. e.g. in GNU C inline asm, the clobber list can just use `"eax"` (or GCC accepts `"%eax"` there as well.) – Peter Cordes Jul 14 '20 at 10:46
  • Thanks for the note. They were included in the ABI document so I assumed that (normally I only work with intel syntax). – fcdt Jul 14 '20 at 10:49
  • 1
    This is almost a duplicate of [What registers must be preserved by an x86 function?](https://stackoverflow.com/q/9603003), but I guess pointing out explicitly that using call-clobbered registers saves work doing save/restore is the real crux of the answer, so +1. (Fun fact: all mainstream 32-bit x86 function-calling conventions agree on EAX, ECX, and EDX being call-clobbered, with the rest being call-preserved.) – Peter Cordes Jul 14 '20 at 10:52