Search code examples
vhdlfpga

VHDL - Why is it bad practice to not include an else-condition in a "process" block?


I'm watching a beginner tutorial on VHDL. The lecturer says that it's bad practice to not include an else-condition inside a "process" block because it will create a latch and is bad for timing in advance circuits. He said that including an else-condition will create a mux instead and is better to use in most case. Why is that? snippet from lecture video

Why is a latch design bad for timing and what makes the mux design better?


Solution

  • The point is to make VHDL code that results in the design you want, and the risk is that you will inadvertently create a latch.

    There are several basic constructions in VHDL, that can illustrate this.

    Mux by process with if-then-else, can be made with this code:

    process (all) is  -- Mux
    begin
      if sel = '0' then
        z <= a;
      else
        z <= b;
      end if;
    end process;
    

    Mux by process with if-then and default assign, can be made with this derived code:

    process (all) is  -- Mux
    begin
      z <= b;  -- Default b, thus for sel = '1', since no overwrite
      if sel = '0' then
        z <= a;
      end if;
    end process;
    

    However, if you want to make a mux, then a better coding style is by continuous assign with this code:

    z <= a when (sel = '0') else b;
    

    Finally, what can lead to a latch with a process, is if the resulting output is not assigned in all branches of the code. That can occur, if the if-then does neither have an else, nor a default assign to the output, like this code:

    process (all) is  -- Latch
    begin
      if en = '1' then
        q <= d;
      end if;
    end process;
    

    So a good rule when designing combinatorial logic using a process, is to have an initial line that makes a default assignment to the resulting output, for example just assing undefined 'X'. A latch is thereby avoided, and functional verification should catch the undefined 'X', if this is a bug.

    Also, remember to check the syntheis report for warnings about created latches, since that is most likely a bug in the design.