🡄 Previous

Next 🡆

Contents > General-purpose Computer > Assembly Language

Branch Instructions

A branch instruction redirects execution to a specified location, either conditionally or unconditionally. With one exception, the branch instructions have the following format.

mnemonic label

A label is a placeholder for an address. In this case, it is the address of the code to run if the branch is taken.

A label declaration consists of a unique name followed by a colon, as shown below.

name:

The declaration appears immediately before target code or data, and the assembler resolves its address based on its position.

Here are all the branch instructions:

InstructionNamePseudocodeOpcode
JMP labelJumpP = label;20
BNE labelBranch Not Equalif (z == 0) P = label;22
BEQ labelBranch Equalif (z == 1) P = label;23
BPL labelBranch Plusif (n == 0) P = label;24
BMI labelBranch Minusif (n == 1) P = label;25
JSR labelJump SubroutineR = P; P = label;28
RTSReturn SubroutineP = R;70

RTS is a 1-byte instruction. The rest are 3-byte instructions consisting of an opcode followed by a big-endian address. The opcode comprises bits 0010rstu, where only one of r, s, and t are set, and u is a value compared to s or t:

Set BitInstructionsDescription
rJSRThe computer copies the program counter, P, to the return register, R, and it branches.
sBPL,BMIThe computer branches iff the negative flag, n, equals bit u.
tBNE,BEQThe computer branches iff the zero flag, z, equals bit u.

JSR supports only leaf subroutines since the computer does not provide a native call stack.

A program can use the conditional branch instructions as relational operators by branching on the result of A - B. However, BPL and BMI treat the difference as a signed number. This leads to the following limitations.

InstructionRelationLimitations
BNEA ≠ Bnone
BEQA = Bnone
BPLA ≥ BA - B ∊ [0, 127]
BMIA < BA - B ∊ [-128, -1]

While there is no indirect branch instruction, a program can employ self-modifying code to alter a branch target at runtime.

By default, the computer initializes all registers to 0 at startup. However, a program can declare an entry point with a label named main. If present, the computer initializes P to its address.

🡄 Previous

Next 🡆