A cheatsheet for Hack's memory layout




About

Use the navigation bar to jump to a section of interest



Preamble

The memory structure shown in these diagrams is imposed only when using the high level and virtual machine languages

Otherwise, code written completely in assembly can safely ignore the structure and read or write wherever it wants. The only caveat is the section allocated for IO use. Although the assembly code can write here, values written will be reflected in an output device or overwritten by an input device



Memory Sections

TECS Layout

address
content
description
0
SP
Stack pointer. Points to the top of the stack
1
LCL
Points to the local segment of the current function
2
ARG
Points to the argument segment of the current function
3
THIS
Points to the base address of the current class instance
4
THAT
Points to a location in the current array
5
...
TEMP
TEMP 0 is reserved1. The rest are available for use
12
13
14
GP
Reserved1
15
16
...
STATIC
Holds the static variables of the classes used by the running program
255
256
...
STACK
Holds data used by subroutines in the calling chain. See stack
2047
2048
...
HEAP
Holds arrays and class instances
16383
16384
...
Screen
Holds memory allocated for DMA by the screen
24575
24576
Keyboard
Holds memory allocated for DMA by the keyboard
24577
...
Unused
65535


Notes

1Reserved for use by code generated by HL and ASM compilers



Stack
address
content
description
256
...
Data of all the subroutines that are up the calling chain
 
ARG  
argument 0
...
Arguments given for the current subroutine
argument n
saved return address
saved LCL pointer
saved ARG pointer
The caller's state is saved so that it can be restored when we return from the current subroutine
saved THIS pointer
saved THAT pointer
LCL  
local 0
...
Local variables (var) declared by the current subroutine
local n
SP  
...
The rest of the stack
2047