Picture a restaurant kitchen with one stove, forty orders, and a rule that every dish must reach the table at exactly the same instant, forever. That is a chip. The stove is a functional unit, the orders are your operations, the instant is the clock edge, and the head chef is a scheduler. This post is about how that chef thinks, first in general, then in one compiler, the Bluespec Compiler (bsc) [1], which writes its decisions to a file (.sched) that you can open and check. A rare thing in engineering: a compiler that shows its work.
Why anyone should care
The clock is brutally short. At 3 GHz a cycle lasts a third of a nanosecond. In that time light travels about 10 cm in vacuum, and a signal on silicon manages less. Every cycle, the hardware must settle who reads what, who writes what, and who waits, and there is nobody to ask.
There is no operating system to sort it out. Software has a scheduler too, but it is a program that runs on the machine, queues things, takes locks and apologises later. A circuit has no later. Its scheduler is not running on the chip, it is the chip, frozen into wires and enable gates at compile time.
Getting it wrong is not slow, it is wrong. In software a bad schedule makes the program slower. In hardware it can make two things drive one register in the same cycle, and the result is not a performance bug, it is a different circuit than the one you meant. A good schedule decides three things at once:
- Speed: how many cycles the job takes.
- Area: how many adders and multipliers you pay for, because units that never run together can be shared.
- Correctness: that every cycle behaves like some orderly sequence of events, so the design means what you wrote.
And the stakes grow with the designs. Nobody schedules a million operations by hand, so we hand the job to a compiler. Which means the useful question is not only “is the compiler clever” but “can I see why it decided that”. Hold that thought, because it is what the .sched file is for.
Part 1: Tetris with a deadline
Take a computation written as a sequence graph: nodes are operations, edges are data dependencies, and the graph has no cycles [2]. Scheduling gives each operation a control step, which is a clock cycle in the finished circuit, so that:
- No operation runs before its inputs are ready (the dependency constraint).
- No step uses more functional units than exist (the resource constraint).
- The total number of steps meets the latency budget (the timing constraint).
Two simple algorithms bound the answer. ASAP (as soon as possible) puts every operation in the earliest step its inputs allow. That gives the shortest possible schedule, but assumes you have unlimited adders and multipliers. ALAP (as late as possible) works backward from the latency budget and puts every operation in the latest step that still lets its successors finish in time.
The distance between the two is an operation’s mobility: how many steps it can slide without breaking anything. Operations with zero mobility form the critical path, and they are pinned. Everything else is wiggle room, and spending that wiggle room wisely is the scheduler’s entire job.
Mobility is where hardware cost is decided. If the three operations n1, n2 and n5 all sit in step 1, you need three units. If the scheduler moves n5 to step 3, step 1 needs only two and the third is never built. Moving work into the gaps so that fewer units are needed is the whole game of resource-constrained scheduling.
That problem is NP-hard in general, which is the polite way of saying nobody is going to solve it by staring harder. In practice tools use heuristics such as list scheduling, which fills each step greedily with the ready operations that have the least mobility [2]. The result is a table “operation to step”, which becomes a finite state machine: a counter that, in each step, enables the right units and steers the right registers. The notes on scheduling algorithms and abstract synthesis models in the archive have the formal treatment.
Part 2: Bluespec changes the question
Bluespec does not do any of that. There is no sequence graph, no control step assigned to each operation, no state machine generated for you. You write rules, each a guard and an action, and every rule is a candidate to fire in every clock cycle. What the scheduler decides is a different thing: which rules may fire in the same cycle, and in what logical order.
| Classical scheduling | Bluespec’s scheduler | |
|---|---|---|
| The unit being placed | An operation (add, multiply) | A rule or method (a whole atomic action) |
| What it decides | Which cycle each operation runs in | Which rules can fire together in one cycle |
| The constraint | Dependencies, units, latency | Conflicts between rules, as a partial order |
| The output | A table, then a state machine | Enable logic: AND gates on the rules that lose |
| Method | Heuristics such as list scheduling | A graph of pairwise relations, and a choice of winner |
The promise Bluespec makes is the one that matters: if a set of rules fires in one cycle, the result is as if they had run one after another in some order. The scheduler’s job is to find that order, or, when none exists, to stop one of the rules. The rest of this post is that job, drawn as hardware.
Part 3: Case study, or how to referee a clock cycle
A rule is a block of wires
A rule is a guard and a body that changes some registers. The mental model is software-like, one rule fires at a time, completely or not at all. The hardware does better than that, it fires many rules in the same clock cycle, as long as the result looks as if they had run one after another.
So what does a rule become? Take rule bump_a (a < 200); a <= a + 1; endrule. It becomes the circuit below. The guard is a comparator. The body is an adder. The register’s write-enable pin is driven by a signal bsc calls WILL_FIRE.
Two signals matter, and the whole scheduler is about the gap between them:
CAN_FIREis the rule’s guard and nothing else. It says “the conditions are right”.WILL_FIREisCAN_FIREAND NOT (any more urgent rule that conflicts with this one is firing). It says “go”.
A rule that conflicts with nobody has WILL_FIRE = CAN_FIRE, and costs no extra gates. Rules that can share a cycle cost no arbitration hardware at all. The cost sits in the rules that cannot.
Reads see the old value, writes land at the clock edge
One physical fact explains nearly every scheduling decision. In a clocked register, a read during the cycle sees the value from before the edge, and a write only takes effect at the next edge. Inside a single cycle, every read happens before every write, whatever order the rules are written in.
That is why rule swap; a <= b; b <= a; endrule really swaps two registers, with no temporary: both reads see the old values. No time travel is involved: the hardware simply looks before anyone moves.
It also gives the scheduler its one rule of thumb. If rule X reads register r and rule Y writes it, both can fire in the same cycle, but only in the order X, then Y, because X’s read must come before Y’s write. Bsc writes that as r.read SB r.write, “read is sequenced before write”.
Four relations, from “always fine” to “never”
Between any two methods (a rule is just a method nobody calls) bsc tracks one of four relations.
| Relation | Meaning | In hardware |
|---|---|---|
CF, conflict-free |
Same cycle, either order | No wires between them at all |
SB, sequenced before |
Same cycle, but the first goes first | The first behaves as if it ran first. Nothing may flow backwards from the second |
SBR, sequenced before, restricted |
Like SB, but not from the same rule |
One rule may not call both |
C, conflict |
Never in the same cycle | An AND gate on one of them (the arbiter) |
The happy case: a pipeline where everyone fires
Before the failures, here is what good Bluespec looks like. A three-stage pipeline: one rule produces numbers, one squares them, one consumes the results. The rules never touch the same register. They only meet at FIFOs, which is the trick, because a FIFO’s enq and deq are conflict-free.
import FIFO::*;
(* synthesize *)
module mkTop (Empty);
Reg#(UInt#(8)) n <- mkReg(1);
Reg#(UInt#(8)) cyc <- mkReg(0);
FIFO#(UInt#(8)) q1 <- mkFIFO;
FIFO#(UInt#(8)) q2 <- mkFIFO;
rule tick;
cyc <= cyc + 1;
if (cyc == 9) $finish;
endrule
rule produce (n <= 6);
q1.enq(n);
n <= n + 1;
$display("cycle %0d produce %0d", cyc, n);
endrule
rule square;
let x = q1.first;
q2.enq(x * x);
q1.deq;
$display("cycle %0d square %0d -> %0d", cyc, x, x * x);
endrule
rule consume;
$display("cycle %0d consume %0d", cyc, q2.first);
q2.deq;
endrule
endmodule
Build the schedule and a simulator, and run it:
bsc -sim -u -show-schedule Top.bsv # writes mkTop.sched
bsc -sim -e mkTop -o sim # links the Bluesim executable
./simThe schedule file is the quiet part, and quiet is good:
Rule: produce Predicate: q1.i_notFull && (n <= 8'd6) Blocking rules: (none)
Rule: square Predicate: q2.i_notFull && q1.i_notEmpty Blocking rules: (none)
Rule: consume Predicate: q2.i_notEmpty Blocking rules: (none)
Rule: tick Predicate: True Blocking rules: (none)
Logical execution order: produce, square, consume, tick
Nobody blocks anybody, so every rule’s WILL_FIRE is just its guard: no arbiter, no extra gates. The predicates are the FIFOs’ own “not full” and “not empty” signals, which is how backpressure comes for free. Now the simulation:
cycle 0 produce 1
cycle 1 produce 2
cycle 1 square 1 -> 1
cycle 2 produce 3
cycle 2 square 2 -> 4
cycle 2 consume 1
cycle 3 produce 4
cycle 3 square 3 -> 9
cycle 3 consume 4
cycle 4 produce 5
cycle 4 square 4 -> 16
cycle 4 consume 9
cycle 5 produce 6
cycle 5 square 5 -> 25
cycle 5 consume 16
cycle 6 square 6 -> 36
cycle 6 consume 25
cycle 7 consume 36
Read it by cycle. Cycle 0 only produce has anything to do. By cycle 2 all three stages are busy at once, and from cycles 3 to 5 the pipeline is full, with three rules firing in the same clock cycle, each on different data. After produce stops at 6, the pipeline drains. This is the scheduler’s whole promise made visible: many rules per cycle, and every cycle still behaves as if the rules had run one after another (the logical order above).
When two rules each insist on going first
Here are two rules that both read and write register a:
rule swap_ab; a <= b; b <= a; endrule
rule bump_a (a < 200); a <= a + 1; endrule
swap_ab reads a, so it must come before bump_a’s write of a. And bump_a reads a, so it must come before swap_ab’s write of a. Each must go first. That is a loop, and a loop has no sequential order. It is two people holding a door for each other, forever. So the two rules can never share a cycle.
This is real bsc output for that code, where bsc tells you what it decided:
Warning: "Top.bsv", line 18, column 8: (G0010)
Rule "swap_ab" was treated as more urgent than "bump_a". Conflicts:
"swap_ab" cannot fire before "bump_a": calls to a.write vs. a.read
"bump_a" cannot fire before "swap_ab": calls to a.write vs. a.read
Notice that the cause is a read-then-write on the same register, not a design mistake. Bsc found the loop on its own, and it names the two calls that collide (a.write vs. a.read). That is enough to fix it. There are two ways out, and one of them is a trap.
Way 1: pick the winner. Add (* descending_urgency = "swap_ab, bump_a" *) above the rules. The G0010 warning goes away, because you have now made the decision yourself. But look at what bsc says next:
Warning: "Top.bsv", line 8, column 8: (G0021)
According to the generated schedule, rule `bump_a' can never fire.
Rule: bump_a
Predicate: a < 8'd200
Blocking rules: swap_ab
swap_ab has no guard, so it is ready every single cycle, and bump_a never gets a turn. Choosing a winner does not give the loser a life. This is the trap: the warning disappeared and the bug did not.
Way 2: make the rules never want the same cycle. Give them guards that cannot both be true:
rule swap_ab (a >= 200); a <= b; b <= a; endrule
rule bump_a (a < 200); a <= a + 1; endrule
Bsc proves the two guards are disjoint, so there is no conflict to resolve:
Rule: swap_ab Blocking rules: (none)
Rule: bump_a Blocking rules: (none)
Logical execution order: swap_ab, bump_a
No warning, no arbiter, and both rules run when they should. When the scheduler complains, the best answer is usually to tell it something true about your design, not to overrule it.
The loser gets one AND gate
When two rules conflict and cannot be separated, bsc has to pick who wins. It picks a winner (the more urgent rule) and gates the other. The loser gets one AND gate and a polite “not this cycle”. Here is the generated hardware for a case where the loser can really fire, a rule feed (src < 150) and a rule wipe (src[0] == 1) that both want the same BVI port:
That is the entire cost. In the Verilog bsc generated:
assign acc$PUT_EN = src < 8'd150 ;
assign acc$CLR_EN = src[0] && src >= 8'd150 ;CLR_EN is the loser’s own guard (src[0]), AND NOT the winner’s guard (src < 150, which bsc simplified into src >= 150). Bsc has names for these signals, CAN_FIRE_RL_x and WILL_FIRE_RL_x, but it inlines them by default. Compile with -keep-fires and they stay in the Verilog as named wires. And one more thing you can see in the real output: if the winner’s guard is always true, the loser can never fire. Bsc says so (G0021: “rule wipe' can never fire") and deletes the loser's hardware. When I first wrotefeed` with no guard, that is what happened.
Reading the .sched file
Compile with -show-schedule and bsc writes <module>.sched, a plain-text summary of everything above for each synthesized module. It is the closest thing a compiler has to a confession. It has two flavours, one for modules that contain rules and one for modules that only offer methods to the outside.
A module with rules (a mkTop with three rules, feed, watch and wipe, using the BVI from the next section):
Rule schedule
-------------
Rule: feed
Predicate: src < 8'd150
Blocking rules: (none)
Rule: watch
Predicate: True
Blocking rules: (none)
Rule: wipe
Predicate: src[0]
Blocking rules: feed
Logical execution order: watch, feed, wipe
PredicateisCAN_FIRE: the guard, after simplification.Blocking ruleslists the more urgent rules that can stop this one.wipeis blocked byfeed, which is the AND gate of Figure 4. An empty list meansWILL_FIRE = CAN_FIRE.Logical execution orderis the imaginary sequential order that everything in one cycle is equivalent to. This is the “X, then Y” from before.watchcomes first because it reads the BVI’sget, andgetis declaredSBbothputandclear.
A module that offers methods (a counter, r is an 8-bit register):
module mkCtr (Ctr);
Reg#(Bit#(8)) r <- mkReg(0);
method Action inc; r <= r + 1; endmethod
method Action dec; r <= r - 1; endmethod
method Bit#(8) value = r;
endmodule
Method schedule
---------------
Method: inc
Ready signal: True
Sequenced after: value
Conflicts: inc, dec
Method: dec
Ready signal: True
Sequenced after: value
Conflicts: inc, dec
Method: value
Ready signal: True
Conflict-free: value
Sequenced before: inc, dec
Logical execution order: value, inc, dec
This is the same information, but now it is the module’s contract with its parent, and it is what the parent’s scheduler will use. Ready signal is the method’s guard, Sequenced before/after, Conflict-free and Conflicts are the four relations of the table above, listed per method.
Read the figure left to right. value only reads, so it comes first and never blocks anybody. inc and dec each read the register and write it, which is the loop of Figure 3 again, so the file says Conflicts: inc, dec. Notice that inc is listed as conflicting with itself: two calls to inc in the same cycle would be two read-modify-writes, which is the same loop.
What a BVI schedule line really says
Everything so far was bsc working out the relations itself, by looking at which registers each method touches. A BVI import removes that. The module is Verilog, bsc cannot see inside it, and so you have to tell bsc the relations, with schedule lines:
interface Acc_Ifc;
method Action put(Bit#(8) x);
method Action clear;
method Bit#(8) get;
endinterface
import "BVI" acc =
module mkAcc (Acc_Ifc);
default_clock clk(CLK, (*unused*) CLK_GATE);
default_reset rst(RST_N);
method put(PUT_X) enable(PUT_EN) clocked_by(clk) reset_by(rst);
method clear() enable(CLR_EN) clocked_by(clk) reset_by(rst);
method GET_X get() clocked_by(clk) reset_by(rst);
schedule get CF get;
schedule get SB (put, clear);
schedule put C (put, clear);
schedule clear C clear;
endmodule
Each line is a promise about the Verilog:
get SB (put, clear): “readinggetnever sees aputorclearfrom the same cycle”. The Verilog must really behave that way, for example by returning a register’s old value.put C (put, clear)andclear C clear: “the module cannot take two of these in one cycle”. Perhaps they write the same register, so bsc must never enable both.- A line like
schedule m CF (a, b, c)names every pair between the left list and the right list. It is a table written as one sentence.
The Verilog behind that import is small. It honours the promises: GET_X is a register, so get sees last cycle’s value, and clear beats put, so the two truly cannot both act.
module acc(CLK, RST_N, PUT_X, PUT_EN, CLR_EN, GET_X);
input CLK, RST_N, PUT_EN, CLR_EN;
input [7:0] PUT_X;
output [7:0] GET_X;
reg [7:0] total;
assign GET_X = total; // registered: get sees last cycle's value
always @(posedge CLK)
if (!RST_N) total <= 8'd0;
else if (CLR_EN) total <= 8'd0; // clear beats put, so they truly conflict
else if (PUT_EN) total <= total + PUT_X;
endmoduleAnd a top module that uses it, with the three rules from the .sched listing above:
(* synthesize *)
module mkTop (Empty);
Acc_Ifc acc <- mkAcc;
Reg#(Bit#(8)) src <- mkReg(0);
Reg#(Bit#(8)) seen <- mkReg(0);
rule feed (src < 150); acc.put(src); src <= src + 1; endrule
rule watch; seen <= acc.get; endrule
rule wipe (src[0] == 1); acc.clear; endrule
endmodule
bsc -verilog -u -show-schedule Top.bsv # mkTop.v, mkTop.sched
iverilog -o sim mkTop.v acc.v # bsc's Verilog and the hand-written one fit togetherThe schedule it produces is the one listed earlier, and you can now trace every line of it back to an annotation. watch goes first because get SB put, and wipe is blocked by feed because put C clear. The whole schedule came from four lines.
Bsc takes the lines on trust, because it cannot read the Verilog. It checks what it can see, which is how you call the module. Call one method with two different arguments in the same cycle and it refuses, since that needs two input ports:
Error: "Top.bsv", line 12, column 11: (G0002)
`acc.put' needs more than 1 ports for the following uses:
`acc.put 8'd1' at "Top.bsv", line 12, column 11
`acc.put 8'd2' at "Top.bsv", line 12, column 11
But whether the Verilog can really do two things at once is something only you know. So lie, and bsc believes you. Declare schedule (put, clear) CF (put, clear) against the same acc.v, call put from one rule and clear from another, and bsc compiles it without a single warning:
assign acc$PUT_EN = 1'd1 ;
assign acc$CLR_EN = 1'd1 ;Both enables are high in every cycle, and the Verilog quietly decides that clear wins. The schedule file says Blocking rules: (none) and looks perfect. It is a lovely, confident, wrong schedule. A schedule line is part of the hardware’s specification, so it deserves the same care as the Verilog next to it.
Leave a pair out and bsc does not guess optimistically either:
Warning: "Top.bsv", line 11, column 20: (P0200)
No scheduling annotation given between method `put' and methods (`put', `clear')
Assuming conflict.
Warning: "Top.bsv", line 11, column 20: (P0200)
No scheduling annotation given between method `get' and methods (`put', `clear')
Assuming sequenced-before.
I got that by deleting the get SB and put C lines. Pairs of action methods are assumed to conflict. A value method against an action method is assumed SB, with the value method first. Both are the safe choice.
What to tell people at parties
- Scheduling is a question you can ask at two levels. “In which cycle does each operation run” and “which actions may share a cycle” are different problems, with different algorithms and different hardware.
- Reads before writes explains most of it. Inside one clock cycle every read sees the old value and every write lands at the edge. Almost every conflict in Bluespec is a read-then-write loop between two rules.
- A conflict costs one AND gate. Rules that can share a cycle cost nothing. Only the loser of a conflict gets an arbiter, so scheduling in Bluespec is mostly about not creating loops.
- Read the
.schedfile. It is the compiler showing its work: the guards, who blocks whom, and the order everything is equivalent to. - Where annotations replace analysis, they are a promise. A BVI
scheduleline is trusted, not checked, so it is worth writing as carefully as the Verilog.