# CS152 Lecture 4: Pipelining 2 ### Section 1: Deeper Pipelines and Compiler Scheduling — The MIPS R4000 Moving beyond the classic 5-stage pipeline, single-thread processors exploit more **Instruction-Level Parallelism (ILP)** across four major pipeline categories: * **Super-pipelined:** Slicing each stage into smaller sub-stages to crank up clock frequency (`Time/Cycle`). * **Decoupled:** Splitting integer/address generation from floating-point execution via queues. * **Out-of-order:** Feeding instructions from an in-order **Frontend** into an **Instruction Pool**, then issuing independent instructions out-of-order into a parallel **Backend**. * **Superscalar:** Widening both Frontend and Backend to fetch and execute multiple instructions per cycle. #### Deeper Pipelines: The 8-Stage MIPS R4000 Suppose `Instruction Memory` and `Data Memory` caches are too large and slow to access in a single short clock cycle. The **MIPS R4000** solves this by super-pipelining cache access into an **8-stage pipeline**: 1. **`IF`** — Instruction cache fetch (first half) 2. **`IS`** — Instruction cache fetch (second half; instruction bits are actually ready at the end of `IS`, *before* the tag check finishes!) 3. **`RF`** — Register Fetch *and* Instruction cache tag check (speculating that a **direct-mapped I$** hit allows us to decode and fetch registers in parallel with checking the tag!) 4. **`EX`** — ALU execution (and branch condition evaluation) 5. **`DF`** — Data cache fetch (first half) 6. **`DS`** — Data cache fetch (second half; data bits ready at end of `DS`) 7. **`TC`** — Data cache tag check (**Commit Point** sits right after `TC`, because we cannot write loaded data into the register file until we know the cache hit!) 8. **`WB`** — Register Writeback How does deepening the pipeline from 5 to 8 stages hurt **branch** and **load-use** hazards? * **R4000 Branches (3-cycle branch delay):** `BEQZ` evaluates its condition in `EX` (Cycle 4). Meanwhile, `Instruction 1` (Cycle 2), `Instruction 2` (Cycle 3), and `Instruction 3` (Cycle 4) have already entered `IF` before `Target` can fetch in Cycle 5—producing a **3-cycle branch delay**! * **R4000 Load-Use Delay (2-cycle delay):** `LD R1` reads direct-mapped D$ data at the end of `DS` (Cycle 6), and speculatively bypasses it directly to `EX` of a consumer `ADDD R2, R1` in Cycle 7 *before* `TC` completes (if `TC` misses, the pipeline stalls/recovers). Even with that aggressive bypass, two instructions (`Instruction 1` in Cycle 2, `Instruction 2` in Cycle 3) sit between `LD` and `ADDD` (`IF`=Cycle 4, `IS`=Cycle 5, `RF`=Cycle 6, `EX`=Cycle 7), creating a **2-cycle load-use delay**! #### Compiler Techniques: Pipeline Scheduling and Loop Unrolling To keep deeper pipelines busy without stalling, compilers rearrange code. Consider the vector-vector add `for (i = 0; i < N; i++) A[i] = B[i] + C[i];` translated naively into RISC-V assembly: ``` loop: fld f0, 0(x2) // x2 -> B[i] fld f1, 0(x3) // x3 -> C[i] fadd.d f2, f0, f1 // stalls waiting for f1! fsd f2, 0(x1) // x1 -> A[i]; stalls waiting for f2! addi x1, x1, 8 addi x2, x2, 8 addi x3, x3, 8 bne x1, x4, loop // x4 = end pointer ``` 1. **Simple Pipeline Scheduling:** Move the independent pointer-bump instructions (`addi x3, x3, 8` and `addi x2, x2, 8`) between `fld f1` and `fadd.d`, and move `addi x1, x1, 8` between `fadd.d` and `fsd` (adjusting the store offset to **`-8(x1)`** because `x1` was already bumped by 8!). Still, long load and floating-point latencies quickly run out of independent work inside a single loop iteration. 2. **Loop Unrolling:** Duplicate the loop body (e.g., 2 iterations at once using distinct registers `f0/f1` and `f10/f11`), bumping pointers once by `16` and storing at `-16(x1)` and `-8(x1)`: ``` loop: fld f0, 0(x2) fld f1, 0(x3) fld f10, 8(x2) fld f11, 8(x3) addi x3, x3, 16 addi x2, x2, 16 fadd.d f2, f0, f1 fadd.d f12, f10, f11 addi x1, x1, 16 fsd f2, -16(x1) fsd f12, -8(x1) bne x1, x4, loop ``` Unrolling cuts loop-overhead instructions (`addi`, `bne`) in half and spaces out dependent `fld` $\rightarrow$ `fadd.d` $\rightarrow$ `fsd` chains. However, unrolling hits four walls: it is limited by the number of **architectural registers**, expands the **instruction cache footprint**, requires complex compiler **pointer-aliasing analysis** (proving `A`, `B`, and `C` don't overlap), and still cannot hide unpredictable cache misses. To overcome what static compiler scheduling cannot predict at compile time, architects turned to **dynamic hardware scheduling**. #### ✎ Check Your Understanding 1. **Pipeline delay check:** On the 8-stage MIPS R4000, why is the load-use delay 2 cycles instead of 3 cycles even though the `TC` (tag check) stage does not finish until Cycle 7? **Answer:** Because the R4000 uses a direct-mapped data cache, allowing the loaded data from `DS` (Cycle 6) to bypass speculatively into the consumer's `EX` stage in Cycle 7 before `TC` finishes. 2. **Code check:** When scheduling `addi x1, x1, 8` *before* `fsd f2, 0(x1)` in the vector-add loop, why did the store instruction change to `fsd f2, -8(x1)`? **Answer:** Because `addi` already advanced `x1` by $+8$ bytes toward the next element, so `-8(x1)` restores the target address of the current element `A[i]`. --- ### Section 2: Dynamic Scheduling, Scoreboarding, and Multi-Unit In-Order Pipelines In 1964, Seymour Cray built the **CDC 6600**—widely regarded as the first supercomputer—and pioneered **dynamic hardware scheduling** to keep **10 parallel, unpipelined functional units** (FP adder, 2 FP multipliers, divider, integer adder, 2 incrementers, etc.) busy at a $10\text{ MHz}$ clock against a 32-bank central memory. #### The CDC 6600 Load/Store ISA Long before "RISC" existed, Cray designed the CDC 6600 ISA specifically to simplify high-performance pipelined hardware: * **Three explicit register banks:** `8 x 60-bit` data operand registers (`X0`–`X7`), `8 x 18-bit` address registers (`A0`–`A7`), and `8 x 18-bit` index registers (`B0`–`B7`). * **3-address register-register ALU:** `opcode(6b) | i(3b) | j(3b) | k(3b)` computing $R_i \leftarrow R_j \text{ op } R_k$. Only 3-bit register fields need dependency checking—zero implicit accumulator or stack dependencies! * **Decoupled implicit Load/Store:** Writing an address into `A1`–`A5` *automatically* initiates a memory load into the matching `X1`–`X5`; writing into `A6`–`A7` initiates a store from `X6`–`X7`. For example, a vector-add loop sets `A0 <- B0 + a0` (triggers load `X0`), `A1 <- B0 + b0` (triggers load `X1`), computes `X6 <- X0 + X1`, and sets `A6 <- B0 + c0` (triggers store `X6`). By decoupling setting `Ar` from reading `Xr`, software and hardware can overlap multiple outstanding memory requests with independent work! (Its successor, the **CDC 7600**, pipelined those functional units, directly foreshadowing RISC.) #### Complex Pipeline Hazards and the CDC 6600 Scoreboard In any multi-unit machine—split into a **Frontend** (fetch/decode) that **dispatches** instructions into an **Instruction Pool**, and a **Backend** that **issues** them to parallel execution units before **Writeback (`WB`)**—four new hazards emerge: 1. Structural conflicts at execution if an FPU/memory unit is unpipelined and busy for multiple cycles. 2. Structural conflicts at the **`WB` port** when fast and slow units finish in the same cycle. 3. **Out-of-order write hazards (WAW and WAR)** when a younger fast instruction overtakes an older slow instruction. 4. **Imprecise exceptions** when younger instructions finish before older ones fault. The **CDC 6600 Scoreboard** (the control logic gating entry/exit of the Instruction Pool) solved these dynamically: * **Dispatch (in-order):** Instructions enter the scoreboard in program order until the scoreboard is full. * **Issue (out-of-order):** An instruction exits the scoreboard to an execution unit only when it has **no RAW hazards**, **no WAW hazards** (checked against all older executing instructions), and **no structural hazards** (on the target EXE unit or register writeback). * **Stalling WAR before Writeback:** Notice the subtle WAR rule! A younger instruction *can* start executing early even if it writes a register (`r1`) that an older stalled instruction hasn't read yet—because it stalls in the `EXE` stage **immediately before register-file writeback** until the older instruction finishes reading `r1` (though stalled outputs waiting to write back can create a **pileup** blocking that functional unit). #### In-Order Multi-Unit and Superscalar Alternatives Not every processor wanted the complexity of out-of-order scoreboarding. An **In-Order Multi-Unit Pipeline** enforces fixed timing instead: * All short/pipelined units (Integer ALU + Data Mem, `FAdd`, `FMul`) are padded to the **exact same latency to `W`** (`X1, X2, X3` to the **Commit Point** right before `W`). Because one instruction enters per cycle and all take 3 execution stages, **writeback ports are never oversubscribed** (`1` in, `1` out per cycle) and **exceptions remain strictly in-order**! * Long-latency operations like an unpipelined **`FDiv`** or cache miss simply stall the pipeline. * **How do we keep 3-stage padding from slowing down single-cycle integer instructions?** **Bypassing** from the end of `X1` directly back to `X1` inputs lets back-to-back integer ops run with zero bubbles while still waiting until `W` to commit! To push throughput past $\text{CPI} = 1$ (reaching $\text{IPC} > 1$) without out-of-order hardware, an **In-Order Superscalar Pipeline** (such as the 1992 Alpha 21064 or 1996 MIPS R5000) fetches **2 instructions per cycle** into a **`Dual Decode`**, issuing both simultaneously whenever one is integer/memory and the other is floating-point. Extending this to 4-wide issue (UltraSPARC, Alpha 21164) by duplicating functional units works conceptually, but **register-file read/write ports and bypassing multiplexer wiring grow explosively**. *[Editor Note: removed supercomputer folklore, CDC 6600 weight/floor-area/cooling/price stats, and the Watson/Cray memo slides.]* #### ✎ Check Your Understanding 1. **Scoreboard rule check:** Which two data hazards prevent an instruction from *issuing* out of the CDC 6600 Scoreboard, and how does the Scoreboard handle the third data hazard (WAR)? **Answer:** RAW and WAW hazards (plus structural hazards) block issue out of the scoreboard; WAR hazards are allowed to issue and execute, then stall right before register-file writeback until the older reader finishes. 2. **Design check:** In the complex in-order pipeline where Integer ALU, `FAdd`, and `FMul` all wait until stage `X3` to reach `W`, why don't consecutive integer instructions stall for 2 cycles? **Answer:** Bypassing forwards the integer ALU result immediately after `X1` to the next instruction's `X1` input without waiting for `W`. --- ### Section 3: Advanced In-Order Techniques — Decoupled Execution and Dynamic ALU Scheduling Even without full out-of-order scoreboarding, architects developed two clever in-order mechanisms to hide memory latency: **Decoupled Architectures** and **Dynamic ALU Scheduling**. #### Decoupled (Lookahead / Runahead) Execution Look back at our vector-add loop: ``` loop: fld f0, 0(x2) // control/address (red) fld f1, 0(x3) // control/address (red) fadd.d f2, f0, f1 // data computation (green) fsd f2, 0(x1) // address (red) + data (green) addi x1, x1, 8 // control/address (red) addi x2, x2, 8 // control/address (red) addi x3, x3, 8 // control/address (red) bne x1, x4, loop // control/address (red) ``` Notice a structural split: **none of the control or memory-address instructions (`addi`, `bne`, `fld` address, `fsd` address) depend on the floating-point data computations (`fadd.d`)!** A **Simple Decoupled Machine** exploits this by connecting two in-order pipelines through FIFO queues: 1. The **Integer Pipeline (`F D X M W`)** runs far ahead ("lookahead"): it executes `addi` and `bne`, computes load addresses (checking each **`Load Address`** against pending entries in the **`Store Address Queue`** so loads never bypass an older store to the same address!), sends loads to memory, and pushes floating-point **`µOp`s** (`Load Data Writeback µOp`, `Compute µOp`, `Store Data Read µOp`) into a **`µOp Queue`**. 2. Memory returns loaded words in order into a **`Load Data Queue`**. 3. The **Floating-Point Pipeline (`R X1 X2 X3 W`)** runs at its own pace, pulling micro-ops from the `µOp Queue` and operands from the `Load Data Queue`, computing `fadd.d`, and placing results into the **`Store Data Queue`** to pair with addresses waiting in the `Store Address Queue`. Because the Integer Pipeline can race several loop iterations ahead, **many writes to `f0` can be queued in flight at the same time**, cleanly ordered by the FIFO queues without WAW/WAR corruption! #### Dynamic ALU Scheduling (Motorola MC68060 Style) Finally, consider a clever in-order pipeline trick used in the **Motorola MC68060** (and adapted in modern in-order RISC cores): placing **two ALU stages—one *before* memory (`EA`) and one *after* memory (`ALU`)**: $$\text{EA (Effective Address)} \longrightarrow \text{MEM (Data Cache)} \longrightarrow \text{ALU (Integer Execute)}$$ Originally built so CISC memory-register instructions (`add x1, x1, 24(x2)`) could calculate `x2 + 24` in `EA`, read `M[x2 + 24]` in `MEM`, and add `x1` in `ALU` all in one pass, this `EA -> MEM -> ALU` structure also lets pure RISC instructions bypass load-use stalls dynamically! Trace all five instructions in the MC68060 example (using RISC-V-style syntax): 1. **`add x1, x1, 24(x2)`**: Cycle 1 `EA` computes `x2 + 24`; Cycle 2 `MEM` reads `M[x2 + 24]`; Cycle 3 `ALU` computes `x1 + M[x2 + 24]`. 2. **`add x3, x1, x6`**: Needs `x1` from Instruction 1's late `ALU` stage (Cycle 3)! Because it needs no memory access, it sails past `EA` (Cycle 2) and `MEM` (Cycle 3), accepts `x1` bypassed directly from Cycle 3's `ALU` into **Cycle 4's `ALU`** (`x1 + x6`), and finishes with **zero stalls**! 3. **`addi x5, x2, 12`**: Needs `x2` (already ready) and no memory access, so it executes *early* in **Cycle 3's `EA` stage** (`x2 + 12`). 4. **`lw x4, 16(x5)`**: Needs `x5` from Instruction 3 immediately for address calculation—and gets `x5` bypassed straight from Cycle 3's `EA` into **Cycle 4's `EA`** (`x5 + 16`), hitting `MEM` in Cycle 5 with **zero stalls**! 5. **`lw x8, 16(x3)`**: Needs `x3` from Instruction 2's late `ALU` (Cycle 4)—and gets `x3` bypassed directly from Cycle 4's `ALU` into **Cycle 5's `EA`** (`x3 + 16`), hitting `MEM` in Cycle 6 with **zero stalls**! By placing an ALU both before and after `MEM`, producers run early (`EA`) when feeding load addresses and late (`ALU`) when consuming loaded data—achieving zero-bubble execution on code that would stall on a single-ALU 5-stage pipeline. *[Editor Note: removed duplicate Simple Decoupled Machine diagram slide.]* #### ✎ Check Your Understanding 1. **Queue safety check:** In the Simple Decoupled Machine, why must every `Load Address` generated by the Integer Pipeline be checked against the `Store Address Queue`? **Answer:** Because the Integer Pipeline runs ahead and sends loads to memory while older floating-point store data may still be queued; if a load matches a pending store address, forwarding or waiting prevents reading stale data from memory. 2. **Stage assignment check:** In an `EA -> MEM -> ALU` pipeline, why does `addi x5, x2, 12` (followed immediately by `lw x4, 16(x5)`) execute in `EA` rather than the later `ALU` stage? **Answer:** Executing `addi` in `EA` produces `x5` two cycles earlier, allowing it to bypass directly into the immediately following `lw`'s `EA` address-calculation stage with zero stalls.