# CS152 Lecture 2: Microcoding ### Section 1: ISA vs. Microarchitecture and Why Learn Microprogramming Looking across all implemented machines gives a five-stage timeline: 1. **Fixed function** (abacus, compass) 2. **Semi-programmable, no branches** (calculators) 3. **Programmable, not easily re-programmed** (ENIAC) 4. **Stored program** (Turing Machine, EDVAC, EDSAC) 5. **Stored program + ISA decoupled from implementation** (IBM 360) While ISAs are typically paired with specific microarchitectural styles—Accumulator $\Rightarrow$ hardwired unpipelined; CISC $\Rightarrow$ microcoded; RISC $\Rightarrow$ hardwired pipelined; VLIW $\Rightarrow$ fixed-latency parallel pipelines; JVM $\Rightarrow$ software interpretation—**any ISA can be implemented with any style** (e.g., Intel Ivy Bridge uses a hardwired pipelined x86 core with microcode support; Apple M1 uses native ARM hardware to emulate x86 in software; Spike interprets RISC-V in software; ARM Jazelle executes JVM in hardware). To understand how hardware executes an ISA from the ground up, we will build a **microcoded RISC-V machine**. Learning microprogramming shows how to build very small processors even for complex ISAs, explains where CISC machines came from, remains relevant inside modern x86/IBM/PowerPC CPUs, and exposes the exact tradeoffs that later drove the shift to RISC. --- ### Section 2: The RISC-V Instruction Set Architecture and Binary Formats To build a microcoded RISC-V processor, we first specify the exact **RV32I** ISA contract our hardware must implement. **RISC-V** is an open, clean fifth-generation RISC ISA developed at UC Berkeley (supporting 32-bit `RV32` and 64-bit `RV64` variants) that is not over-architected for one implementation style. For our base 32-bit integer subset (**RV32I**), the programmer-visible **Processor State** consists of: * **Program counter (`pc`)**: a 32-bit register holding the byte address of the current instruction. * **32 integer registers (`x0`–`x31`)**, each 32 bits wide (`XLEN = 32`), where **`x0` (`zero`) is hardwired to `0`** (writes to `x0` are ignored). #### Instruction Encoding and Formats RISC-V supports variable-length instructions cleanly in byte-addressed memory: 16-bit compressed instructions have lowest two bits `aa` $\neq 11_2$, while **32-bit base RV32I instructions always have lowest two bits $= 11_2$** (with bits `[4:2]` $\neq 111_2$). Even in RV32I where all instructions are 32 bits wide, **all branches and jumps specify targets at 16-bit (2-byte) granularity** to remain compatible with 16-bit compressed code. Every 32-bit RV32I instruction uses one of six formats (MSB bit `31` on the left, LSB bit `0` on the right): 1. **R-type:** `funct7 [31:25]` | `rs2 [24:20]` | `rs1 [19:15]` | `funct3 [14:12]` | `rd [11:7]` | `opcode [6:0]` 2. **I-type:** `imm[11:0] [31:20]` | `rs1 [19:15]` | `funct3 [14:12]` | `rd [11:7]` | `opcode [6:0]` 3. **S-type:** `imm[11:5] [31:25]` | `rs2 [24:20]` | `rs1 [19:15]` | `funct3 [14:12]` | `imm[4:0] [11:7]` | `opcode [6:0]` 4. **B-type:** `imm[12] [31]` | `imm[10:5] [30:25]` | `rs2 [24:20]` | `rs1 [19:15]` | `funct3 [14:12]` | `imm[4:1] [11:8]` | `imm[11] [7]` | `opcode [6:0]` 5. **U-type:** `imm[31:12] [31:12]` | `rd [11:7]` | `opcode [6:0]` 6. **J-type:** `imm[20] [31]` | `imm[10:1] [30:21]` | `imm[11] [20]` | `imm[19:12] [19:12]` | `rd [11:7]` | `opcode [6:0]` Notice the structural alignment: `opcode` is always `[6:0]` (with `[1:0] = 11_2`), `rd` is always `[11:7]`, `rs1` is always `[19:15]`, `rs2` is always `[24:20]`, and the immediate sign bit is always bit `[31]`. **Inline Example — Decoding a B-type Immediate:** Suppose a branch instruction has `imm[12]=1`, `imm[10:5]=111111_2`, `imm[4:1]=1110_2`, and `imm[11]=1`. Notice there is no stored `imm[0]` because branch targets are 16-bit aligned (`imm[0] = 0`). Assembling `imm[12:0]` from MSB to LSB yields `1_1_111111_1110_0_2`, which in two's complement is $-4$ bytes (one 32-bit instruction backward). We'll use these immediate extractors (`ImmI`, `ImmB`, `ImmJ`) directly in our datapath and microcode. *[Editor Note: removed floating-point registers `f0`–`f31`/`fcsr` outside RV32I and unratified $\ge 48$-bit instruction encodings.]* #### ✎ Check Your Understanding 1. **Quick decoding check:** In all 32-bit RV32I formats, which bit holds the immediate's sign bit, and what are bits `[1:0]` of `opcode` always equal to? **Answer:** Bit `31` holds the immediate's sign bit, and bits `[1:0]` of `opcode` are always `11_2`. 2. **What would happen if** an instruction executes `ADD x0, x1, x2`? **Answer:** `x0` remains `0` because `x0` is hardwired to `0` and writes to it have no effect. --- ### Section 3: Control vs. Datapath and the Single-Bus Microcoded RISC-V Machine Every processor divides into two halves: * The **Datapath**, where state is stored (`PC`, `Inst. Reg.`, `Registers`) and arithmetic is computed (`ALU`), exchanging `Address` and `Data` with `Main Memory`. * The **Control**, which sequences datapath operations via **Control Lines** in response to `Instruction` / `Opcode`, `Condition?` (from the ALU), and `Busy?` (from Main Memory). In 1958, **Maurice Wilkes** invented **microprogramming** for **EDSAC-II** to replace error-prone hardwired vacuum-tube control logic. In the 1950s, logic (vacuum tubes) was extremely expensive compared to memory, main memory (magnetic cores) was slow, and **Read-Only Memory (ROM)** (diode matrices or punched metal cards) was **both much cheaper and much faster than RAM**. Storing control sequences inside a fast ROM turned control design into writing a microprogram. #### The Microcoded CPU and the `µPC` vs. `PC` Distinction In a **Microcoded CPU**, Main Memory holds the user program (macroinstructions). Inside Control, a register called **`µPC`** feeds a **Decoder** into a **Microcode ROM**. Each ROM row outputs **`Control Lines`** (driving the Datapath and Main Memory) and a **`Next State`** feedback signal that combines with `Busy?`, `Opcode`, and `Condition?` to update `µPC`. **Preempting a Critical Misconception:** **The `µPC` is NOT the `PC`!** * **`PC`** is **architectural**: visible to software, stored in the datapath, pointing to the current RISC-V instruction in Main Memory. * **`µPC`** is **microarchitectural**: invisible to software, stored inside Control, stepping through microcode rows in the Microcode ROM to execute *one* RISC-V instruction across several clock cycles. #### The Single-Bus Datapath for Microcoded RISC-V To minimize hardware cost, all datapath components share a **single 32-bit bus**. Only one source may drive the bus in any clock cycle via its tri-state enable (`*En`), while one or more destination registers may latch from the bus on the rising clock edge via their load signals (`*Ld`). Walking left to right across the datapath: 1. **`Instruction Reg. (IR)`**: Latches the instruction from the bus when **`InstLd=1`**; sends **`Opcode`** up to Control and register/immediate fields to the datapath. 2. **`Immediate`**: Extracts and sign-extends the selected immediate (`ImmI`, `ImmS`, `ImmB`, `ImmU`, `ImmJ`) via **`ImmSel`**, driving the bus when **`ImmEn=1`**. 3. **`Register RAM`**: Stores `x0`–`x31` *plus* **`PC` at address `32`**. **`RegSel`** selects `rs1`, `rs2`, `rd`, or `32 (PC)`. Set **`RegW=0, RegEn=1`** to read onto the bus, or **`RegW=1`** (with `RegEn=0`) to write from the bus. 4. **`A`, `B`, and `ALU`**: Latches **`A`** (`ALd`) and **`B`** (`BLd`) feed the combinational **`ALU`** (`ALUOp`), which outputs **`Condition?`** to Control and drives its result onto the bus when **`ALUEn=1`**. 5. **`Mem. Addr (MA)` and `Main Memory`**: **`MA`** latches an address when **`MALd=1`**. Main Memory reads onto the bus when **`MemEn=1`** (`MemW=0`), writes from the bus when **`MemW=1`**, and asserts **`Busy?`** until complete. #### Register-Transfer Notation We write microinstructions as **register transfers** rather than raw bitstrings. Three concrete translations: * **`MA:=PC`** $\equiv$ `RegSel=PC; RegW=0; RegEn=1; MALd=1` * **`B:=Reg[rs2]`** $\equiv$ `RegSel=rs2; RegW=0; RegEn=1; BLd=1` * **`Reg[rd]:=A+B`** $\equiv$ `ALUop=Add; ALUEn=1; RegSel=rd; RegW=1` One source can load multiple destinations simultaneously (e.g., `MA,A:=PC` asserts both `MALd=1` and `ALd=1`), but two `*En` drivers can never be active simultaneously or they will short-circuit the shared bus. *[Editor Note: removed duplicate single-bus datapath diagram slides.]* #### ✎ Check Your Understanding 1. **True or False (with justification):** The `µPC` and the `PC` hold the same address during instruction execution. **Answer:** False. The `PC` is architectural state pointing to the current RISC-V instruction in Main Memory, while the `µPC` is microarchitectural state inside Control pointing to the current microinstruction in the Microcode ROM. 2. **Quick translation:** Write the non-zero control signals required to execute `B:=ImmI`. **Answer:** `ImmSel=ImmI; ImmEn=1; BLd=1` (with all other enables, loads, and writes set to `0`). --- ### Section 4: Microcode Execution for RISC-V and Complex Instructions RISC-V instructions pass through up to seven phases: *Instruction Fetch, Instruction Decode, Register Fetch, ALU Operations, Optional Memory Operations, Optional Register Writeback, and Calculate Next Instruction Address*. Let us trace six microcode sequences on our single-bus datapath: 1. **Instruction Fetch:** * `MA,A:=PC` (send `PC` to `MA` for memory read and save `PC` in `A`) * `PC:=A+4` (increment `PC`—note that in Section 5's ROM table we schedule `PC:=A+4` right after `IR:=Mem` so the bus is free during memory wait) * *`wait for memory`* (spin while `Busy? == 1`) * `IR:=Mem` (latch fetched instruction into `IR`) * *`dispatch on opcode`* 2. **`ALU` (R-type, e.g., `ADD`):** * `A:=Reg[rs1]` $\rightarrow$ `B:=Reg[rs2]` $\rightarrow$ `Reg[rd]:=ALUOp(A,B)` $\rightarrow$ *`goto instruction fetch`* 3. **`ALUI` (I-type, e.g., `ADDI`):** * `A:=Reg[rs1]` $\rightarrow$ `B:=ImmI` $\rightarrow$ `Reg[rd]:=ALUOp(A,B)` $\rightarrow$ *`goto instruction fetch`* 4. **`LW` (Load Word):** * `A:=Reg[rs1]` $\rightarrow$ `B:=ImmI` $\rightarrow$ `MA:=A+B` $\rightarrow$ *`wait for memory`* $\rightarrow$ `Reg[rd]:=Mem` $\rightarrow$ *`goto instruction fetch`* 5. **`JAL` (Jump and Link):** Assuming `A` holds `PC_orig + 4` entering execute: * `Reg[rd]:=A` *(stores return address `PC_orig + 4`)* * `A:=A-4` *(recovers `PC_orig`—skipping this would offset the jump target by +4!)* * `B:=ImmJ` $\rightarrow$ `PC:=A+B` $\rightarrow$ *`goto instruction fetch`* 6. **`Branch` (Conditional Branch):** * `A:=Reg[rs1]` $\rightarrow$ `B:=Reg[rs2]` * `if (!ALUOp(A,B)) goto instruction fetch` *(Not taken: since `PC` is already `PC_orig + 4`, jumping straight to fetch continues sequentially!)* * If taken, fall through: `A:=PC` $\rightarrow$ `A:=A-4` $\rightarrow$ `B:=ImmB` $\rightarrow$ `PC:=A+B` $\rightarrow$ *`goto instruction fetch`* #### The Payoff: Complex Instructions Without Datapath Changes Suppose we want to add a CISC-style **Memory-Memory Add** (`M[rd] = M[rs1] + M[rs2]`). On a hardwired pipelined CPU, three memory accesses in one instruction require major datapath surgery. Here, **the datapath stays completely untouched**—we only add seven rows (`MMA0`–`MMA6`) to the microcode ROM: * `MMA0`: `MA:=Reg[rs1]` $\rightarrow$ `next` * `MMA1`: `A:=Mem` $\rightarrow$ `spin` * `MMA2`: `MA:=Reg[rs2]` $\rightarrow$ `next` * `MMA3`: `B:=Mem` $\rightarrow$ `spin` * `MMA4`: `MA:=Reg[rd]` $\rightarrow$ `next` * `MMA5`: `Mem:=ALUOp(A,B)` $\rightarrow$ `spin` * `MMA6`: *(idle)* $\rightarrow$ `fetch` Now we must ask: how large does that Microcode ROM grow if implemented naively, and how do we compress it? #### ✎ Check Your Understanding 1. **Trace the pitfall:** In `Branch`, why must the microcode execute `A:=A-4` after `A:=PC` when a branch is taken? **Answer:** `PC` was already incremented to `PC + 4` during instruction fetch, whereas `ImmB` is relative to the branch instruction's original address, so `A:=A-4` recovers the original `PC`. 2. **Yes or No:** Does adding `M[rd] = M[rs1] + M[rs2]` require modifying our single-bus datapath? **Answer:** No. The existing datapath performs the three memory accesses and addition sequentially across clock cycles; only extra microcode ROM entries are needed. --- ### Section 5: Implementing and Compressing the Microcode Control Store In a **Pure ROM Implementation**, four registers (`µPC`, `Opcode`, `Cond?`, `Busy?`) concatenate into the ROM `Address`, and each ROM `Data` word outputs `Next µPC` plus `Control Signals`: 1. **Address width:** $|\mu\text{address}| = |\mu\text{PC}| + |\text{opcode}| + 1 + 1$ (summing `µPC` bits, `opcode` bits, 1 `Cond?` bit, and 1 `Busy?` bit). 2. **Data width:** $|\text{data}| = |\mu\text{PC}| + |\text{control signals}| = |\mu\text{PC}| + 18$ (next micro-address plus 18 datapath/memory control lines). 3. **Total ROM size:** $\text{Total ROM size} = 2^{|\mu\text{address}|} \times |\text{data}|$ ($2^{|\mu\text{address}|}$ lookup rows, each `|data|` bits wide). Inspecting the **Pure ROM Contents** reveals huge waste: `fetch0` (`X, X, X` $\rightarrow$ `MA,A:=PC | fetch1`), `fetch1` (`Busy=1` spins, `Busy=0` latches `IR:=Mem`), `fetch2` (dispatches on `Opcode`), and `ALU0`–`ALU2` (`X, X, X`). Almost every address row has `X` ("don't care") in `Opcode`, `Cond?`, and `Busy?`, duplicating rows exponentially! Let us compute the exact **Pure ROM size** for our RISC-V machine: * $3$ fetch steps + $\sim 12$ instruction groups $\times 5$ steps each $= 63$ steps $\implies$ **$|\mu\text{PC}| = 6$ bits** ($2^6 = 64$). * RV32I `opcode` has `5` varying bits (`[1:0]=11_2`), plus $1$ `Cond?` bit and $1$ `Busy?` bit $\implies |\mu\text{address}| = 6 + 5 + 1 + 1 = 13$ bits. * With $18$ control signals $\implies |\text{data}| = 6 + 18 = 24$ bits. * $\text{Total ROM size} = 2^{13} \times 24\text{ bits} = 8,192 \times 24 = 196,608\text{ bits} = 24\text{ KiB} \approx 25\text{ KB}$. #### Compressing the Control Store To eliminate that exponential bloat, we shrink both ROM height and width: * **Reduce ROM height (`#address bits`):** Handle `Opcode`, `Cond?`, and `Busy?` in small external logic rather than the ROM address, and group similar opcodes. * **Reduce ROM width (`#data bits`):** Replace the 6-bit `Next µPC` with a 3-bit **`µPC jump`** code, and optionally encode control signals. In our **Single-Bus RISC-V Microcode Engine**, the ROM `Address` takes **only `µPC`** ($64$ rows total!). External **`µPC Jump Logic`** inspects `Cond?`, `Busy?`, and the ROM's **`µPC jump`** field—chosen from **`next`** ($\mu\text{PC}+1$), **`spin`** (hold while `Busy?=1`, else $+1$), **`fetch`** (`fetch0`), **`dispatch`** (`Decode(Opcode)`), and **`ftrue`/`ffalse`** (`fetch0` if `Cond?` true/false, else $+1$)—and steers a 4-way mux into `µPC`. The **Encoded ROM Contents** now have zero `X` columns: * `fetch0`: `MA,A:=PC` | `next` * `fetch1`: `IR:=Mem` | `spin` * `fetch2`: `PC:=A+4` | `dispatch` * `ALU0`–`ALU2`: `A:=Reg[rs1]` (`next`), `B:=Reg[rs2]` (`next`), `Reg[rd]:=ALUOp(A,B)` (`fetch`) * `Branch0`–`Branch5`: `A:=Reg[rs1]` (`next`), `B:=Reg[rs2]` (`next`), `A:=PC` (`ffalse` — tests `Condition?` on `Reg[rs1], Reg[rs2]` synchronously before `A` latches `PC` on the clock edge!), `A:=A-4` (`next`), `B:=ImmB` (`next`), `PC:=A+B` (`fetch`). At $64 \times (3 + 18) = 1,344\text{ bits} = 168\text{ bytes}$, the ROM shrank by over **$146\times$**. #### Horizontal vs. Vertical Microcode and Nanocoding Control-signal encoding trades ROM height against width: * **Horizontal $\mu$code:** wider $\mu$instructions (multiple parallel ops per cycle, fewer steps, sparser `X` encoding $\Rightarrow$ more bits wide). * **Vertical $\mu$code:** narrower $\mu$instructions (typically one datapath op per step + separate branch $\mu$instructions, more steps, compact $\Rightarrow$ fewer bits wide). * **Nanocoding:** combines both by exploiting recurring control patterns (such as `A <- Reg[rs1]` appearing in both `ALU0` and `ALUI0`). `µPC` indexes a narrow **`µcode ROM`**, which outputs either a next-state jump or a **`nanoaddress`** into a wide **`nanoinstruction ROM`** storing each unique horizontal pattern only once. For example, the **Motorola 68000** used a **17-bit $\mu$code ROM** holding either a 10-bit $\mu$jump or a **9-bit nanoinstruction pointer** into a **68-bit nanoinstruction ROM** that decoded into **196 control signals**. *[Editor Note: removed the Turing-machine "tallest µCode" cartoon slide.]* #### ✎ Check Your Understanding 1. **Quick computation:** If a Pure ROM controller has $5$ bits of `µPC`, a $4$-bit `Opcode`, $1$ `Cond?` bit, $1$ `Busy?` bit, and $15$ control signals, what is its total ROM size in bits? **Answer:** $|\mu\text{address}| = 5 + 4 + 1 + 1 = 11$ bits and $|\text{data}| = 5 + 15 = 20$ bits, giving $2^{11} \times 20 = 40,960\text{ bits}$. 2. **Concept check:** Why does the Encoded ROM engine's `Branch2` step (`A:=PC` with `ffalse`) not corrupt `A` before `Condition?` is checked? **Answer:** Because registers update on the rising clock edge: during the `Branch2` cycle, `A` still holds `Reg[rs1]` so the combinational ALU outputs `Condition?` for `Reg[rs1]` and `Reg[rs2]`, while `A` only latches `PC` at the end of the cycle if `µPC` falls through to `Branch3`. --- ### Section 6: The Rise, Retreat, and Modern Legacy of Microprogramming Microprogramming dominated computer design through the 1960s and 1970s. On IBM System/360, every model except the fastest two (Models 75 and 95, which were hardwired) was microprogrammed—scaling from an 8-bit datapath using punched metal-film capacitive cards (**Card-Capacitor Read-Only Storage**, cycling twice as fast as main memory) up to 64-bit models. Microcode also allowed IBM to sell **ISA emulation** packages so System/360 could run legacy IBM 1401 and 7000 programs. Except for the cheapest and fastest machines, almost every computer in the 1960s and 1970s was microprogrammed because: 1. ROMs were far faster than DRAM/core memory. 2. For complex ISAs, microcoded control was simpler and cheaper than hardwired logic. 3. New instructions (e.g., floating-point) required no datapath changes. 4. Fixing controller bugs meant swapping a ROM card. 5. Compatibility across wide model families was cheap and easy. #### Why Microprogramming Retreated in the 1980s In the early 1980s, five forces broke microprogramming's dominance: 1. **Runaway microcode complexity:** Complex ISAs like the **DEC VAX 11-780** demanded huge microprograms with subroutines and call stacks inside $\mu$code. 2. **Read-only ROM vs. bugs:** Bug-free giant microprograms were nearly impossible to write, forcing vendors to adopt **Writable Control Store (WCS)** in fast MOS SRAM (e.g., B1700, QMachine, Intel i432). Some minicomputers offered **User-WCS** so customers could write custom microcode, but **User-WCS failed** due to lack of tools, tiny control-store space, ISA-tailored datapaths, expensive OS context switches (WCS became part of processor state), broken protection, and the nightmare of making microcode restartable across virtual-memory page faults. 3. **VLSI invalidated the ROM/RAM speed gap:** Putting logic and fast SRAM caches on the same chip eliminated ROM's speed advantage. 4. **Better compilers** made exotic CISC instructions unnecessary. 5. **Pipelining, caches, and buffers** made multi-cycle microcoded execution of simple register-register instructions too slow, driving the industry toward hardwired, pipelined **RISC** architectures. #### Microprogramming Today Despite the rise of RISC pipelines, **microprogramming is far from extinct**. Heavily pipelined x86 and POWER processors still use microcode selectively in two ways: 1. **Complex/infrequent instructions:** Common instructions execute directly via fast **hardwired control**, while rare or complicated operations (such as floating-point subnormal handling or legacy complex x86 instructions) invoke an internal microcode sequencer. 2. **Post-fabrication bug and security patches:** Modern CPUs load **patchable microcode** into internal SRAM at bootup to fix hardware errata in shipped silicon—most famously when Intel had to deploy boot-time microcode patches across millions of processors to mitigate the **Meltdown and Spectre** security vulnerabilities. *[Editor Note: removed IBM 360 monthly rental fees, `CCROS`/`TCROS`/`BCROS` acronym table, Honeywell Liberator / 650-on-1401-on-360 backstory, and unreadable VAX 11-780 printout.]* #### ✎ Check Your Understanding 1. **Causal check:** Name two reasons why User-Writable Control Store (User-WCS) failed in minicomputers. **Answer:** (Any two of:) lack of programming tools, difficulty fitting code into small space, datapaths tailored to the original ISA, expensive OS context switches because WCS became processor state, protection problems, and virtual memory requiring restartable microcode. 2. **Yes or No:** Do modern x86 CPUs execute *every* instruction through microcode? Explain briefly. **Answer:** No. Most common instructions execute directly via hardwired control, while microcode is reserved for infrequent/complex instructions (like FP subnormals) and boot-time bug or security patches.