Verilog latch inference and prevention
Understand why incomplete combinational assignments infer latches and apply reliable default-assignment and complete-branch patterns.
Why a latch appears
A combinational process must define every output for every possible input combination. If an output is not assigned on one path, it must retain its previous value. Synthesis therefore needs storage and infers a level-sensitive latch.
always @* begin
if (enable)
y = data; // y is unassigned when enable is 0
end
This code infers a latch. If the intended inactive value is zero, add an else or a default assignment.
always @* begin
y = 1'b0;
if (enable)
y = data;
end
Reliable patterns
Assign defaults at the beginning of a combinational block, then override them in selected branches. For a case, either cover every possible value or provide a meaningful default.
always @* begin
next_state = state;
grant = 2'b00;
case (state)
IDLE: if (request) next_state = BUSY;
BUSY: begin
grant = 2'b01;
if (done) next_state = IDLE;
end
default: next_state = IDLE;
endcase
end
The default for next_state intentionally holds the FSM state through the clocked state register; it does not create a latch inside this combinational block because next_state is assigned immediately.
Verification
Treat unexpected latch warnings as defects. Run lint, inspect the synthesized cell report, and test all branch conditions. Do not silence the warning merely because simulation appears correct—the untested path may preserve stale data.