Search code examples
gccinterruptriscv

gcc: how to save all used register on function entry


This is regarding gcc used for RISC-V, but it probably also applies to other targets.

If I declare a function as ISR using __attribute__((interrupt)), gcc automatically saves and restores all used registers by the ISR. GCC will also generate a return-from-interrupt instruction (mret) at the end of the function instead of a regular function return (ret).

Is it possible to instruct gcc to save all used registers just like with an ISR, but instead of generating an mret instruction it should generate a regular ret?


Solution

  • There is no builtin support for this in GCC. Typically this is resolved by making a small trampoline stub which saves all caller-saved registers and then calls the real function normally.

    Or, if the only needed change is replacing mret with ret, you could simply postprocess generated assembly code:

    $ gcc file.c -S -o file.s
    $ sed -i -e 's/\bmret\b/ret/'