What Causes Latch Inference in Verilog: Explanation and Examples
Latch inference in Verilog happens when a signal is assigned conditionally without specifying all possible cases, causing the synthesis tool to create a memory element to hold the previous value. This usually occurs inside
always blocks when some branches do not assign a value to a variable, leading to unintended latches.Syntax
Latch inference typically occurs in always blocks with incomplete assignments. The common pattern looks like this:
always @(condition): Defines when the block runs.- Conditional statements like
iforcaseinside the block. - Assignments to variables that are not made in every possible condition.
If a variable is not assigned in all branches, the synthesizer infers a latch to remember the previous value.
verilog
always @(posedge clk) begin if (enable) begin q = d; end // No else branch assigning q end
Example
This example shows latch inference because q is assigned only when enable is true. When enable is false, q keeps its old value, so a latch is created.
verilog
module latch_inference_example( input wire clk, input wire enable, input wire d, output reg q ); always @(posedge clk) begin if (enable) begin q <= d; // Assigned only when enable is true end // No else: q holds previous value, latch inferred end endmodule
Common Pitfalls
Common mistakes that cause latch inference include:
- Not assigning a variable in all branches of an
if-elseorcasestatement. - Using blocking assignments (
=) in sequential logic instead of non-blocking (<=). - Forgetting the
elsebranch or default case to cover all conditions.
To avoid latches, always assign variables in every possible path or use default assignments at the start of the always block.
verilog
/* Wrong: latch inferred */ always @(posedge clk) begin if (enable) begin q = d; end // else missing end /* Correct: no latch */ always @(posedge clk) begin if (enable) begin q <= d; end else begin q <= 1'b0; // assigned in else branch end end
Quick Reference
Tips to prevent latch inference:
- Always assign outputs in every branch of conditional statements.
- Use
elseordefaultcases to cover all conditions. - Prefer non-blocking assignments (
<=) in sequential logic. - Initialize variables at the start of
alwaysblocks if needed.
Key Takeaways
Latch inference happens when variables are not assigned in all conditional branches inside an always block.
Always provide assignments for every possible condition to avoid unintended latches.
Use non-blocking assignments (<=) in sequential logic for clarity and correctness.
Including else or default cases prevents latch creation by covering all scenarios.
Initializing variables at the start of always blocks can help avoid latch inference.