计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 2 · 本科二年级

11The Processor: Datapath, Control and Pipelining

A laundry has a washer, a dryer and a folding table, each taking half an hour. Done one at a time, four loads take six hours. But as soon as the first load leaves the washer, the second can go in: with the three machines busy at once, the four loads are done in three hours, and each extra load adds only half an hour. A processor does the same with instructions. Here are five instructions going through a five-step processor, one row per instruction and one column per clock cycle:

$ python timing_diagram.py independent.S
                      1  2  3  4  5  6  7  8  9
addi t0, zero, 1      F  D  X  M  W
addi t1, zero, 2         F  D  X  M  W
addi t2, zero, 3            F  D  X  M  W
addi a0, zero, 0               F  D  X  M  W
jalr zero, 0(ra)                  F  D  X  M  W
5 instructions, 9 cycles, 0 stall cycles
Output 11.1. Five instructions in 9 cycles instead of 25: F fetch, D decode, X execute, M memory, W write back. Some lines are left out.

No instruction finishes sooner than before; more of them finish per second. This chapter builds the processor that runs the instructions of Chapter 10, first as one large circuit that does a whole instruction in one clock cycle, then cut into five stages that work at once, and measures, on real programs run by rv, what the overlap costs when instructions depend on one another.

You already know

Book 3: a multiplexer selects one of its inputs by a control value; a decoder turns a number into one active line; an ALU computes an arithmetic or logic function chosen by its control inputs; every gate has a propagation delay. A register holds its value until the clock edge; a clock paces a synchronous circuit; a finite-state machine changes state on each edge. A processor is a datapath, which moves and transforms data, and a control unit, which drives it. Chapter 10: the RV32I formats, the immediates, and branch offsets.

11.1 A single-cycle datapath

Definition 11.1 (Single-cycle processor)

A single-cycle processor executes each instruction completely in one clock cycle: in that cycle the instruction is fetched, its registers read, the ALU used, memory accessed and the result written back, and the next clock edge stores the new program counter and the result.

Its datapath, for a subset of RV32I (the register and immediate arithmetic, lw, sw and the six conditional branches), needs these parts:

  • the program counter (PC), a 32-bit register, and an instruction memory read at the PC;
  • the register file, with two read ports (rs1, rs2) and one write port (rd);
  • the immediate generator, which gathers the scattered immediate bits of the I, S and B formats and sign-extends them;
  • the ALU, and a data memory read or written at the address the ALU computes;
  • two adders for the next PC, pc+4\mathit{pc} + 4 and pc+imm\mathit{pc} + \mathit{imm};
  • multiplexers wherever two sources compete for one input.
The single-cycle datapath of datapath.py. Data flows left to right; the write-back and the next PC return to the left. The three multiplexers choose the ALU’s second input (register or immediate), the value written back (ALU result or loaded word) and the next PC (pc + 4 or the branch target). The control signals, in colour, come from the control unit; a comparator beside the ALU (not drawn) decides taken.
The single-cycle datapath of datapath.py. Data flows left to right; the write-back and the next PC return to the left. The three multiplexers choose the ALU’s second input (register or immediate), the value written back (ALU result or loaded word) and the next PC (pc+4\mathit{pc} + 4 or the branch target). The control signals, in colour, come from the control unit; a comparator beside the ALU (not drawn) decides taken.

The model datapath.py computes, for one instruction word and the current state of an rv machine, what this circuit does in one clock cycle, without changing the machine; the caller then lets rv execute the instruction and compares the two.

def cycle(m, pc, word):
    """One clock cycle of the datapath, reading machine m without changing it."""
    c = CONTROL.get(word & 0x7F)
    if c is None or (c.name in ("lw", "sw") and word >> 12 & 7 != 2):
        return None                                # outside the subset: lb, sh, ...
    if c.name == "R-type" and word >> 25 == 1:
        return None                                # mul, div: the M extension
    rd, rs1, rs2 = word >> 7 & 31, word >> 15 & 31, word >> 20 & 31
    a, b_reg = m.x[rs1], m.x[rs2]                  # the register file: two reads
    imm = imm_gen(word)
    b = imm & MASK if c.alu_src else b_reg         # the ALUSrc multiplexer
    if c.branch:
        taken = BRANCH[word >> 12 & 7](a, b_reg)
        return Effect(None, None, None, None, (pc + imm) & MASK if taken else pc + 4)
    result = ALU[alu_control(c, word)](a, b) & MASK
    mem_value = m.load(result, 4) if c.mem_read else (b_reg if c.mem_write else None)
    value = mem_value if c.mem_to_reg else result  # the MemtoReg multiplexer
    write = c.reg_write and rd != 0
    return Effect(rd if write else None, value if write else None,
                  result if c.mem_read or c.mem_write else None, mem_value, pc + 4)
Listing 11.1. One cycle of the datapath code/bachelor-2/11-processor-and-pipelining/listings/datapath.py
def imm_gen(word):
    """The immediate generator: gather the scattered bits, then sign-extend."""
    op = word & 0x7F
    if op in (0b0010011, 0b0000011):  # I
        return sext(word >> 20, 12)
    if op == 0b0100011:               # S
        return sext((word >> 25) << 5 | (word >> 7) & 0x1F, 12)
    if op == 0b1100011:               # B
        return sext((word >> 31) << 12 | (word >> 7 & 1) << 11
                    | (word >> 25 & 0x3F) << 5 | (word >> 8 & 0xF) << 1, 13)
    return 0
Listing 11.2. The immediate generator: the layouts of Chapter 10 read backwards code/bachelor-2/11-processor-and-pipelining/listings/datapath.py

Each line of cycle is a wire or a box of the figure. Tracing four instructions is a matter of following the values: add t2, t0, t1 reads two registers, the ALU adds, the multiplexer passes the ALU result to the write port. sw t2, 12(sp) reads sp and t2, the ALU adds 12 to sp as an address, and the data memory stores t2 there; nothing is written to a register. lw t3, 12(sp) computes the same address, reads memory, and writes the loaded word, through the second multiplexer, to t3. beq t2, t3, same compares the two registers; when they are equal, the PC multiplexer takes pc+imm\mathit{pc} + \mathit{imm}.

11.2 Control

Definition 11.2 (Control signal)

A control signal is a wire from the control unit that selects a multiplexer’s input, enables a write, or chooses an ALU operation. In a single-cycle processor the control unit is a combinational circuit whose input is the instruction’s opcode (with funct3 and funct7 for the ALU).

Method 11.3 (Deriving the control table)

For each class of instruction, follow the path its data must take through the datapath, then set each signal:

  1. RegWrite is 1 when the instruction has a destination register, else 0 (stores, branches);
  2. ALUSrc is 1 when the ALU’s second operand is the immediate (I-type, loads, stores), 0 for a register;
  3. MemRead and MemWrite are 1 only for loads and stores respectively;
  4. MemtoReg is 1 when the written value comes from memory (loads); when RegWrite is 0 it does not matter;
  5. Branch is 1 for the conditional branches; the PC multiplexer takes the target when Branch is 1 and the comparison holds;
  6. the ALU operation is “add” for addresses, “compare” for branches, and read from the funct fields otherwise.

A signal that does not matter for an instruction may be set either way; setting it to 0 makes the table simpler, never a signal that writes something.

CONTROL = {                       # opcode -> signals: the control table
    0b0110011: Control("R-type", 0, 0, 1, 0, 0, 0, "funct"),
    0b0010011: Control("I-type", 1, 0, 1, 0, 0, 0, "funct"),
    0b0000011: Control("lw",     1, 1, 1, 1, 0, 0, "add"),
    0b0100011: Control("sw",     1, 0, 0, 0, 1, 0, "add"),
    0b1100011: Control("branch", 0, 0, 0, 0, 0, 1, "compare"),
}
Listing 11.3. The control table, one row per opcode code/bachelor-2/11-processor-and-pipelining/listings/datapath.py

alu_control then picks the operation from funct3, and funct7 separates add from sub and srl from sra; an addi has no funct7, its bit 30 being part of the immediate, which is why subi does not exist. The model’s check runs four.S and compares every instruction it covers with rv:

$ python datapath.py four.S
instruction          decoded   ALUSrc MemtoReg RegWrite  MemRead MemWrite   Branch
addi sp, sp, -16     I-type         1        0        1        0        0        0  agrees
addi t0, zero, 7     I-type         1        0        1        0        0        0  agrees
addi t1, zero, 5     I-type         1        0        1        0        0        0  agrees
add t2, t0, t1       R-type         0        0        1        0        0        0  agrees
sw t2, 12(sp)        sw             1        0        0        0        1        0  agrees
lw t3, 12(sp)        lw             1        1        1        1        0        0  agrees
beq t2, t3, same     branch         0        0        0        0        0        1  agrees
addi a0, zero, 0     I-type         1        0        1        0        0        0  agrees
addi sp, sp, 16      I-type         1        0        1        0        0        0  agrees
jalr zero, 0(ra)     outside the model's subset
9 instructions agree with rv, 1 outside the subset
Output 11.2. The control signals of each instruction, and the agreement with rv.

The chapter’s test runs the same check on every program of the chapter: the datapath and rv agree on every instruction of the subset. The ret that ends four.S is a jalr, which needs one more path, pc+4\mathit{pc} + 4 into the register file: Exercise 11.12 adds it.

The trouble with this design is its clock. The cycle must be long enough for the slowest instruction, the load, which goes through instruction memory, register file, ALU, data memory and back to the register file. Suppose those take 200, 100, 200, 200 and 100 ps: the clock period is at least 800 ps, and an add, which does not need data memory, waits for nothing while its 600 ps of work end.

11.3 The five-stage pipeline

Definition 11.4 (Instruction pipeline, pipeline stage, pipeline register)

An instruction pipeline splits the execution of an instruction into steps, the pipeline stages, each taking one clock cycle, so that several instructions are in progress at once, one per stage. Between two stages a pipeline register holds what the next stage needs: the values computed so far and the control signals of the instruction.

The classic RISC pipeline has five stages, cut where the single-cycle datapath has its large blocks: IF (fetch from instruction memory), ID (decode and read the registers), EX (the ALU), MEM (data memory) and WB (write the register). Its pipeline registers are named after the stages they separate: IF/ID, ID/EX, EX/MEM, MEM/WB. With the delays above, the clock period becomes that of the slowest stage, 200 ps.

Definition 11.5 (Latency, throughput)

The latency of an instruction is the time from its fetch to its completion. The throughput of a processor is the number of instructions it completes per unit of time, or per cycle.

The pipeline does not lower the latency: in five stages of 200 ps an instruction takes 1000 ps, more than the 800 ps of the single cycle. It raises the throughput: in the steady state, one instruction completes every cycle.

Proposition 11.6 (Ideal gain of a pipeline)

On a kk-stage pipeline with no hazard, nn instructions take k+n−1k + n - 1 cycles. With a cycle kk times shorter than the unpipelined one, the time of the unpipelined machine divided by that of the pipeline is

nkk+n−1,\frac{nk}{k + n - 1},

which tends to kk as nn grows.

Proof. The first instruction leaves the last stage at the end of cycle kk. Each later one enters the pipeline one cycle after the one before it and so leaves one cycle after it: the nn-th leaves at the end of cycle k+n−1k + n - 1. The unpipelined machine takes nn cycles of length kk (in units of the short cycle), so nknk. Dividing, nk/(k+n−1)=k/(1+(k−1)/n)→knk/(k + n - 1) = k / (1 + (k - 1)/n) \to k. ∎

The hook’s five instructions took 5+5−1=95 + 5 - 1 = 9 cycles. In practice the stages are never perfectly balanced and the pipeline registers add their own delay, so the gain stays below kk even before the next section’s hazards.

The chapter’s timing model pipeline.py does not simulate wires: it takes the stream of instructions that rv executed (one Step per instruction, with the registers it read and wrote) and computes the cycle in which each enters each stage, with these rules: an instruction enters ID when the one before it leaves ID, and enters EX when its operands are ready.

def schedule(steps, forwarding=True, predictor=None):
    """The cycle of every stage of every instruction, the first IF in cycle 1."""
    predictor = predictor or NotTaken()
    t = Timing()
    ready = {}                       # register -> earliest EX of a reader
    next_fetch, prev_ex = 1, 1
    for s in steps:
        f = next_fetch
        d = max(f + 1, prev_ex)      # ID frees when the one ahead enters EX
        need = max([ready.get(r, 0) for r in s.srcs], default=0)
        x = max(d + 1, need)         # the hazard check, made in ID
        if t.execute:
            t.flushed += d - prev_ex     # fetched late: a branch or a jump
            t.stalls += x - (d + 1)      # held in ID until operands are ready
        t.fetch.append(f)
        t.decode.append(d)
        t.execute.append(x)
        if s.rd is not None:
            if not forwarding:           # read in ID once WB has written it
                ready[s.rd] = x + NO_FORWARD_DELAY
            else:
                ready[s.rd] = x + (LOAD_DELAY if s.kind == "load" else ALU_DELAY)
        next_fetch = d               # the next is fetched as this enters ID
Listing 11.4. The timing model, first part: when each instruction reaches each stage code/bachelor-2/11-processor-and-pipelining/listings/pipeline.py

11.4 Hazards

Definition 11.7 (Hazard: structural, data, control)

A hazard is a situation in which the next instruction cannot enter its next stage in the next cycle. It is structural when two instructions need the same hardware in the same cycle; a data hazard when an instruction needs a value that an earlier instruction has not yet written; a control hazard when the processor does not yet know which instruction comes next, after a branch or a jump.

Separate instruction and data memories remove the structural hazard between IF and MEM, and the register file is written in the first half of a cycle and read in the second, so WB and ID can share a cycle. Data hazards are everywhere: add t0, a1, a2 followed by sub t1, t0, a2 reads t0 in ID while add is still in EX. Without any help, sub must wait in ID until add has written t0 in WB, two cycles later.

Definition 11.8 (Stall, bubble, load-use hazard)

A stall holds an instruction in its stage for a cycle; the stage after it receives a bubble, an empty slot that does nothing. A load-use hazard is a data hazard in which an instruction uses the register that the instruction just before it loads from memory.

Definition 11.9 (Forwarding)

Forwarding (or bypassing) sends a result to the ALU’s input directly from a pipeline register, EX/MEM or MEM/WB, as soon as it has been computed, instead of waiting for it to be written to the register file and read again.

The value add computes is in EX/MEM at the end of its EX cycle, just in time for sub’s EX in the next one. The forwarding unit compares the source registers of the instruction in EX with the destinations of the two instructions ahead of it:

def forward(rs, ex_mem, mem_wb, check_x0=True):
    """ex_mem, mem_wb: (reg_write, rd) of the instructions one and two ahead."""
    for source, (reg_write, rd) in (("EX/MEM", ex_mem), ("MEM/WB", mem_wb)):
        if reg_write and rd == rs and (rd != 0 or not check_x0):
            return source  # the nearer one wins: it is the newer value
    return "register file"
Listing 11.5. The forwarding unit for one source register code/bachelor-2/11-processor-and-pipelining/listings/forwarding.py
$ python forwarding.py forwarding.S
addi a1, zero, 7     zero <- register file
addi a2, zero, 5     zero <- register file
add t0, a1, a2       a1 <- MEM/WB, a2 <- EX/MEM
sub t1, t0, a2       t0 <- EX/MEM, a2 <- MEM/WB
and t2, t0, t1       t0 <- MEM/WB, t1 <- EX/MEM
or t3, t0, t2        t0 <- register file, t2 <- EX/MEM
jalr zero, 0(ra)     ra <- register file
Output 11.3. Where each operand comes from, in a stream where each instruction uses the last ones. Some lines are left out.
The forwarding paths. Each ALU input gets a multiplexer with three sources: the register value read in ID, the result in EX/MEM (solid: one instruction ahead), or the result in MEM/WB (dashed: two ahead). The forwarding unit drives them with the rule of .
The forwarding paths. Each ALU input gets a multiplexer with three sources: the register value read in ID, the result in EX/MEM (solid: one instruction ahead), or the result in MEM/WB (dashed: two ahead). The forwarding unit drives them with the rule of Listing 11.5.

Forwarding cannot help a load: its value comes out of data memory at the end of MEM, one cycle later than an ALU result. The model encodes these delays in three numbers: an instruction may be in EX one cycle after an ALU producer, two after a load, and three after any producer when there is no forwarding (it reads in ID, during the producer’s WB).

Proposition 11.10 (One stall per load-use)

With forwarding from EX/MEM and MEM/WB, an instruction that uses the result of a load immediately before it is stalled exactly one cycle, and an instruction that uses it two or more instructions later is not stalled by it.

The proof is Exercise 11.8. Here are both effects on load_use.S:

$ python timing_diagram.py load_use.S
                      1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
auipc a0, 0xfff0      F  D  X  M  W
addi a0, a0, 0           F  D  X  M  W
lw t0, 0(a0)                F  D  X  M  W
add t1, t0, t0                 F  D  *  X  M  W
lw t2, 4(a0)                      F  .  D  X  M  W
add t3, t1, t2                          F  D  *  X  M  W
sw t3, 8(a0)                               F  .  D  X  M  W
addi a0, zero, 0                                 F  D  X  M  W
jalr zero, 0(ra)                                    F  D  X  M  W
Output 11.4. With forwarding: two stalls (*), one per load-use, and the stores and adds forwarded. A dot is an instruction waiting in IF because the stage ahead is held. Some lines are left out.
$ python timing_diagram.py load_use.S --no-forwarding
                      1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
auipc a0, 0xfff0      F  D  X  M  W
addi a0, a0, 0           F  D  *  *  X  M  W
lw t0, 0(a0)                F  .  .  D  *  *  X  M  W
add t1, t0, t0                       F  .  .  D  *  *  X  M  W
lw t2, 4(a0)                                  F  .  .  D  X  M  W
add t3, t1, t2                                         F  D  *  *  X  M  W
sw t3, 8(a0)                                              F  .  .  D  *  *  X  M  W
addi a0, zero, 0                                                   F  .  .  D  X  M  W
jalr zero, 0(ra)                                                            F  D  X  M  W
9 instructions, 23 cycles, 10 stall cycles
Output 11.5. The same program without forwarding: every dependence costs up to two cycles, 23 cycles in all. Some lines are left out.
The diagram of  drawn from the model’s output. The arrows are the forwarded values: from MEM/WB to an EX one cycle later (the two loads), and from EX/MEM (the add to the sw). Each stall slides every later instruction one column to the right.
The diagram of Output 11.4 drawn from the model’s output. The arrows are the forwarded values: from MEM/WB to an EX one cycle later (the two loads), and from EX/MEM (the add to the sw). Each stall slides every later instruction one column to the right.

The second half of the model handles control hazards. A conditional branch is resolved in EX, so when the processor guesses wrong about it, the two instructions fetched after it are thrown away and fetching restarts after its EX: two cycles lost. A jal knows its target in ID (it is pc+imm\mathit{pc} + \mathit{imm}), one cycle lost; a jalr needs a register, so EX, two cycles.

        if s.kind == "branch":
            guess = predictor.predict(s.pc)
            predictor.update(s.pc, s.branch_taken)
            if guess != s.branch_taken:  # resolved in EX: fetch again after it
                t.mispredicted += 1
                next_fetch = x + 1
        elif s.kind == "jump":
            jal = s.text.split()[0] == "jal"   # jal: target known in ID; jalr: EX
            next_fetch = d + 1 if jal else x + 1
        prev_ex = x
    return t
Listing 11.6. The timing model, second part: fetching again after a branch or a jump code/bachelor-2/11-processor-and-pipelining/listings/pipeline.py

11.5 Branch prediction

Definition 11.11 (Branch prediction, predictor, misprediction penalty)

Branch prediction lets the processor fetch past a conditional branch before it is resolved, along the direction a branch predictor guesses. When the guess is wrong, the instructions fetched since are discarded (flushed); the cycles lost are the misprediction penalty, here 2.

The simplest predictor says “not taken” for every branch, and is right whenever the branch falls through. Loops defeat it: the branch that closes a loop is taken at every turn but the last. A dynamic predictor remembers what each branch did. A one-bit predictor predicts that a branch does what it did last time; it is wrong twice per run of a loop, at the last turn and again at the first turn of the next run.

Definition 11.12 (Saturating counter)

A two-bit saturating counter is a number from 0 to 3, incremented when the branch is taken and decremented when it is not, without going past 0 or 3; it predicts “taken” when it is 2 or 3.

The two-bit predictor of one branch as a finite-state machine: T when the branch is taken, N when it is not. A single surprise in state 3 or 0 moves the state but not the prediction.
The two-bit predictor of one branch as a finite-state machine: T when the branch is taken, N when it is not. A single surprise in state 3 or 0 moves the state but not the prediction.
class TwoBit:
    """A two-bit saturating counter per branch: 0, 1 predict not taken; 2, 3 taken."""
    name = "two-bit"

    def __init__(self, start=1):
        self.start = start
        self.counter = {}

    def predict(self, pc):
        return self.counter.get(pc, self.start) >= 2

    def update(self, pc, taken):
        c = self.counter.get(pc, self.start)
        self.counter[pc] = min(c + 1, 3) if taken else max(c - 1, 0)
Listing 11.7. A two-bit counter per branch, kept by the address of the branch code/bachelor-2/11-processor-and-pipelining/listings/predictor.py

Proposition 11.13 (Two bits for a loop)

Let the branch that closes an inner loop of m≥2m \ge 2 turns be taken m−1m - 1 times and then not taken, at each execution of the inner loop. Once its counter has reached 3 during one execution, a two-bit counter mispredicts it exactly once per later execution of the inner loop; a one-bit predictor mispredicts it twice per execution.

The proof is Exercise 11.11. On the branch traces of three programs, the three predictors give:

$ python branches.py
program         branches  taken   mispredicted:  not taken  one-bit  two-bit
loop_sum.S            32     31                        31        2        2
bubble_sort.S        272    176                       176       86       60
collatz.S            942    186                       186      315      161
Output 11.6. Mispredicted branches out of all conditional branches executed. Some lines are left out.

On loop_sum.S the two-bit counter is wrong twice: once at the first turn, while it warms up, once at the exit. collatz.S is harder: its branch on the parity of nn follows the data, and there a one-bit predictor does worse than predicting “not taken” at all, because an odd nn is always followed by an even one: each taken outcome comes alone and costs the one-bit predictor two mistakes, the miss and the miss after it, where “not taken” misses once. Real processors keep thousands of counters, indexed by the address and by the outcomes of the last branches, and predict far better than these three; the principle is the same.

11.6 The performance equation

Definition 11.14 (Cycles per instruction, performance equation)

The cycles per instruction (CPI) of a run is its number of cycles divided by its number of instructions. The performance equation gives the time of a run:

time=instructions×CPI×cycle time.\text{time} = \text{instructions} \times \text{CPI} \times \text{cycle time}.

Each factor belongs to someone. The number of instructions depends on the program, the compiler and the instruction set; the CPI on the pipeline’s handling of hazards and on how often the program triggers them; the cycle time on the circuit. A single-cycle processor has a CPI of 1 and a long cycle; the pipeline has a short cycle and a CPI above 1, which forwarding and prediction bring closer to 1. In the model, for nn instructions,

cycles=n+4+stall cycles+cycles lost to branches and jumps,\text{cycles} = n + 4 + \text{stall cycles} + \text{cycles lost to branches and jumps},

an identity the chapter’s test checks on every program and every configuration.

$ python cpi_table.py
program         instructions         no forwarding            forwarding  forwarding + two-bit
loop_sum.S               136                 2.456                 1.721                 1.294
bubble_sort.S            964                 1.961                 1.512                 1.272
collatz.S               3342                 1.790                 1.338                 1.323
Output 11.7. The CPI of three programs in three configurations of the pipeline. Some lines are left out.
The CPI of . Forwarding helps every program; the predictor helps the two loops, and hardly collatz.S, whose branches follow the data.
The CPI of Output 11.7. Forwarding helps every program; the predictor helps the two loops, and hardly collatz.S, whose branches follow the data.
The die of a MIPS R3000A, a 32-bit RISC processor, photographed on its wafer. The squares along the edges are the pads wired to the package; the regular blocks are arrays of identical cells, and the irregular regions are logic. Photograph: Pauli Rautakorpi, CC BY 3.0.
The die of a MIPS R3000A, a 32-bit RISC processor, photographed on its wafer. The squares along the edges are the pads wired to the package; the regular blocks are arrays of identical cells, and the irregular regions are logic. Photograph: Pauli Rautakorpi, CC BY 3.0.

In practice — Pipelines today

Processors in desktops and phones have much longer pipelines than five stages, issue several instructions per cycle, and execute them out of order when their operands are ready; the hazards of this chapter remain, handled by more forwarding paths, deeper buffers and better predictors. The performance equation still decides: a longer pipeline shortens the cycle but raises the misprediction penalty. When code is slow on a modern machine, the usual suspects are mispredicted branches on unpredictable data and loads that miss in the caches, the subject of Chapter 12.

11.7 Exercises

Exercise 11.1 ★

How many cycles does the five-stage pipeline take for 8 independent instructions? For nn? What fraction of the stage slots are used in the first case?

Solution

Solution of Exercise 11.1.

By Proposition 11.6, n+4n + 4 cycles: 12 for 8 instructions. The pipeline has 12×5=6012 \times 5 = 60 stage slots in those cycles and the instructions use 8×5=408 \times 5 = 40: two thirds. The empty slots are the filling at the start and the draining at the end, which matter less as nn grows.

Exercise 11.2 ★

A designer copies the row of lw for sw and only clears MemRead and MemtoReg, leaving RegWrite at 1. What does sw t2, 12(sp) then do besides storing? (Look at what bits 11 to 7 of an S-type word hold.)

Solution

Solution of Exercise 11.2.

In an S-type word, bits 11 to 7 are the low five bits of the immediate, not a register. For sw t2, 12(sp) they hold 12, so the register file writes register x12, which is a2. MemtoReg is 0, so the value written is the ALU result, the address sp+12\texttt{sp} + 12. The store itself is correct; a2 is silently overwritten, and the bug shows only when a caller later reads a2. That is why RegWrite must be 0 for every instruction without a destination, while the “don’t care” signals may be anything.

Exercise 11.3 ★

Give the control signals for lui and the change it needs in the datapath. Add it to the model and check it against rv.

Solution

Solution of Exercise 11.3.

lui rd, imm writes imm⋅212\mathit{imm} \cdot 2^{12} to rd: RegWrite 1, ALUSrc 1, MemRead 0, MemWrite 0, MemtoReg 0, Branch 0. Two changes are needed. The immediate generator learns the U format (the upper 20 bits of the word, low bits zero). And the ALU’s first input must be 0, not rs1, since bits 19 to 15 of a U-type word belong to the immediate: a new multiplexer on that input, driven by a new signal, with the ALU adding.

# New signals: a_zero (the ALU's first input is 0, not rs1), pc4 (rd gets pc + 4), jump
# ("jal": the next pc is pc + imm; "jalr": the ALU result with bit 0 cleared).
MORE = {
    0b0110111: dict(name="lui", alu_src=1, reg_write=1, a_zero=1, pc4=0, jump=None),
    0b1101111: dict(name="jal", alu_src=1, reg_write=1, a_zero=0, pc4=1, jump="jal"),
    0b1100111: dict(name="jalr", alu_src=1, reg_write=1, a_zero=0, pc4=1, jump="jalr"),
}
The new signals for lui, jal and jalr code/bachelor-2/11-processor-and-pipelining/exercises/datapath_more.py

The chapter’s test runs a program with lui (through li) and checks the model against rv.

Exercise 11.4 ★

Compute the ratio of Proposition 11.6 for k=5k = 5 and n=10n = 10, 100100 and 10001000, and for k=10k = 10, n=10n = 10. How many instructions are needed for a five-stage pipeline to reach 90 % of its limit?

Solution

Solution of Exercise 11.4.

For k=5k = 5: 50/14≈3.5750/14 \approx 3.57 for n=10n = 10, 500/104≈4.81500/104 \approx 4.81 for n=100n = 100, 5000/1004≈4.985000/1004 \approx 4.98 for n=1000n = 1000. For k=10k = 10, n=10n = 10: 100/19≈5.26100/19 \approx 5.26, still far from 10, as filling and draining a deep pipeline cost more. For 90 % of 5: 5n/(n+4)≥4.55n/(n + 4) \ge 4.5 gives 0.5n≥180.5n \ge 18, so n≥36n \ge 36.

Exercise 11.5 ★★

Draw the timing diagram, with forwarding, of exo_diagram.S, and give its number of cycles.

main:   lw   t0, 0(sp)
        addi t1, t0, 1
        addi t2, zero, 5
        add  t3, t1, t2
        ret
Listing 11.8. One load, used at once code/bachelor-2/11-processor-and-pipelining/listings/exo_diagram.S
Solution

Solution of Exercise 11.5.

$ python timing_diagram.py exo_diagram.S
                      1  2  3  4  5  6  7  8  9 10
lw t0, 0(sp)          F  D  X  M  W
addi t1, t0, 1           F  D  *  X  M  W
addi t2, zero, 5            F  .  D  X  M  W
add t3, t1, t2                    F  D  X  M  W
jalr zero, 0(ra)                     F  D  X  M  W
5 instructions, 10 cycles, 1 stall cycle
Output 11.9. The model’s diagram.

The addi t1 uses t0 just after it is loaded: one stall, by Proposition 11.10, and the next addi waits one cycle in IF. add t3 gets t1 from MEM/WB and t2 from EX/MEM. Five instructions take 5+4+1=105 + 4 + 1 = 10 cycles.

Exercise 11.6 ★★

A forwarding unit tests only reg_write and rd == rs, without rd != 0. Find a short program whose result is then wrong, and say what it computes.

Solution

Solution of Exercise 11.6.

$ python forwarding.py exo_x0.S --forget-x0
addi t0, zero, 41    zero <- register file
addi zero, t0, 1     t0 <- EX/MEM
add a0, zero, zero   zero <- EX/MEM, zero <- EX/MEM
jalr zero, 0(ra)     ra <- register file
Output 11.10. The faulty unit on exo_x0.S. Some lines are left out.

addi zero, t0, 1 computes 42 and, since it writes x0, the register file ignores it. But the faulty unit sees rd == 0 == rs in the next instruction and forwards 42 from EX/MEM to both inputs of add a0, zero, zero, which computes 84 instead of 0. Writes to x0 are rare in compiled code, but a nop is addi zero, zero, 0, and any instruction can be used as a no-op that way.

Exercise 11.7 ★★

Add to the model a static predictor, “backward taken, forward not taken”: a branch whose target lies before it is predicted taken. Measure it on the three programs against the two-bit counter.

Solution

Solution of Exercise 11.7.

class BackwardTaken:
    """Predict taken exactly for the branches that jump backwards: loop branches."""
    name = "backward taken"

    def __init__(self, steps):
        self.back = {s.pc: decode(s.word).imm < 0 for s in steps if s.kind == "branch"}

    def predict(self, pc):
        return self.back[pc]

    def update(self, pc, taken):
        pass
Backward taken, forward not taken code/bachelor-2/11-processor-and-pipelining/exercises/btfn.py

The predictor decodes the branch’s offset; it needs no memory and no warm-up. On the three programs it mispredicts 1, 72 and 158 branches (two-bit: 2, 60 and 161), for CPIs of 1.279, 1.297 and 1.322. It wins on loop_sum.S, whose only branch closes a loop, and on collatz.S, whose backward bge closes the outer loop; it loses on the sort, where the forward branch bge t4, t3, keep is taken 55 times out of 120, which a counter follows better than a fixed rule. The test checks the case of loop_sum.S.

Exercise 11.8 ★★

Prove Proposition 11.10 from the model’s rules.

Solution

Solution of Exercise 11.8.

Let a load be in EX at cycle xx. In the model a consumer may be in EX at x+2x + 2 at the earliest (the word leaves data memory at the end of MEM, cycle x+1x + 1, and reaches the ALU input through MEM/WB). Instructions enter EX in order, at most one per cycle, and without hazards each enters EX one cycle after the one before. If the consumer follows the load directly, it would be in EX at x+1x + 1; the rule holds it one cycle, to x+2x + 2, and nothing else delays it by this dependence: exactly one stall. If it comes j≥2j \ge 2 instructions later, it cannot be in EX before x+j≥x+2x + j \ge x + 2, since the instructions between enter EX in the cycles in between: the rule asks nothing more, no stall. (The test checks both cases with an ALU instruction, a store and a branch as the consumer.)

Exercise 11.9 ★★

Reorder the loop of loop_sum.S so that no instruction stalls with forwarding, without changing what it computes, and measure the gain in cycles in the model.

Solution

Solution of Exercise 11.9.

The addi t0, t0, 4 does not depend on the load; moving it between the load and the add puts the use two places after the load:

loop:   lw   t2, 0(t0)
        addi t0, t0, 4          # moved up: independent of the load
        add  a0, a0, t2         # t2 now arrives through MEM/WB: no stall
        bltu t0, t1, loop
The reordered loop code/bachelor-2/11-processor-and-pipelining/exercises/loop_sum_sched.S

The bltu still reads t0 one instruction after the addi, which forwarding handles. The model gives 202 cycles instead of 234, the 32 load-use stalls removed, with the same 136 instructions. Compilers do this reordering, called instruction scheduling, for exactly this reason.

Exercise 11.10 ★★★

In a program, 20 % of the instructions are conditional branches, mispredicted 10 % of the time with a penalty of 2 cycles; 25 % are loads, 40 % of which are followed at once by a user of the loaded value; there are no other hazards. Compute the CPI. Which improvement is worth more: halving the misprediction rate, or reordering so that half of the load-uses disappear?

Solution

Solution of Exercise 11.10.

Per instruction, the branches cost 0.2×0.1×2=0.040.2 \times 0.1 \times 2 = 0.04 cycle and the load-uses 0.25×0.4×1=0.100.25 \times 0.4 \times 1 = 0.10 cycle: CPI=1+0.04+0.10=1.14\text{CPI} = 1 + 0.04 + 0.10 = 1.14. Halving the misprediction rate saves 0.020.02 (CPI 1.12); halving the load-uses saves 0.050.05 (CPI 1.09). Here the reordering is worth more, because load-uses are more frequent than mispredictions, even with a smaller penalty.

Exercise 11.11 ★★★

Prove Proposition 11.13. Does it hold for m=1m = 1?

Solution

Solution of Exercise 11.11.

Within one execution the branch is taken m−1≥1m - 1 \ge 1 times, then not taken. Suppose the counter is at least 2 when an execution starts. The taken outcomes are predicted taken and push the counter to 3, where it stays; the final not-taken outcome is predicted taken, wrongly, and brings the counter down to 2. So the execution has exactly one misprediction and the next one starts at 2. Once the counter has reached 3 in one execution, that execution ends at 2, and by induction every later one starts at 2 and has one misprediction. With one bit, an execution starts after a not-taken outcome: its first outcome, taken, is mispredicted, the next m−2m - 2 are right, and the exit is wrong again: two per execution. For m=1m = 1 the branch is never taken; the counter falls to 0 and never errs again, while the hypothesis (reaching 3) is never met: the proposition does not apply, and the loop costs nothing once warm.

Exercise 11.12 ★★★

Add jal and jalr to the single-cycle datapath: the new paths, the new control signals, and the model, checked against rv on a program that calls and returns.

Solution

Solution of Exercise 11.12.

jal rd, imm writes pc+4\mathit{pc} + 4 to rd and jumps to pc+imm\mathit{pc} + \mathit{imm} (J format); jalr rd, imm(rs1) writes pc+4\mathit{pc} + 4 and jumps to (rs1+imm)(\texttt{rs1} + \mathit{imm}) with bit 0 cleared. The datapath needs a third input on the write-back multiplexer, pc+4\mathit{pc} + 4 from the existing adder (signal pc4_to_reg); the J format in the immediate generator, whose result goes to the existing branch adder; and a third input on the PC multiplexer, the ALU result with bit 0 cleared (signal jump, three values: none, jal, jalr).

    if c is None:
        return cycle(m, pc, word)
    rd, rs1 = word >> 7 & 31, word >> 15 & 31
    imm = imm_more(word)
    a = 0 if c["a_zero"] else m.x[rs1]
    result = (a + imm) & MASK  # the ALU adds
    if c["jump"] == "jal":
        next_pc = (pc + imm) & MASK
    elif c["jump"] == "jalr":
        next_pc = result & ~1
    else:
        next_pc = pc + 4
    value = pc + 4 if c["pc4"] else result
    write = rd != 0
    return Effect(rd if write else None, value if write else None, None, None, next_pc)
The extended cycle code/bachelor-2/11-processor-and-pipelining/exercises/datapath_more.py

The test runs a program with a call, a ret and an indirect jalr through a register: the model agrees with rv on every instruction but the auipc of la and the final ecall, and on every program of the chapter it now covers the rets too.

11.8 Problem: Making the sort run faster

Problem 11.1

Weekend problem — Making the sort run faster

A bubble sort of 16 page counts is run through the pipeline model in its three configurations. The problem counts its instructions, then its cycles, and reads the gain of each improvement in the performance equation.

Part I — Counting instructions.

sort:                           # sort(a0 = array, a1 = n): a leaf
        addi t0, a1, -1         # i = n - 1
outer:  blez t0, done           # for (; i > 0; i--)
        mv   t1, a0             #   p = &a[0]
        slli t2, t0, 2
        add  t2, a0, t2         #   end = &a[i]
inner:  lw   t3, 0(t1)          #   for (; p < end; p++)
        lw   t4, 4(t1)
        ble  t3, t4, keep       #     if (p[0] > p[1]) swap them
        sw   t4, 0(t1)
        sw   t3, 4(t1)
keep:   addi t1, t1, 4
        bltu t1, t2, inner
        addi t0, t0, -1
        j    outer
done:   ret
Listing 11.9. The sort, a leaf code/bachelor-2/11-processor-and-pipelining/listings/bubble_sort.S
  1. How many instructions does one turn of the inner loop execute, without and with a swap?
  2. How many does one turn of the outer loop execute outside the inner loop?
  3. Prove that sort executes 52n(n−1)+6(n−1)+2S+3\frac{5}{2}n(n-1) + 6(n-1) + 2S + 3 instructions on n≥1n \ge 1 values, where SS is the number of swaps.
  4. Prove that SS is the number of inversions of the array, the pairs i<ji < j with ai>aja_i > a_j.
  5. The array has 65 inversions and main executes 141 instructions. Check the total against the model’s count of 964.
  6. How many loads and stores does the run execute?

Part II — Without forwarding.

$ python -m rv run bubble_sort.S
12 38 65 77 87 98 133 145 189 199 251 260 300 320 412 501 
Output 11.8. The program’s output.
  1. Which instructions of the inner loop depend on the instruction just before them?
  2. Show that without forwarding an instruction one place after its producer waits two cycles, and one two places after waits one.
  3. The model counts 552 stall cycles. Account for them: 120 turns of the inner loop, 16 of the printing loop, 15 outer turns, and 5 single stalls of two cycles each.
  4. Under “not taken”, which branches cost cycles, and how many cycles do they and the jumps lose in all?
  5. Compute the cycles and the CPI, and check them against Output 11.7.
  6. Which costs more here, the data hazards or the control hazards?

Part III — Forwarding and prediction.

  1. With forwarding, which dependences still stall, and how many cycles do they cost?
  2. Propose a change of the inner loop that removes them, and say what else it saves.
  3. The two-bit counters mispredict 60 branches: 41 of bge t4, t3, keep, 16 of the inner loop’s bltu, 2 of the printing loop’s, 1 of the outer test. Explain each number.
  4. Why is the swap test the hardest to predict?
  5. How many cycles do branches and jumps now lose?
  6. Compute the cycles and the CPI.

Part IV — The performance equation.

  1. With the stage delays of this chapter, the single-cycle clock is 800 ps and the pipeline’s 200 ps. Compute the time of the run on the single-cycle processor and on the pipeline in its three configurations.
  2. How many times faster than the single-cycle processor is the best pipeline? Why not 4?
  3. Which factor of the performance equation does each of the three improvements (pipelining, forwarding, prediction) act on?
  4. What would the CPI be with a perfect predictor?
  5. And with a perfect predictor and the change of question 14?
  6. State the result of the problem.
Solution

Solution of Problem 11.1.

1. Five without a swap (lw, lw, bge, addi, bltu); seven with one, the two stores added.

2. Six: blez, mv, slli, add, then addi and j after the inner loop.

3. The addi before the loop runs once. The outer loop runs for i=n−1i = n - 1 down to 1, and turn ii executes 6 instructions and ii inner turns of 5, plus 2 per swap: ∑i=1n−1(6+5i)=6(n−1)+52n(n−1)\sum_{i=1}^{n-1} (6 + 5i) = 6(n - 1) + \frac{5}{2}n(n-1), and 2S2S for the swaps. The last test blez, taken, and the ret add 2. In all 52n(n−1)+6(n−1)+2S+3\frac{5}{2}n(n-1) + 6(n-1) + 2S + 3; for n=1n = 1, the three instructions addi, blez, ret.

4. A swap exchanges two adjacent values aj>aj+1a_j > a_{j+1}. The relative order of every other pair is unchanged, so the number of inversions falls by exactly one. At the end the array is sorted, with no inversion; every swap removed one, so SS equals the initial number of inversions.

5. 600+90+130+3=823600 + 90 + 130 + 3 = 823 for sort, and 823+141=964823 + 141 = 964, the count of Output 11.7.

6. Loads: 2 per inner turn, 240, the 16 of the printing loop and the lw ra: 257. Stores: 2 per swap, 130, and sw ra: 131.

7. bge t4, t3 uses t4, loaded just before, and t3, two before; bltu t1, t2 uses t1, set by the addi just before. The two stores use the loaded values two and three places after their loads.

8. Without forwarding the consumer reads in ID, at the earliest in the producer’s WB cycle, x+2x + 2, so it is in EX at x+3x + 3. Placed jj after, it would naturally be in EX at x+jx + j: it waits 3−j3 - j cycles, 2 for j=1j = 1, 1 for j=2j = 2, none beyond.

9. Each inner turn stalls 2 at the bge and 2 at the bltu: 4×120=4804 \times 120 = 480. The stores are not stalled, the bge having waited already. The printing loop’s bltu follows its addi: 2×16=322 \times 16 = 32. Each outer turn’s add t2, a0, t2 follows the slli: 2×15=302 \times 15 = 30. Five pairs occur once (the sw ra after addi sp; the two la, addi after auipc; the addi t1, t0, 64 after the second la; the first blez after addi t0): 10. Total 480+32+30+10=552480 + 32 + 30 + 10 = 552.

10. The taken branches each lose 2: 105 of the inner bltu, 55 of the swap test, 15 of the printing loop and the last outer test, 176 in all, 352 cycles. The 16 jal (one call, 15 j) lose 1 each, and sort’s ret loses 2; main’s ret is the last instruction and loses nothing. 352+16+2=370352 + 16 + 2 = 370.

11. 964+4+552+370=1890964 + 4 + 552 + 370 = 1890 cycles, CPI 1890/964≈1.9611890/964 \approx 1.961.

12. The data hazards, 552 cycles against 370.

13. Only the load-use of t4 by the bge, one cycle per inner turn: 120.

14. Move addi t1, t1, 4 up between lw t4 and the bge, and write the stores as sw t4, -4(t1) and sw t3, 0(t1): the bge is then two places after the load, and no stall remains, for the same number of instructions; 120 cycles saved. A further change saves loads too: after the compare the larger value is at p[1], so it can stay in a register as the next turn’s p[0], one load instead of two per turn.

15. The swap test depends on the data and is wrong 41 times out of 120. The inner bltu is wrong at each of the 15 exits and once at the very first turn, when its counter still says “not taken”: 16, as Proposition 11.13 predicts. The printing loop’s is wrong at its first turn and at its exit: 2. The outer blez is not taken 15 times and taken once, at the end: 1.

16. Its outcome is whether two neighbours are out of order, a property of the data, not of the loop’s structure; only as the sorted tail grows does it become regular.

17. 2×60+16+2=1382 \times 60 + 16 + 2 = 138.

18. 964+4+120+138=1226964 + 4 + 120 + 138 = 1226 cycles, CPI ≈1.272\approx 1.272.

19. Single-cycle: 964×800 ps=771.2964 \times 800\,\text{ps} = 771.2 ns. Pipeline: 1890×200=378.01890 \times 200 = 378.0 ns without forwarding, 1458×200=291.61458 \times 200 = 291.6 ns with it, 1226×200=245.21226 \times 200 = 245.2 ns with the predictor too.

20. 771.2/245.2≈3.15771.2 / 245.2 \approx 3.15 times faster. The cycle is 4 times shorter but the CPI is 1.272 instead of 1: 4/1.272≈3.154 / 1.272 \approx 3.15.

21. Pipelining acts on the cycle time (and raises the CPI from 1); forwarding and prediction act on the CPI. None changes the number of instructions.

22. Only the jumps would lose cycles, 18: (964+4+120+18)/964=1106/964≈1.147(964 + 4 + 120 + 18)/964 = 1106/964 \approx 1.147.

23. With no stall either: 986/964≈1.023986/964 \approx 1.023, close to the ideal.

24. In the five-stage model, forwarding and a two-bit predictor take the CPI of the bubble sort from 1.961 to 1.272: forwarding removes 432 of the 552 stall cycles, the predictor 232 of the 370 cycles lost to branches and jumps, and the run takes 1226 cycles instead of 1890, 35 % fewer.

本章定义的术语

在术语表中查看全部 1050 个术语