- Published on
nand2tetris系列01-实现无限循环汇编程序
- Authors

- Name
- Morphy Chan
hack computer是nand2tetris课程实现的一台伪机器(pseudo-machine),包含了相应的指令集和配套软件。本文介绍如何用hack computer汇编实现一个无限循环程序。
无限循环的程序如下,参考1。
(END)
@END
0;JMP // Unconditional jump
程序很简洁,包含1个符号(symbol)和2条指令。
- 首先,
(END)是一个符号(symbol),在汇编中经常见到。跳转指令(JMP)需要指定下一条执行指令的地址,但是具体的地址并不知道,因此需要借助符号来标记地址:
Label symbols: These user-defined symbols, which serve to label destinations of goto commands, are declared by the pseudo-command ''(Xxx)''. This directive defines the symbol Xxx to refer to the instruction memory location holding the next command in the program.
(END)指向的是紧跟在该符号之后的下一条指令的地址,这里就是@END指令的地址。
- 接下来是
@END指令
The A-instruction is used to set the A register to a 15-bit value... @value: Where value is either a non-negative decimal number or a symbol referring to such number
@指定A register的值,这里的值是符号END,根据上面对符号的解释,实际上这里将A寄存器的值设置为本条指令自身的地址。
- 最后是
JMP跳转指令,跳转指令就是跳转到下一条指令的地址
The jump field of the C-instruction tells the computer what to do next. There are two possibilities: The computer should either fetch and execute the next instruction in the program, which is the default, or it should fetch and exe- cute an instruction located elsewhere in the program. In the latter case, we assume that the A register has been previously set to the address to which we have to jump.
JMP总是跳转到A register的地址,由于上一条指令指定了A register的值为@END指令的地址,所以JMP总是会跳转到@END指令,因此实现了无限循环。
nand2tetris提供了可以执行hack computer汇编程序的CPU模拟器,运行程序。
图1:nand2tetris实现无限循环
一些说明:
- 在程序加载并执行以后,已经没有符号了。符号
(END)被替换为其下一条指令实际的地址,这里@END指令的地址为0,所以(END)被替换为了0 @0总是指定A寄存器的值为0,A寄存器的值没有改变JMP总是跳转到地址为0的指令,进而程序计数器(PC)一直在循环执行地址为0和1的2条指令