https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103882
Bug ID: 103882 Summary: Register corruption in ASM only functions when optization is -O2/-Os/-O3 Product: gcc Version: 10.3.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: target Assignee: unassigned at gcc dot gnu.org Reporter: krystalgamer at protonmail dot com Target Milestone: --- Host: x86_64-linux-gnu Target: mips-linux-gnu Build: x86_64-linux-gnu When a function is only composed of an `asm` statement if the optimizations are at least -O2 it will make it assume none of the registers will be tainted. Example code: ``` int is_first_char_a(const char *f){ return f[0] == 'a'; } void fail(){ asm __volatile__ ( "li $a0, 0x60606060\n" ); } int example(char *c){ fail(); return is_first_char_a(c); } void __start(){} ``` Compiled with `-nostdlib -O1`, generates the following code: ``` 00400180 <example>: 400180: 27bdffe0 addiu sp,sp,-32 400184: afbf001c sw ra,28(sp) 400188: afb00018 sw s0,24(sp) 40018c: 00808025 move s0,a0 400190: 0c10005d jal 400174 <fail> 400194: 00000000 nop 400198: 82020000 lb v0,0(s0) 40019c: 38420061 xori v0,v0,0x61 4001a0: 2c420001 sltiu v0,v0,1 4001a4: 8fbf001c lw ra,28(sp) 4001a8: 8fb00018 lw s0,24(sp) 4001ac: 03e00008 jr ra 4001b0: 27bd0020 addiu sp,sp,32 ``` Compiled with `-nostdlib -O2`, generates the following code: ``` 00400180 <example>: 400180: 3c046060 lui a0,0x6060 400184: 34846060 ori a0,a0,0x6060 400188: 80820000 lb v0,0(a0) 40018c: 38420061 xori v0,v0,0x61 400190: 03e00008 jr ra 400194: 2c420001 sltiu v0,v0,1 ``` As can be seen before -O1 levels of optimization the compiler saves $a0 in $s0 and then restores it. -O2 level and beyond causes the compiler to assume that a0 is preserved. >From what I can tell this might be because the optimizer doesn't take into consideration ASM statements(which is good), but it makes wrong assumptions. A possible solution would be to save the caller-saved registers whenever a function with an ASM statement is called.