Context switch using arm inline assembly


I have another question about an inline assembly instruction concerning a context switching. This code may work but I'm not sure at 100% so I submit this code to the pros of stackoverflow ;-)

I'm compiling using gcc (no optimization) for an arm7TDMI. At some point, the code must do a context switching.

/* Software Interrupt */
/* we must save lr in case it is called from SVC mode */
#define ngARMSwi(code) __asm__("SWI %0" : : "I"(code) : "lr")
// Note : code = 0x23 

When I check the compiled code, I get this result :

svc 0x00000023

The person before me who coded this wrote "we must save lr" but in the compiled code, I don't see any traces of lr being saved.

The reason I think that code could be wrong is that the program run for some time before going into a reset exception and one of the last thing the code execute is a context switch...

asked on Stack Overflow Mar 27, 2012 by Martin Allard

2 Answers


The __asm__ statement lists lr as a clobbered register. This means that the compiler will save the register if it needs to.

As you're not seeing any save, I think you can assume the compiler was not using that register (in your testcase, at least).

answered on Stack Overflow Mar 27, 2012 by ams

I think that SWI instruction should be called in the user mode. if this is right. The mode of ARM is switched to SVC mode after this instruction. then the ARM core does the copy operation that the CPSR is copied into SPSR_svc and LR is copied into LR_svc. this should be used for saving the user mode cpu's context to return from svc mode. if your svc exception handler use lr like calling another function the lr register should be required to be preserved like using stack between the change of the mode. i guess the person before you wrote like that to talk about this situation.

answered on Stack Overflow Aug 25, 2016 by attila • edited Aug 25, 2016 by attila

User contributions licensed under CC BY-SA 3.0