What the Simulator Does with Your RTL: Event Regions and Races
Follow one clock edge through the simulator's event regions, and predict which value each statement reads.
You Will Be Able To
- Explain what compilation and elaboration fix before time 0.
- Predict which value a statement reads from the region it runs in.
- Find a race that no single block shows: two processes, or a clock made by an assignment.
- Choose between
$display,$strobeand$monitorfor a value at a clock edge.
- Lesson
- R11.1
- Time
- 30 min
- Runs on
- Your browser
- Check
- 5 questions
A block takes every second sample from a stream. Each register uses a nonblocking assignment, as the rule says. The capture register still takes the sample one edge too early.
q (clock made by <=) is the shipped design. q (enable) is the same block with one clock and an enable.- Cycle 0
Edge 2:
s_qtakes 1. The brief saysqtakes the values_qheld before the edge, which is 0. - Cycle 0
The shipped
qshows 1. It reads_qafter the update of this same edge. - Cycle 2
Edge 4: the same again.
qshows 3, the news_q, where the brief gives 2. - Cycle 2
The enable version reads the old
s_qevery time. Both versions build 10 cells.
Icarus 12 and Verilator 5.052 print the same lines. The cause is the order of events inside one time slot.
Before Time 0: Compilation and Elaboration
A simulator does two jobs before it runs anything. Compilation checks each file against the language rules. Elaboration builds the design tree: it binds each instance to its module, fixes every parameter and expands every generate.
After elaboration, widths and instance names can no longer change. A synthesizer elaborates in the same way before it builds gates.
tb.g[0] exists, tb.g[1] exists, tb.u7: W=7 bits(s)=8 and tb.u4: W=4 bits(s)=5. One module became two different adders.module add #(parameter int W = 4) (
input logic [W-1:0] a, b,
output logic [W:0] s
);
if (W < 2) $error("W must be at least 2"); // checked at elaboration
assign s = a + b;
initial $display("%m: W=%0d bits(s)=%0d", W, $bits(s));
endmodule
module tb;
logic [7:0] s8;
logic [4:0] s4;
add #(.W(7)) u7 (.a(7'd100), .b(7'd100), .s(s8));
add u4 (.a(4'd9), .b(4'd9), .s(s4));
for (genvar i = 0; i < 2; i++) begin : g
initial $display("%m exists");
end
endmodule| Fixed at elaboration | Example above | So in RTL |
|---|---|---|
| Parameter values | W is 7 in u7 and 4 in u4 | a parameter can size a vector; a signal cannot |
| Generate blocks | g[0] and g[1] exist as two scopes | a generate loop makes copies, never iterations in time |
| Checks on parameters | the $error under if (W < 2) | a bad parameter can stop the tool before any run |
| Compile order | a package or typedef comes before its user | lesson R9.3 covers file order |
An elaboration check is only as strong as the tool. See the note below.
Time, Units and Precision
Simulated time moves in steps. The time unit says what #1 means. The precision says how finely a delay is rounded.
| With a unit of 1 ns and a precision of 100 ps | Result |
|---|---|
#1.26 | rounded to 1.3 ns: $realtime prints 1.30 |
#0.04 after it | rounded to 0: $realtime still prints 1.30 |
| RTL with no delays | every assignment takes zero time; only the clock moves time |
Measured on Icarus 12 and Verilator 5.052 with the directive timescale 1ns/100ps.
The directive timescale applies to every file compiled after it, so its effect depends on file order. The keywords timeunit and timeprecision sit inside a module and affect only that module.
Synthesizable RTL has no delays. All of its work at a clock edge happens at one instant, so the order inside that instant decides the result.
One Time Slot, Several Regions
A time slot is everything that happens at one simulated time. The simulator splits it into event regions and empties them in a fixed order.
- Step
- Structure
- clk rises: Active
Every block waiting on
clkruns, in an order the simulator picks. Each<=reads its right side now and waits.Follow the calls, values and waits
- call s_q <= d: read d: Preponed → Active
- NBA
Active and Inactive are empty. Every left side updates together:
s_qtakesd, andclk2flips.Follow the calls, values and waits
- data s_q takes d: Active → Inactive
- data s_q takes d: Inactive → NBA
- A delta: back to Active
The updates are new events. A block waiting on
clk2wakes now. It readss_qafter the update.Follow the calls, values and waits
- data clk2 rises: NBA → Active
- call q <= s_q: reads new s_q: NBA → Active
- Observed and Reactive
Concurrent assertions evaluate the values they sampled in Preponed. Testbench program code and assertion actions run after the design has settled.
- Postponed
Nothing can change any more.
$strobeand$monitorprint the final values of the slot, and time moves on.
Read the diagram as text
- Preponed: assertions sample
- Active: =, assign, right side of <=
- Inactive: #0 waits here
- NBA: left side of <= updates
- Observed: assertions evaluate
- Reactive: program blocks, actions
- Postponed: $strobe, $monitor
- Next time slot: time moves on
- Preponed → Active
- Active → Inactive
- Inactive → NBA
- NBA → Observed
- Observed → Reactive
- Reactive → Postponed
- Postponed → Next time slot
- NBA → Active: new events
- Reactive → Active: new events
RTL lives in Active and NBA. A pass from one region to the next is a delta; a slot can take many.
This order is why <= makes flops safe. Every block reads old values in Active. The new values appear only in NBA, when all the reading is done.
Processes Run in Any Order
Inside one begin-end, statements run top to bottom. Between two blocks there is no such rule. Both wake on the same edge, and the simulator may run either one first.
b first in the file
always @(posedge clk) b = a;
always @(posedge clk) c = b;
With a = 1 and b = c = 0 before the edge: Icarus 12 prints b=1 c=0. Verilator 5.052 prints b=1 c=1.
c first in the file
always @(posedge clk) c = b;
always @(posedge clk) b = a;
Icarus 12 prints b=1 c=1. Verilator 5.052 prints b=1 c=1. Swapping two lines changed one simulator's result.
All four results are legal. The code has a race: its result depends on an order that the language leaves open. Synthesis sees two flops in a row and builds the same hardware each time.
| Also left open | Icarus 12 | Verilator 5.052 |
|---|---|---|
An assign w = a & b; fed by blocking writes, read later in the same block | the block sees the old value of w | the block sees the new value |
Which initial block of two instances prints first | u7 before u4 | u4 before u7 |
$monitor when a = and a <= change at one edge | one line, with the final values | two lines, the first with the old q |
Three more orders measured on this site. None of them is wrong.
A delay of #0 looks like a way to choose the order. It moves the rest of the block to the Inactive region, behind every Active process of the slot.
A Clock Made by an Assignment Arrives One Delta Late
Return to the opening figure. clk2 is written with <=, so it changes in the NBA region. s_q changes in that same region.
The block on posedge clk2 wakes one delta later, back in Active. By then s_q already holds its new value. The nonblocking rule protects readers on the same clock only.
A second clock
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) clk2 <= 1'b0;
else clk2 <= ~clk2;
always_ff @(posedge clk2 or negedge rst_n)
if (!rst_n) q <= 4'h0;
else q <= s_q;
q reads s_q after the update. On this flow: 10 cells, 9 flops, and the q flops have their own clock net.
One clock and an enable
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) en_q <= 1'b1;
else en_q <= ~en_q;
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) q <= 4'h0;
else if (en_q) q <= s_q;
q reads the old s_q. On this flow: 10 cells, 9 flops, every flop on clk.
In silicon the left version is a hold-time race. The divided clock is late by one flop delay, and the data is late by one flop delay. Which wins depends on the layout.
Printing from a Clocked Block
The three print tasks differ only in the region where they read the values.
q is 0 and r is 0. The first edge loads 3 into q and 4 into r.module tb;
logic clk = 0;
logic [3:0] d = 4'd3, q = 4'd0, r = 4'd0;
always @(posedge clk) begin
q <= d; // nonblocking
r = d + 4'd1; // blocking
$display("display: q=%0d r=%0d", q, r);
$strobe ("strobe: q=%0d r=%0d", q, r);
end
initial $monitor("monitor: t=%0t q=%0d r=%0d", $time, q, r);
initial begin
#5 clk = 1;
#5 clk = 0; d = 4'd7;
#5 clk = 1;
#5 $finish(0);
end
endmodule| Task | Prints in | First edge, Icarus 12 | Reads |
|---|---|---|---|
$display | Active, where the statement stands | display: q=0 r=4 | the old q, the new r |
$strobe | Postponed, once per call | strobe: q=3 r=4 | the final values of the slot |
$monitor | Postponed, in every slot where an argument changed | monitor: t=5 q=3 r=4 | the final values of the slot |
The whole run prints seven lines on Icarus 12. Only one $monitor can be active at a time.
A Loop with No Delay Never Lets Time Move
A time slot ends only when every region is empty. Combinational logic that feeds itself keeps making new events, so the slot never ends.
A wire that inverts itself
module osc (input logic en, output logic y);
assign y = en & ~y;
endmodule
With en at 1, Icarus 12 prints nothing more and the site stops the run at its time limit. Verilator 5.052 reports %Error-DIDNOTCONVERGE: Active region did not converge.
The same toggle through a flop
module osc (input logic clk, en, output logic y);
always_ff @(posedge clk)
if (en) y <= ~y;
endmodule
One change per clock edge. The flop breaks the loop, so each slot ends and time moves on.
Synthesize refuses the left module as a logic loop, as lesson R1.3 showed for a latch written by accident.
The Lab: One Clock, and an Enable
| Port | Direction | Width | Meaning |
|---|---|---|---|
| clk | input | 1 | clock |
| rst_n | input | 1 | reset, asynchronous, active-low |
| d | input | [3:0] | the sample stream |
| s_q | output | [3:0] | registers d at every edge |
| q | output | [3:0] | at every second edge, takes the value s_q held before that edge |
- Clock
- rising edge
- Reset
rst_nasynchronous, active-low.qfirst loads at the first edge after reset- Corner cases
- the edge where
s_qandqboth load. Done when: Run showsqas 0, 0, 2, 2, 4, 4, and Synthesize still reports 10 cells
Run as shipped
qreads 1, 1, 3, 3, 5, 5. At edge 2 it already shows the 1 thats_qtook at that same edge.Find the late clock
Every assignment is nonblocking. Look at the event lists: two blocks wake on
clk, and the third wakes onclk2, which changes in the NBA region.Use one clock
Replace
clk2with the enable shown below and Run.qreads 0, 0, 2, 2, 4, 4: the olds_qeach time.Check the gates
Synthesize both. Each is 10 cells and 9 flops. In the enable version every flop shares one clock, so timing analysis sees one clock domain.
The fix: an enable on the one clock
$_DFFE_PN0P_, 4 $_DFF_PN0_, 1 $_DFF_PN1_ and 1 $_NOT_. The shipped design has 9 $_DFF_PN0_ and 1 $_NOT_. logic en_q; // 1 on every second edge
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) en_q <= 1'b1;
else en_q <= ~en_q;
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) s_q <= 4'h0;
else s_q <= d;
always_ff @(posedge clk or negedge rst_n) // one clock; the enable picks the edges
if (!rst_n) q <= 4'h0;
else if (en_q) q <= s_q;Asked in interviews
Why does a nonblocking assignment prevent a race between two flops?
Its right side is read in the Active region and its left side updates in the NBA region. Every block on that clock reads old values first, so the order of blocks does not matter.
What is the difference between
$displayand$strobe?$displayprints where it stands, in the Active region, so it shows a register's old value.$strobeprints in the Postponed region, after every update of the time slot.What is a delta cycle?
One pass through the event regions with no change of simulated time. An update in the NBA region can wake more processes, and the simulator loops until none are left.
Try It
The bench changes d 1 ns after an edge and prints 1 ns after the next one. s_q shows the d of its edge on every line, as it should.
q loads at edges 2, 4 and 6. Each time it shows the value on the same line as s_q. It read s_q one delta after the update.
Synthesize reports 10 cells: 9 $_DFF_PN0_ and 1 $_NOT_, with 0 latches and 1 level of logic. Lint prints nothing.
Synthesize the design to measure its cells and inspect the mapped gates.
e2 d=1 s_q=1 q=1 e3 d=2 s_q=2 q=1 e4 d=3 s_q=3 q=3 e5 d=4 s_q=4 q=3 e6 d=5 s_q=5 q=5 e7 d=6 s_q=6 q=5Original design · 10 cells · 9 flip-flops · 0 latches · 1 logic levels. Synthesis uses Yosys; counts depend on the toolchain.
Read included file: tb.sv
`timescale 1ns/1ps
module tb;
logic clk = 0;
always #5 clk = ~clk; // rising edges at 5, 15, 25, ...
logic rst_n = 1; // falls at 1 ns, rises 1 ns after edge 1
int edge_n = -1;
always @(posedge clk) edge_n = edge_n + 1;
logic [3:0] d = 0;
logic [3:0] s_q, q;
half_rate dut (.*);
task automatic tick();
@(posedge clk); #1;
if (rst_n) $display("e%0d d=%h s_q=%h q=%h", edge_n, d, s_q, q);
endtask
initial begin
#1 rst_n = 0; tick(); tick(); rst_n = 1;
d = 4'h1; tick();
d = 4'h2; tick();
d = 4'h3; tick();
d = 4'h4; tick();
d = 4'h5; tick();
d = 4'h6; tick();
$finish(0);
end
endmodule
Check Yourself
Common Mistakes
Wrong Sample a design output in the bench at the same clock edge that updates it.
The bench process and the design process run in the same region, in an order the simulator picks.
Fix Sample after the edge, as the lab bench does 1 ns later, or print with $strobe.
Wrong Put the timescale directive in one file and assume that every module uses it.
The directive applies only to files compiled after it, so a new file order changes the delays.
Fix State timeunit and timeprecision inside each module that has delays.
Wrong Add #0 to push a statement behind the one it races with.
#0 only moves the statement to the Inactive region of the same slot, and a second #0 elsewhere brings the race back.
Fix Remove the cause: write the register with <=, so its readers see the old value in the Active region. Synthesize refuses a #0 in any case.
always @(posedge clk) #0 c = b;
always @(posedge clk) b = a;always_ff @(posedge clk) c <= b;
always_ff @(posedge clk) b <= a;Wrong Rely on an elaboration $error to stop a bad parameter in every tool.
Icarus 12 and Verilator 5.052 on this site ignored the check and ran the simulation.
Fix Keep the check, and read the synthesis log too: Synthesize does stop on it.
Remember
- Elaboration fixes parameters, widths and generate copies before time 0. Simulators and synthesizers both do it.
- RTL runs in two regions: Active reads and computes, NBA updates. That split is what makes
<=safe. - Ready processes run in any order. A result that depends on the order is a race, even if today's simulator hides it.
- A clock written by an assignment arrives one delta late. Use one clock and an enable.
$displayshows values in mid-slot.$strobeand$monitorshow them when the slot ends.