Commit 458011f21f

joachimschmidt557 <joachim.schmidt557@outlook.com>
2021-01-17 23:09:08
stage2 AArch64: update function prologue and epilogue to include stack offsets
1 parent ea6f3e3
Changed files (1)
src/codegen.zig
@@ -641,20 +641,33 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
                     const cc = self.fn_type.fnCallingConvention();
                     if (cc != .Naked) {
                         // TODO Finish function prologue and epilogue for aarch64.
-                        // Reserve the stack for local variables, etc.
 
                         // stp fp, lr, [sp, #-16]!
+                        // mov fp, sp
+                        // sub sp, sp, #reloc
                         writeInt(u32, try self.code.addManyAsArray(4), Instruction.stp(
                             .x29,
                             .x30,
                             Register.sp,
                             Instruction.LoadStorePairOffset.pre_index(-16),
                         ).toU32());
+                        writeInt(u32, try self.code.addManyAsArray(4), Instruction.add(.x29, .xzr, 0, false).toU32());
+                        const backpatch_reloc = self.code.items.len;
+                        try self.code.resize(backpatch_reloc + 4);
 
                         try self.dbgSetPrologueEnd();
 
                         try self.genBody(self.mod_fn.body);
 
+                        // Backpatch stack offset
+                        const stack_end = self.max_end_stack;
+                        const aligned_stack_end = mem.alignForward(stack_end, self.stack_align);
+                        if (math.cast(u12, aligned_stack_end)) |size| {
+                            writeInt(u32, self.code.items[backpatch_reloc..][0..4], Instruction.sub(.xzr, .xzr, size, false).toU32());
+                        } else |_| {
+                            return self.failSymbol("TODO AArch64: allow larger stacks", .{});
+                        }
+
                         try self.dbgSetEpilogueBegin();
 
                         // exitlude jumps
@@ -690,6 +703,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
                             Register.sp,
                             Instruction.LoadStorePairOffset.post_index(16),
                         ).toU32());
+                        // add sp, sp, #stack_size
+                        writeInt(u32, try self.code.addManyAsArray(4), Instruction.add(.xzr, .xzr, @intCast(u12, aligned_stack_end), false).toU32());
                         // ret lr
                         writeInt(u32, try self.code.addManyAsArray(4), Instruction.ret(null).toU32());
                     } else {