Code Generation

First, we need to understand how and where variables are stored in memory, because that is a large part of how we generate code for them.

Where are Variables Stored?

Local variables are stored in the function’s stack frame

  • The typical addressing mode is [SP, #pimm]

Global variables are stored at locations named by labels

  • The typical addressing mode is label
  • Need to use ADRP and ADR instructions to reach the address

Code Generation for Basic Types

C Source CodeTypeA64 Assembly Code
int x, y, z *wNAx is in memory at [sp, #24], y @ [sp, #20], z @ [sp, #16], w @ [sp #8]
x = 2intmov w9, #2 str w9, [sp, #24]
y=xintldr w9, [sp, #24 str w9, [sp, #20]
x++intldr w9, [sp, #24] add w9, w9, #1 str w9, [sp, #24]
y -= xintldr w10, [sp, #24] ldr w9, [sp, #20] subs w9, w9, w10 str w9, [sp, #20]
z = x + y - 4intldr w10, [sp, #24] ldr w9, [sp, #20] add w9, w9, w10 subs w9, w9, #4 str w9, [sp, #16]
w = &xint*add x8, sp, #24 str x8, [sp, #8]
z = *wintldr x10, [sp, #8] // load W ldr w9, [x10] // load X str w9, [sp, #16] // store in Z
unsigned i, int *Ei @ [sp #60] E @ [sp, #48]
int x = E[i]ldr x8, [sp, #48] ldr w9, [sp, #60] ldr w8, [x8, x9,