Week 8
Labels and Branching
Labels and Branching · Recall Labels
Labels and Branching
Recall Labels
- Labels are used to give meaningful names to locations in memory
- Previously we saw this used to define variables:
Defines “someplace” as a label for a memory location holding a
- But we can also use labels to mark the location of instructions in our programs!
Instructions have addresses too!
- Recall that before a program is executed, it is loaded into memory
- Every instruction therefore occupies a word of memory, and has an address like any other data
- Recall also that this is a core principle of the Von Neumann architecture
- We can therefore use the address of specific instructions to jump from one location to another
- often referred to as branching
The Program Counter
- To understand labels and branching we need to understand how the CPU keeps track of which instruction to execute next
- It uses the special register, the Program Counter (PC) register
Program Counter
The Program Counter (cont)
- After each instruction is executed, the PC register is updated with the address of the next instruction to execute.
- This update is performed by a hardware counter within the ALU
Labels as branch points
To see how labels and branching work, consider this code:
MOV R0, #0
Loop:
ADD R0,R0,#1
B Loop
HALT
Labels as branch points
Consider this code:
MOV R0, #0
Loop: Label referring to the address of the next instruction
ADD R0,R0,#1
B Loop
HALT
Labels as branch points
Consider this code:
MOV R0, #0
Loop: Label referring to the address of the next instruction
ADD R0,R0,#1
B Loop A Branch instruction, telling the program counter that the HALT next instruction to execute is at address of label ‘Loop’
Labels as branch points
Consider this code:
MOV R0, #0
Loop: Label referring to the address of the next instruction
ADD R0,R0,#1
B Loop A Branch instruction, telling the program counter that the HALT next instruction to execute is at address of label ‘Loop’
Let’s load this into ARMliteand see it in action!
Unconditional Branch
B someplace
Branch to the address represented by the label someplace
Unconditional Branch
B someplace This can be any word aligned address, but is almost always given as a label, defined elsewhere in the program Branch to the address represented by the label someplace