RTL Reference

always_ff

A procedure for flip-flops. It runs on a clock edge and must use nonblocking assignments.

Syntax

always_ff @(posedge clk or negedge rst_n)
  if (!rst_n) q <= '0;
  else        q <= d;

Rules

  • It needs exactly one event control, at the top. No other delay or wait may appear inside.
  • Use nonblocking assignments (<=). Every flop then reads the old value of every other flop.
  • A variable written here may not be written by any other procedure.
  • Put an asynchronous reset in the event list. Leave a synchronous reset out of it.

Example

module tb;
  logic clk = 0, rst_n = 0;
  logic [3:0] count;

  always #5 clk = ~clk;

  always_ff @(posedge clk or negedge rst_n)
    if (!rst_n) count <= '0;
    else        count <= count + 1;

  initial begin
    #12 rst_n = 1;
    repeat (3) begin
      @(posedge clk); #1;
      $display("t=%0t count=%0d", $time, count);
    end
    $finish;
  end
endmodule
Output on Icarus Verilog 12
t=16 count=1
t=26 count=2
t=36 count=3

Run It in the Playground

Common Mistake

Blocking assignments in a clocked block

always_ff @(posedge clk) begin
  a = d;   // a changes now
  b = a;   // b gets the new a: one flop, not two
end

With =, the second line reads the value the first line just wrote. The two-stage shift register becomes one stage.

Fix: Write a <= d; b <= a;. Both right-hand sides are read before either flop changes.

Learn It Properly

These lessons teach it step by step, with practice problems.

Standard

IEEE 1800-2023, 9.2.2.4.