tuanp.dev

Part 4 of 20 · about an hour

A CPU that can repeat itself

This is the part where a calculator turns into a computer. It is also the part with the strangest idea so far, a byte that means a negative number. If it does not click on first reading, run the broken version below, look at where the program lands, and read the section once more. It clicks on the second pass for most people, me included.

Last time our processor got a memory and learned to store into it. But a program still runs once, top to bottom. The last exercise asked for a program that fills five slots: that takes 18 bytes, and two hundred slots would take 603. Today the processor learns to go back and do something again.

By the end of this part

  • Your processor remembers whether the last result was zero.
  • It can jump backwards in its program depending on that, which makes a loop.
  • It prints a line for every instruction it runs, so you can watch it think.

A program that counts to three

Here is the program we want to run today. On the left is where each instruction sits in memory.

8000  A2 00    LDX #$00     put 0 into X
8002  E8       INX          add one to X
8003  E0 03    CPX #$03     is X equal to 3?
8005  D0 FB    BNE $8002    if not, go back to $8002
8007  00       BRK          stop

LDX is easy: it is LDA for the X register. The other two new opcodes raise three questions, and the rest of this part answers them in order:

  1. CPX asks a question and BNE, a separate instruction, acts on the answer. Where is the answer kept in between?
  2. How does a program "go back"?
  3. The instruction says go back to $8002, but its second byte is FB. Where is the address?

A. Where the answer is kept

Besides its registers, the processor has a handful of single bits that it updates as a side effect of other work. Each one is called a flag. What is a flag? A flag is one bit inside the processor that records a yes-or-no fact about the last result.

The one we need is the zero flag, written Z. Whenever an instruction puts a value into a register, Z is set to 1 if that value was zero, and to 0 otherwise. CPX uses the same flag: it subtracts its number from X, throws the answer away, and keeps only the fact "was that zero?". If X minus 3 is zero, X is 3.

In Rust a yes-or-no value has the type bool, and its two values are true and false. So Z becomes a new field:

src/main.rsSnapshot
struct Cpu {
    a: u8,
    x: u8,
    pc: u16,
    zero: bool,
    memory: [u8; 0x10000],
}

impl Cpu {
    fn new() -> Cpu {
        Cpu { a: 0, x: 0, pc: 0x8000, zero: false, memory: [0; 0x10000] }
    }

And every instruction that changes a register gets one more line. The comparison self.x == 0 produces a bool, which is exactly what the field wants:

                0xE8 => {
                    // INX: add one to X
                    self.x = self.x.wrapping_add(1);
                    self.zero = self.x == 0;
                }
                0xE0 => {
                    // CPX: compare X with the next byte
                    let value = self.fetch();
                    self.zero = self.x == value;
                }

INX has grown from one line to a block in braces, because it now does two things.

B. How a program goes back

You already know everything needed. The processor always reads its next instruction from wherever pc points. So to go back, an instruction only has to put a smaller address into pc.

An instruction that does this depending on a flag is called a branch. What is a branch? A branch is an instruction that changes pc, but only if a flag has a certain value. BNE stands for "branch if not equal": it changes pc if Z is 0, and does nothing if Z is 1.

C. Where the address went

A branch does not carry an address. To save a byte, it carries a distance: how far to move pc from where it is now. So let us try the obvious thing and add that byte to pc:

first attemptSnapshot
                0xD0 => {
                    // BNE: branch if the last result was not zero
                    let offset = self.fetch();
                    if !self.zero {
                        self.pc = self.pc + offset as u16;
                    }
                }

To see what happens we will also make the processor print one line per instruction, just before it runs it: the address, the opcode, and the registers and flag at that moment. This goes at the top of the loop:

        loop {
            println!(
                "{:04X}  {:02X}  A={:02X} X={:02X} Z={}",
                self.pc, self.read(self.pc), self.a, self.x, self.zero as u8
            );
            let opcode = self.fetch();

({:04X} prints four hex digits. self.zero as u8 turns false and true into 0 and 1.) A printout like this is called a trace, and it is the emulator builder's best friend. Run the first attempt:

$ cargo run -q
8000  A2  A=00 X=00 Z=0
8002  E8  A=00 X=00 Z=1
8003  E0  A=00 X=01 Z=0
8005  D0  A=00 X=01 Z=0
8102  00  A=00 X=01 Z=0
A = $00  X = $01

Read it line by line. It starts well. Then, after the D0 at $8005, the next instruction comes from $8102. The branch did not go back five bytes. It went forward 251, landed in empty memory, found a 00 and stopped.

$FB is 251. How can 251 mean "back five"?

Remember Part 2: a byte wraps. Start at 5 and add 251, and you get 256, which wraps to 0. So within one byte, adding 251 has the same effect as subtracting 5. The 6502's designers used this. In a branch, the bytes $00 to $7F mean forward 0 to 127, and the bytes $80 to $FF mean backward: $FF is −1, $FE is −2, and $FB is −5.

This way of reading a byte is called two's complement. What is two's complement? Two's complement is a way of reading a byte in which the top half of its values, $80 to $FF, stand for the negative numbers −128 to −1.

A table with three columns: the byte, its value read as a u8, and its value read as an i8. 00 is 0 and 0. 01 is 1 and 1. 7F is 127 and 127. 80 is 128 and minus 128. FB is 251 and minus 5. FF is 255 and minus 1.the byteread as u8read as i8$0000$0111$7F127127$80128−128$FB251−5$FF255−1same upto heredifferentfrom $80
The eight bits never change. Only the way we agree to read them does.

Rust has a type for each reading. u8 is a byte read as 0 to 255. i8 is the same eight bits read as −128 to 127 (the "i" is for integer, meaning it may be negative). Converting with as i8 does not change any bits; it changes which column of the table you are in.

Eight memory boxes from address 8000 to 8007 holding A2, 00, E8, E0, 03, D0, FB, 00. The pc arrow is at 8007, just past the FB. A curved arrow labelled minus five leads from there back to 8002.80008001800280038004800580068007A200E8E003D0FB00pc−5
The distance is counted from where pc is after the whole branch instruction has been read: $8007 − 5 = $8002.

So the fix is to read the byte as an i8 and add that to pc:

                0xD0 => {
                    // BNE: branch if the last result was not zero
                    let offset = self.fetch() as i8;
                    if !self.zero {
                        self.pc = self.pc.wrapping_add_signed(offset as i16);
                    }
                }
  • self.fetch() as i8 reads the distance as a signed number.
  • if !self.zero { … }: the ! means "not". In Rust the condition has no brackets round it, and the braces are required.
  • wrapping_add_signed adds a possibly negative number to an unsigned one. Its argument must be 16 bits wide like pc, so we widen the distance with as i16, which keeps −5 as −5.

Watch it loop

The pc arrow moves along the eight program bytes, and jumps back from the end of the BNE instruction to address 8002 twice. X counts 1, 2, 3. On the third lap the Z flag becomes 1 and pc moves on to the BRK.80008001800280038004800580068007A200E8E003D0FB00pcbefore the loopX00Z0
0xE8 => {  // INX
    self.x = self.x.wrapping_add(1);
    self.zero = self.x == 0;
}
0xE0 => {  // CPX
    let value = self.fetch();
    self.zero = self.x == value;
}
0xD0 => {  // BNE
    let offset = self.fetch() as i8;
    if !self.zero { /* move pc by offset */ }
}
  1. The start. pc is $8000, X is 0, and Z is 0.
  2. A2 00, LDX: X is loaded with 0. The value loaded was zero, so Z becomes 1. Nobody is looking at Z yet.
  3. E8, INX: X becomes 1. That is not zero, so Z goes back to 0.
  4. E0 03, CPX: is X equal to 3? 1 is not 3, so Z stays 0.
  5. D0 FB, BNE. After reading both bytes pc is $8007. Z is 0, so we branch: pc moves back 5 to $8002.
  6. Lap 2 runs the same three instructions: X becomes 2, 2 is not 3, and the branch sends pc back to $8002 again.
  7. Lap 3. INX makes X = 3. Now CPX finds that X is equal to 3, and Z becomes 1.
  8. BNE again, but this time Z is 1, so it does nothing. pc simply carries on to $8007.
  9. 00, BRK. The loop ran three times and X holds 3.

The whole run method

Here is run with everything in place. Besides the three new opcodes, LDA and TAX have each grown a line to keep Z up to date.

    fn run(&mut self) {
        loop {
            println!(
                "{:04X}  {:02X}  A={:02X} X={:02X} Z={}",
                self.pc, self.read(self.pc), self.a, self.x, self.zero as u8
            );
            let opcode = self.fetch();

            match opcode {
                0xA9 => {
                    // LDA: load the next byte into A
                    self.a = self.fetch();
                    self.zero = self.a == 0;
                }
                0xA2 => {
                    // LDX: load the next byte into X
                    self.x = self.fetch();
                    self.zero = self.x == 0;
                }
                0x8D => {
                    // STA: store A at the address that follows
                    let addr = self.fetch_addr();
                    self.write(addr, self.a);
                }
                0xAA => {
                    // TAX: copy A into X
                    self.x = self.a;
                    self.zero = self.x == 0;
                }
                0xE8 => {
                    // INX: add one to X
                    self.x = self.x.wrapping_add(1);
                    self.zero = self.x == 0;
                }
                0xE0 => {
                    // CPX: compare X with the next byte
                    let value = self.fetch();
                    self.zero = self.x == value;
                }
                0xD0 => {
                    // BNE: branch if the last result was not zero
                    let offset = self.fetch() as i8;
                    if !self.zero {
                        self.pc = self.pc.wrapping_add_signed(offset as i16);
                    }
                }
                0x00 => break, // BRK: stop
                _ => panic!("unknown opcode ${:02X}", opcode),
            }
        }
    }

Put today's program in main (the snapshot has it with comments) and run:

$ cargo run -q
8000  A2  A=00 X=00 Z=0
8002  E8  A=00 X=00 Z=1
8003  E0  A=00 X=01 Z=0
8005  D0  A=00 X=01 Z=0
8002  E8  A=00 X=01 Z=0
8003  E0  A=00 X=02 Z=0
8005  D0  A=00 X=02 Z=0
8002  E8  A=00 X=02 Z=0
8003  E0  A=00 X=03 Z=0
8005  D0  A=00 X=03 Z=1
8007  00  A=00 X=03 Z=1
A = $00  X = $03

Look down the first column: 8002, 8003, 8005, three times over. Your processor is running a loop. Eight bytes of program, and it would be the same eight bytes for a count of two hundred.

Shortcuts we took on purpose

  • A real 6502 has seven flags, packed together into one register called P. We have one, as a separate bool. Left open; our cartridge only needs Z.
  • A real CPX also updates two other flags. Left open, for the same reason.
  • The trace is always on. Fixed in Part 7, where we give it a switch.

What changed today

  • The Cpu has a zero flag, updated by every instruction that changes a register.
  • New opcodes: LDX ($A2), CPX ($E0) and the branch BNE ($D0).
  • A branch distance is read as an i8, so it can point backwards.
  • run prints a trace line before each instruction.

Now you

  1. On paper: what byte follows D0 to branch back 3 bytes? Forward 4 bytes? Back 128?
    HintGoing backwards, count down from $00 with wrapping: −1 is $FF, −2 is $FE, and so on.
  2. Add DEX ($CA, subtract one from X, updating Z) if you have not yet. Then work out by hand what A2 05 CA D0 FD 00 does, and check it with the trace. Why does this loop need no CPX?
  3. Add BEQ ($F0), "branch if equal": the opposite of BNE. It is one character different.
  4. Our loop goes round three times and does the same thing each time. Suppose lap one should write to $0200, lap two to $0201 and lap three to $0202. Which register already holds a different number on each lap? How might a STA make use of it? Think about it before Part 5.
  5. From blank: this time, start by writing the trace line, and add opcodes one at a time, running after each.

Check your understanding

  1. What is a flag?
    AnswerOne bit inside the processor that records a yes-or-no fact about the last result.
  2. What is a branch?
    AnswerAn instruction that changes pc, but only if a flag has a certain value.
  3. What is two's complement?
    AnswerA way of reading a byte in which the values $80 to $FF stand for the negative numbers −128 to −1.
  4. What is the difference between u8 and i8?
    AnswerBoth are eight bits. u8 reads them as 0 to 255; i8 reads them as −128 to 127.
  5. A branch distance is counted from where?
    AnswerFrom pc after the whole branch instruction, both bytes, has been read.

Next time

Right now the loop can count, but every lap touches the same places. In Part 5 the count itself becomes part of an address, so that each lap works on the next byte of a list.