Pipeline diagram with branch bubbles

A pipeline diagram has one row per instruction and one column per clock cycle. A taken branch makes the pipeline wait two cycles before it can fetch the right next instruction.

What to build

A program that draws the pipeline diagram of a list of instructions on the 5-stage pipeline.

Requirements

  • The stages are IF, ID, EX, MEM, WB, each one cycle long, and instructions are fetched one per cycle.
  • An instruction is either op (any ordinary instruction) or branch (a taken branch). After a taken branch, the next instruction is fetched two cycles later than it otherwise would be (two bubbles).
  • Print one row per instruction, I1:, I2: and so on, followed by one cell for each cycle from 1 to the last WB cycle, separated by single spaces. A cell is the stage name, or .. when the instruction is not in the pipeline.

Input

A line with n, then n lines, each op or branch.

Output

n lines.

Constraints

1 ≤ n ≤ 12.

Example

Input:

3
op
op
op

Output:

I1: IF ID EX MEM WB .. ..
I2: .. IF ID EX MEM WB ..
I3: .. .. IF ID EX MEM WB

Why it works

Without bubbles, instruction i enters IF in cycle i + 1 and moves one stage per cycle. Each taken branch before it delays its fetch by two cycles, so the whole row shifts right.

Examples

Example 1 · Input
3
op
op
op
Expected output
I1: IF ID EX MEM WB .. ..
I2: .. IF ID EX MEM WB ..
I3: .. .. IF ID EX MEM WB
Example 2 · Input
2
branch
op
Expected output
I1: IF ID EX MEM WB .. .. ..
I2: .. .. .. IF ID EX MEM WB

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

If t is the number of taken branches before instruction i (counting from 0), then instruction i is fetched in cycle 1 + i + 2 * t.

Hint 2

Its stage at cycle c is the stage number c - fetch_cycle in the list IF, ID, EX, MEM, WB; outside 0 to 4 print "..".

Hint 3

The last cycle is the last instruction's fetch cycle + 4.

Solution

Show one correct solution (try it yourself first)
STAGES = ["IF", "ID", "EX", "MEM", "WB"]
n = int(input())
kinds = [input().strip() for _ in range(n)]
fetch, taken = [], 0
for i in range(n):
    fetch.append(1 + i + 2 * taken)
    if kinds[i] == "branch":
        taken += 1
total = fetch[-1] + 4
for i in range(n):
    cells = []
    for c in range(1, total + 1):
        s = c - fetch[i]
        cells.append(STAGES[s] if 0 <= s < 5 else "..")
    print(f"I{i + 1}: " + " ".join(cells))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Pipelining →