Lecture 3: Pipelining 1

Section 1: The Iron Law of Performance and the Shift from Microcode to RISC

Earlier, we saw how a microcoded processor implements a complex ISA over a tiny datapath by stepping through a control ROM over many clock cycles. To judge whether that design—or any processor design—is actually fast, we need a quantitative framework. That framework is the “Iron Law” of Processor Performance (formulated by Joel Emer and Doug Clark):

\frac{\text{Time}}{\text{Program}} = \frac{\text{Instructions}}{\text{Program}} \times \frac{\text{Cycles}}{\text{Instruction}} \times \frac{\text{Time}}{\text{Cycle}}

Let us break apart each factor in this product:

  1. \frac{\text{Instructions}}{\text{Program}} (Dynamic Instruction Count): How many machine instructions the processor executes to finish the program. This depends on the source code, compiler technology, and the ISA (e.g., a CISC ISA may pack more work into one instruction than a RISC ISA).
  2. \frac{\text{Cycles}}{\text{Instruction}} (\text{CPI}, Cycles Per Instruction): The average number of clock cycles required per instruction, averaged over a large number of instructions. This depends on both the ISA and the microarchitecture.
  3. \frac{\text{Time}}{\text{Cycle}} (Clock Period): The duration of one clock tick, set by the microarchitecture’s critical combinational path and the underlying silicon technology. Notice the physical constraint on this term: a modern large die near the lithography reticle limit (\sim 830\text{ mm}^2) measures roughly 30\text{ mm} (\sim 1\text{ inch}) on a side; at a 5\text{ GHz} clock rate, one cycle lasts only 0.2\text{ nanoseconds}, meaning signal propagation across a chip is increasingly bottlenecked by the speed of light.

Together, the Iron Law reminds us that total execution time is a product of all three terms—optimizing one factor (such as reducing instruction count via complex CISC instructions) fails if it blows up \text{CPI} or clock period even more.

Why Microcoded CISC Machines Lost to Pipelined RISC

Consider a concrete \text{CPI} measurement on a microcoded machine executing three instructions in sequence taking 7, 5, and 10 cycles respectively:

In the late 1970s and early 1980s, three landmark empirical findings exposed why paying \text{CPI} \approx 7 for microcoded CISC processors was a bad trade:

  1. John Cocke and the IBM 801 / PL.8 compiler: Cocke’s group built a simple pipelined processor (the 801) and ported their experimental PL.8 compiler to the CISC IBM 370, restricting the compiler to only simple register-register and load/store instructions. Even running on existing IBM 370 hardware, the restricted code ran up to 6\text{ MIPS} where 2\text{ MIPS} using the full CISC instruction set had been considered good!
  2. Emer and Clark’s DEC VAX-11/780 measurements: Using external hardware probes, they discovered that the VAX-11/780 actually delivered only 0.5\text{ MIPS} (half its advertised 1\text{ MIPS}). Worse, 20\% of VAX instructions consumed 60\% of the microcode, yet accounted for only 0.2\% of execution time.
  3. The VAX 8800 control-store bloat: The VAX 8800 spent 16\text{K} \times 147\text{ bits} of fast RAM on its microcode control store versus 64\text{K} \times 8\text{ bits} on its unified cache—4.5\times more fast on-chip RAM storing fixed microcode than caching user data and instructions!

Meanwhile, VLSI IC technology changed the underlying economics: logic, RAM, and ROM were all built out of MOS transistors, making semiconductor RAM roughly the same speed as ROM. Revisit our nanocoded Motorola 68000 controller from the previous lecture (µPC \rightarrow µcode ROM \rightarrow nanoinstruction ROM \rightarrow control lines). Architects realized they could replace all three blocks with their user-visible equivalents:

With early 1980s VLSI integration finally able to fit a 32-bit datapath and small caches on a single chip (avoiding slow chip crossings in the common case), RISC architectures took over. Look at how the three microarchitectural styles compare in the Iron Law:

Microarchitecture CPI Cycle Time
Microcoded > 1 (e.g., 7.33) Short
Single-cycle unpipelined 1 Long
Pipelined 1 (ideal) Short

Pipelining achieves the best of both worlds—\text{CPI} = 1 and a short clock period—which raises an immediate engineering question: how does a pipelined datapath work cycle by cycle, and what prevents it from staying at \text{CPI} = 1?

[Editor Note: removed course administrivia, Grace Hopper nanosecond video URL, and Berkeley RISC-I/II transistor/area museum specs.]

✎ Check Your Understanding

  1. Iron Law reasoning: Suppose Processor A cuts \frac{\text{Instructions}}{\text{Program}} by 20\% using complex microcoded instructions, but doubles its \text{CPI} compared to Processor B at the same clock frequency. Which processor finishes the program faster, and by what factor? Answer: Processor B is faster. Processor A’s execution time changes by 0.80 \times 2.0 = 1.60, meaning Processor A takes 1.6\times longer than Processor B.

  2. Fill in the blank: When VLSI technology made semiconductor RAM as fast as ROM, RISC architectures replaced the fixed microcode ROM with a user-visible ________ and replaced the nanoinstruction ROM with ________. Answer: Instruction Cache; Hardwired Decode.


Section 2: The Classic 5-Stage RISC Pipeline, Throughput Metrics, and Structural Hazards

To see how pipelining achieves both \text{CPI} = 1 and a short clock cycle, compare three timelines executing Inst 1, Inst 2, and Inst 3:

Preempting a Classic Misconception: Students frequently see 5 stages per instruction and think a 5-stage pipeline has \text{CPI} = 5. A 5-stage pipeline does NOT have \text{CPI} = 5! Each individual instruction has a latency of 5 cycles from start to finish, but because 5 instructions overlap concurrently, the throughput is 1 instruction per cycle—\text{CPI} = 1.

To keep pipeline metrics precise as we scale to deeper and multi-unit designs, we define three distinct terms for any hardware unit:

Students often assume \text{Occupancy} = \text{Latency} and \text{Bandwidth} = 1/\text{Latency}. All four departures from that assumption are possible for a single functional unit:

  1. \text{Occupancy} \ll \text{Latency}: A pipelined unit (e.g., a 5-stage FP adder) accepts a new operation every 1 cycle (\text{Occupancy} = 1) while taking 5 cycles to finish (\text{Latency} = 5).
  2. \text{Occupancy} > \text{Latency}: A unit that delivers its useable result early, then requires recovery/cooldown cycles (such as DRAM row precharge/refresh after a read returns data) before accepting the next request.
  3. \text{Bandwidth} > 1/\text{Latency}: Either a pipelined unit (where \text{BW} = 1/\text{Occupancy} > 1/\text{Latency}) or multiple replicated sub-units inside the block.
  4. \text{Bandwidth} < 1/\text{Latency}: Whenever \text{Occupancy} > \text{Latency} (recovery overhead) or pipeline stalls/bubbles interrupt steady issue.

The Classic 5-Stage RISC Pipeline Datapath

Verbalizing the classic 5-stage RISC pipeline from left to right (with dashed vertical lines representing pipeline registers clocked on the rising edge, and assuming synchronous reads and writes for register files and memories):

  1. Fetch (F): PC addresses the Instruction Cache, which delivers the instruction into Inst. Register at the F/D boundary.
  2. Decode (D): Inst. Register drives control/register specifiers into Registers (reading rs1 and rs2 into latches A and B) and sign-extends Imm into the D/X pipeline registers.
  3. EXecute (X): A multiplexer selects B or Imm, feeding the ALU alongside A; the ALU output latches into the X/M pipeline register, while store data passes alongside in Store.
  4. Memory (M): The ALU result addresses the Data Cache (reading or writing Store data) or bypasses around it into the M/W latches.
  5. Writeback (W): A multiplexer selects either the Data Cache load value or the ALU result and routes it back to write Registers.

Pipeline Bubbles and Structural Hazards

When instructions overlap in a pipeline, they interact in three ways that force us to insert bubbles (wasted cycles), degrading ideal \text{CPI} above 1:

We measure steady-state pipeline CPI from when the first instruction finishes to when the last instruction finishes:

Resolving a structural hazard is straightforward: either stall the newer instruction in hardware until the older instruction frees the resource, or add duplicate hardware (e.g., if instruction fetch and data memory access collided on a single memory port, adding separate Instruction and Data caches—a second memory port—eliminates the hazard). By design, the classic 5-stage RISC integer pipeline has zero structural hazards (though real implementations introduce structural hazards on multi-cycle units like multipliers, dividers, floating-point units, and shared register writeback ports).

With structural hazards eliminated in our 5-stage integer core, the dominant obstacles to \text{CPI} = 1 are data hazards and control hazards.

✎ Check Your Understanding

  1. True or False (with justification): A 5-stage pipelined processor has an ideal \text{CPI} of 5 because every instruction takes 5 cycles to execute. Answer: False. While each instruction has a latency of 5 cycles, 5 instructions overlap in different stages simultaneously, so one instruction finishes every cycle, giving an ideal \text{CPI} of 1.

  2. Quick computation: Suppose a single-unit memory controller takes 4 cycles to return read data to the processor, and then needs 2 additional cycles of internal precharge before it can accept a new request. State its Latency, Occupancy, and peak Bandwidth (in ops/cycle). Answer: Latency = 4 cycles; Occupancy = 4 + 2 = 6 cycles; peak Bandwidth = 1/6 ops/cycle (so \text{Occupancy} > \text{Latency} and \text{Bandwidth} < 1/\text{Latency}).


Section 3: Data Hazards — Interlocking, Bypassing, and Value Speculation

Consider a sequence of register-register instructions of the form r_k \leftarrow r_i \text{ op } r_j. Overlapping instructions in a pipeline can trigger three kinds of data hazards:

  1. Data-dependence — Read-After-Write (RAW): r_3 \leftarrow r_1 \text{ op } r_2 \quad \text{followed by} \quad r_5 \leftarrow r_3 \text{ op } r_4 The second instruction must read the new r_3 produced by the first. If it reads the register file too early, it gets the stale value. (This is the only data hazard that occurs in our simple in-order 5-stage pipeline, because reads always happen in D and writes in W.)
  2. Anti-dependence — Write-After-Read (WAR): r_3 \leftarrow r_1 \text{ op } r_2 \quad \text{followed by} \quad r_1 \leftarrow r_4 \text{ op } r_5 The second instruction must not overwrite r_1 before the first reads the old r_1. (Cannot occur in our in-order 5-stage pipeline, but will become critical in out-of-order machines in Lecture 4!)
  3. Output-dependence — Write-After-Write (WAW): r_3 \leftarrow r_1 \text{ op } r_2 \quad \text{followed by} \quad r_3 \leftarrow r_6 \text{ op } r_7 Both write r_3; the second write must land after the first. (Also arises when variable-latency pipelines allow later instructions to finish out of order.)

Hardware designers resolve RAW data hazards using three strategies: Interlock (stall the dependent instruction in Decode/Issue until the value is written), Bypass (forward the computed value directly to the consumer’s ALU input as soon as it exists), or Speculate (guess the value and recover if wrong).

Inline Example: Interlocking vs. Bypassing

Trace the two-instruction sequence:

add x1, x3, x5
sub x2, x1, x4

To eliminate all ALU-to-ALU and Memory-to-ALU register stalls across a 4-instruction window, we build a Fully Bypassed Datapath:

Where Bypassing Fails: Load-Use Hazards and Value Speculation

Is there any instruction sequence where full bypassing still cannot avoid a bubble? Yes—a load immediately followed by an instruction that uses the loaded register (LW \rightarrow ADD)! In LW, the data is not available from the Data Cache until the end of the M stage, which is too late to feed the immediately following instruction’s X stage (that would require sending data backward in time by one cycle!). Thus, even on a fully bypassed 5-stage pipeline, a load-use hazard forces a 1-cycle bubble (unless the compiler schedules an independent instruction in between).

As an alternative to stalling, architects have explored Value Speculation—guessing the missing value and checking later—though in practice it is only effective in narrow, highly predictable cases: branch prediction (guessing the next PC), stack pointer updates, and memory address disambiguation (guessing whether a load hits the same address as an older pending store—which can also introduce subtle security side-channels if speculative loads leak secret data before misprediction recovery).

[Editor Note: removed ephemeral SLAP/FLOP Apple Silicon side-channel news graphics.]

✎ Check Your Understanding

  1. Hazard classification: Identify whether the following pair has a RAW, WAR, or WAW hazard on x2: add x3, x2, x1 followed by sub x2, x4, x5. Answer: WAR (Write-After-Read) hazard: the second instruction writes x2, which the first instruction must read first.

  2. What would happen if lw x1, 0(x2) is immediately followed by add x3, x1, x4 on our fully bypassed 5-stage RISC pipeline? Answer: A 1-cycle stall (bubble) occurs, because lw only obtains x1 from the Data Cache at the end of its M stage, one cycle after add originally wanted to enter X.


Section 4: Control Hazards, Delay Slots, and Why CPI Exceeds 1

Control hazards are the hardest hazards in pipelining because branches, jumps, and exceptions alter which instruction is fetched next. We classify RISC-V control-flow instructions along two axes—direct vs. indirect (target known from PC + instruction encoding vs. read from a register) and conditional vs. unconditional (maybe taken vs. always taken). Generally, conditional is harder than unconditional, and indirect is harder than direct.

Mapping when each piece of control-flow information becomes known in the 5-stage pipeline tells us the exact bubble penalty:

Unconditional Jumps, Conditional Branches, and Kill Logic

Trace the hardware for Unconditional PC-Relative Jumps (j target):

For Conditional Branches (beq x1, x2, target) and Jump Register (jr x1), we wait until EXecute for Cond? (or the bypassed rs1 target). That requires carrying PC_execute + an Add unit into X (or computing PC_decode + Imm in D and holding the target) and asserting both FKill and DKill when taken—flushing the two younger instructions in F and D and creating a 2-cycle bubble!

Branch Delay Slots: A Historical Detour

To hide those 1-cycle or 2-cycle bubbles in the 1980s, early RISC ISAs (like MIPS and SPARC) adopted Branch Delay Slots from microcode engines: they redefined the ISA so the instruction physically stored immediately after a jump or branch (0x104 add x1, x2, x3 right after 0x100 j target) always executes before control transfers to 0x205 target. If the compiler found an independent instruction to move into the delay slot, it eliminated the bubble; otherwise, it inserted a NOP.

Post-1990 RISC ISAs (including RISC-V) abandoned delay slots for four reasons:

  1. Leaky abstraction: Delay slots encode a specific pipeline depth directly into the ISA (just like the IBM 650’s magnetic drum layout!).
  2. Performance penalties: Filling unused slots with NOPs bloats code size and causes extra I-cache misses—even stalling on an I-cache miss just to fetch a NOP!
  3. Breaks advanced pipelines: A 1-instruction delay slot becomes useless baggage on a modern 30-stage, 4-wide superscalar pipeline.
  4. Better branch prediction eliminates taken-branch bubbles dynamically without changing ISA semantics.

Summary: Why Classic 5-Stage Pipelines Have \text{CPI} > 1

Even after pipelining, real workloads rarely hit \text{CPI} = 1:

✎ Check Your Understanding

  1. Cycle count check: On our 5-stage RISC-V pipeline without branch prediction, how many bubble cycles occur on a taken beq (resolved in X) versus an unconditional j (resolved in D)? Answer: beq incurs a 2-cycle bubble (FKill and DKill flush the 2 instructions in F and D), whereas j incurs a 1-cycle bubble (FKill flushes only the 1 instruction in F).

  2. Yes or No: If a compiler inserts NOP instructions into branch delay slots, does that improve real program execution speed? Explain using the Iron Law. Answer: No. Although NOPs eliminate stall cycles (which lowers apparent CPI), they proportionally increase \frac{\text{Instructions}}{\text{Program}} so total execution time stays unchanged (or worsens due to I-cache misses).


Section 5: Traps, Interrupts, and Precise Exception Handling

Control hazards also arise asynchronously or unexpectedly from exceptions and interrupts. Using strict terminology:

When a trap occurs at instruction I_i, normal sequential execution (I_{i-1} \rightarrow I_i \rightarrow I_{i+1}) diverts to a trap handler (HI_1 \rightarrow HI_2 \dots \rightarrow HI_n) and then typically returns to I_i.

We require precise traps (precise interrupts): the machine must stop cleanly on one instruction I_i such that all instructions before I_i (I_0 \dots I_{i-1}) have completed, and no instruction from I_i onward has modified architectural state.

Precise Exceptions in a 5-Stage Pipeline

In our 5-stage pipeline, four different instructions can simultaneously raise four different exceptions in the same clock cycle:

If the hardware jumped to the trap handler immediately when Overflow fired in X, a younger instruction might be in D while an older instruction ahead of it in M actually had an earlier Data address exception—violating precise traps!

The clean hardware solution uses a Commit Point at the end of the M stage (right before architectural register writes in W, and ensuring Data Mem stores only commit there):

  1. Attach two extra shift registers down the pipeline latches: Exc D/E/M (holding any exception flag raised by that instruction) and PC D/E/M (carrying its PC).
  2. Priority per instruction: Earlier pipe stages override later pipe stages for a given instruction (e.g., if F flagged a PC address error, D’s Illegal Opcode cannot overwrite it).
  3. Priority across instructions: Because instructions reach M strictly in program order, holding Exc until the Commit Point guarantees the oldest faulting instruction traps first!
  4. Inject Asynchronous Interrupts at the Commit Point, overriding other exceptions for that cycle.
  5. On trap at Commit: Update Cause and EPC (from PC_M), assert Kill F, Kill D, Kill E, and Kill Writeback (preventing the faulting instruction and all younger instructions from updating architectural state), and drive Select Handler PC into PC_fetch.

Speculating on Exceptions and the Meltdown Lesson

Notice how this architecture actually speculates on exceptions: because exceptions are rare, the pipeline predicts no exception every cycle, lets younger instructions execute and even consume uncommitted results via bypassing, checks for exceptions at the Commit Point, and recovers by flushing uncommitted state (since architectural state is only written at/after commit).

Preempting a Critical Security Misconception: You might think that flushing architectural registers on a trap erases all trace of the killed instructions. Lazy exception handling—letting younger instructions speculatively read privileged memory and leave side effects in the cache before the Commit Point kills the faulting load—is the exact mechanism behind the Meltdown security vulnerability!

[Editor Note: removed Univac/DYSEAC early-history exception slides and acknowledgements.]

✎ Check Your Understanding

  1. Ordering check: Suppose in the same cycle, Instruction 1 (in M) suffers a Data Address Exception, and younger Instruction 2 (in X) suffers an Arithmetic Overflow. Using the Commit-Point exception pipeline, which exception is taken, and what happens to Instruction 2? Answer: Instruction 1’s Data Address Exception reaches the Commit Point first and triggers the trap (EPC gets PC_M of Instruction 1), while Instruction 2 is killed (Kill E / Kill Writeback) before changing architectural state.

  2. Fill in the blank: In the 5-stage exception pipeline, an instruction’s exception flags are carried down to the ________ at the end of the M stage, so that architectural state is only modified once the instruction is guaranteed not to fault. Answer: Commit Point.