Inferred Latch in Verilog: What It Is and How to Avoid It
inferred latch in Verilog happens when the code does not specify outputs for all conditions inside a combinational block, causing the synthesis tool to create a memory element to hold the previous value. To avoid inferred latches, always assign values to outputs in every possible condition or use always @(*) blocks with complete case or if-else statements.How It Works
Imagine you are telling a friend to remember a number only if you say so, but sometimes you forget to tell them what to do. In Verilog, if you write code that does not clearly say what the output should be for every input, the tool assumes you want to remember the last output value. This creates a latch, which is like a small memory that holds the value.
This happens because combinational logic must produce an output for every input instantly. If some inputs are missing output assignments, the synthesis tool infers a latch to keep the previous output. This can cause unexpected behavior in your hardware, making it harder to debug and slower to work.
Example
This example shows a Verilog block that causes an inferred latch because the output y is not assigned in all cases.
module latch_example(input wire a, b, output reg y);
always @(*) begin
if (a) begin
y = b;
end
// Missing else: y is not assigned when a is 0
end
endmoduleWhen to Use
Inferred latches are usually unintended and should be avoided in most digital designs because they can cause timing issues and unpredictable behavior. However, if you want to create a memory element that holds a value until changed, you might use latches intentionally, but this is rare and requires careful design.
To avoid inferred latches, always write your combinational logic with complete assignments. Use always @(*) blocks and cover all input cases with if-else or case statements. This practice ensures your design is purely combinational and easier to understand and test.
Key Points
- An inferred latch happens when outputs are not assigned in all conditions inside a combinational block.
- It causes the synthesis tool to create memory elements unintentionally.
- Use
always @(*)and completeif-elseorcasestatements to avoid latches. - Inferred latches can cause bugs and timing problems in hardware.
- Intentional latches are rare and need careful design.