@@ -110,9 +110,11 @@ void update_elf_offset(ph2_ir_t *ph2_ir)
110
110
void cfg_flatten (void )
111
111
{
112
112
func_t * func = find_func ("__syscall" );
113
- func -> bbs -> elf_offset = 48 ; /* offset of start + exit in codegen */
113
+ /* Prologue ~ 6 instructions (24 bytes). Place __syscall right after. */
114
+ func -> bbs -> elf_offset = 24 ;
114
115
115
- elf_offset = 84 ; /* offset of start + exit + syscall in codegen */
116
+ /* Reserve space for prologue (24) + syscall trampoline (36) = 60 bytes. */
117
+ elf_offset = 60 ;
116
118
GLOBAL_FUNC -> bbs -> elf_offset = elf_offset ;
117
119
118
120
for (ph2_ir_t * ph2_ir = GLOBAL_FUNC -> bbs -> ph2_ir_list .head ; ph2_ir ;
@@ -437,24 +439,17 @@ void emit_ph2_ir(ph2_ir_t *ph2_ir)
437
439
void code_generate (void )
438
440
{
439
441
elf_data_start = elf_code_start + elf_offset ;
442
+ func_t * func ;
440
443
441
- /* start */
444
+ /* start: save original sp in s0; allocate global stack; run init */
445
+ emit (__addi (__s0 , __sp , 0 ));
442
446
emit (__lui (__t0 , rv_hi (GLOBAL_FUNC -> stack_size )));
443
447
emit (__addi (__t0 , __t0 , rv_lo (GLOBAL_FUNC -> stack_size )));
444
448
emit (__sub (__sp , __sp , __t0 ));
445
- emit (__addi (__gp , __sp , 0 ));
449
+ emit (__addi (__gp , __sp , 0 )); /* Set up global pointer */
446
450
emit (__jal (__ra , GLOBAL_FUNC -> bbs -> elf_offset - elf_code -> size ));
447
451
448
- /* exit */
449
- emit (__lui (__t0 , rv_hi (GLOBAL_FUNC -> stack_size )));
450
- emit (__addi (__t0 , __t0 , rv_lo (GLOBAL_FUNC -> stack_size )));
451
- emit (__add (__gp , __gp , __t0 ));
452
- emit (__addi (__sp , __gp , 0 ));
453
- emit (__addi (__a0 , __a0 , 0 ));
454
- emit (__addi (__a7 , __zero , 93 ));
455
- emit (__ecall ());
456
-
457
- /* syscall */
452
+ /* syscall trampoline for __syscall - must be at offset 24 */
458
453
emit (__addi (__a7 , __a0 , 0 ));
459
454
emit (__addi (__a0 , __a1 , 0 ));
460
455
emit (__addi (__a1 , __a2 , 0 ));
@@ -471,12 +466,15 @@ void code_generate(void)
471
466
emit_ph2_ir (ph2_ir );
472
467
473
468
/* prepare 'argc' and 'argv', then proceed to 'main' function */
474
- emit (__lui (__t0 , rv_hi (GLOBAL_FUNC -> stack_size )));
475
- emit (__addi (__t0 , __t0 , rv_lo (GLOBAL_FUNC -> stack_size )));
476
- emit (__add (__t0 , __gp , __t0 ));
469
+ /* use original sp saved in s0 to get argc/argv */
470
+ emit (__addi (__t0 , __s0 , 0 ));
477
471
emit (__lw (__a0 , __t0 , 0 ));
478
472
emit (__addi (__a1 , __t0 , 4 ));
479
- emit (__jal (__zero , MAIN_BB -> elf_offset - elf_code -> size ));
473
+ emit (__jal (__ra , MAIN_BB -> elf_offset - elf_code -> size ));
474
+
475
+ /* exit with main's return value in a0 */
476
+ emit (__addi (__a7 , __zero , 93 ));
477
+ emit (__ecall ());
480
478
481
479
for (int i = 0 ; i < ph2_ir_idx ; i ++ ) {
482
480
ph2_ir = PH2_IR_FLATTEN [i ];
0 commit comments