MIPS 5-stage pipeline is a classic way to illustrate CPU pipelining, and it is a common interview questions for new grads and junior engineers. The 5-stage pipeline consists of the following stages:
IF – instruction fetch
ID – instruction decode and operand fetch
EX – instruction execution
MEM – memory access
WB – write back
IF stage can be summarized using the formula below:
IR <- Mem[PC]
PC <- PC + 4
where PC indicates the Program Counter or address of the next instruction, and IR means instruction
In this stage, CPU fetches instruction using PC and PC gets updated to point to next instruction. Here we assume each instruction takes 4 bytes.
ID stage can be summarized using the formula below:
A <- Regs[IR[10:6]]
B <- Regs[IR[15:11]]
Imm <- IR[15:0]
where A and B are both operands, and Imm is immediate operand.
In this stage, CPU may use IR[10:6] and IR[15:11] as the register indices to read operands from register file, and may extract immediate operand from IR[15:0]
EX stage can be summarized using the formula below:
ALU output <- A + Imm (compute the effective memory address)
ALU output <- A op B (reg-to-reg operation)
ALU output <- A op Imm (reg-to-imm operation)
ALU output <- PC + Imm (calculate target address for branch)
where op is certain operation defined by the instruction.
In this stage, ALU is used to compute the effective address of memory operation, perform register to register / immediate operand operation, or calculate target address for branch. The branch condition is also decided this this stage.
MEM stage can be summarized using the formula below:
LMD <- MEM[ALU output] (memory load)
MEM[ALU output] <- B (memory store)
if (condition is met) PC <- ALU output
else PC <- PC + 4
where LMD is the pipeline register to temporarily hold the data loaded from memory.
In this stage, memory load and memory store operations are performed. In addition, branch operation will also be completed in this cycle. If the condition obtained in EX stage is met, PC will be loaded with ALU output from EX stage and the program branches; otherwise the program is executed sequentially and PC gets updated to point to next instruction.
WB stage can be summarized using the formula below:
Regs[IR[20:16]] <- ALU output (reg-to-reg operation)
Regs[IR[15:11]] <- ALU output (reg-to-imm operation)
Regs[IR[15:11]] <- LMD (memory load)
In this stage, the final results are written back to register file. For register to register operation, result is written to the register indexed by IR[20:16]; For register to immediate operand operation, result is written to register indexed by IR[15:11]; For memory load operation, data loaded to memory is written to register indexed by IR[15:11].
The familiarity of how does MIPS 5-stage pipeline work and what role each stage is in the overall big picture is a must in hardware interview questions.