Search code examples
c++cgccinline-assemblycpu-registers

when writing a function in C/C++ that uses inline assembly (x86-64), is it safe to choose any GPRs (rax to r15) when want to?


I'm new to the concept of writing functions that contains inline assembly in C/C++ and I want to know if it's safe to use all of the available general purpose registers. (from rax to r15)

In my knowledge, all of the variables/objects/data are actually stored in the main memory, and it is only loaded in the registers when we are performing operations with it, because of this I assume that it is actually safe to use any of the GP registers with inline assembly inside a function but I'm not sure about it.

I'm worried if it's possible that there might be a case where some registers are still used outside of the function and when that function is invoked those register's value might be overwritten and might case some errors possibly in the program?

Is there any registers that I should avoid when writing inline assembly?


Solution

  • No, it is not correct that "data are actually stored in the main memory, and it is only loaded in the registers when we are performing operations with it". Compilers work very hard to keep data in the registers and only spill to memory if required.

    You have to tell the compiler about all the registers you use in the inline assembly, so it can ensure that they are available for you. None of the registers are available to use freely.

    To indicate to the compiler that you are modifying the contents of registers, you list them as outputs or in the clobber list.