Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท SystemVerilog Features

always_comb, always_ff, Packages and Functions in SystemVerilog

Use SystemVerilog always_comb, always_ff and always_latch to state your intent, write unique and priority case statements, and share types and functions with packages.

Plain Verilog has one always block for everything, and the synthesizer guesses from its contents whether you meant combinational logic, a flip-flop or a latch. Guessing causes the nastiest bug in RTL design: logic that simulates correctly and synthesizes into something else. SystemVerilog adds intent-revealing blocks that the compiler checks, plus packages for sharing definitions. These are the first SystemVerilog features worth adopting in every project.

The code here is read-only SystemVerilog (no simulator runs on this site); the C programs are labelled stand-ins that model what the blocks do.

always_comb

always_comb means "this block is purely combinational". Compared with always @* it has three advantages:

  1. It runs once at time 0, so outputs have correct values from the start even if no input changed.
  2. Its sensitivity list is computed for you and includes signals read inside called functions.
  3. Tools warn (or fail) if the block infers a latch, i.e. an output is not assigned on every path.
SYSTEMVERILOG
always_comb begin
  y = 1'b0;                       // default: no latch
  if (sel) y = a;
  else     y = b;
end

A variable assigned in an always_comb cannot be written by another block.

always_ff

always_ff means "this block describes flip-flops". It needs an edge-sensitive event control and the tool errors if you write something that is not sequential:

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

Use non-blocking <= inside it. Using always_ff where you meant combinational logic is a compile error, which is the point.

always_latch

If you really want a latch (rare, and usually reserved for clock gating cells or specific library macros), say so:

SYSTEMVERILOG
always_latch
  if (en) q <= d;

Because latches must be explicit, an accidental latch in an always_comb is reported as a problem.

The classic latch bug, in C

In combinational logic, every path must assign every output. If one path forgets, the hardware has to remember the previous value, which means a latch. The first stand-in shows the difference: the buggy function keeps its old output when sel is not 0 or 1, exactly like an inferred latch, while good has a default.

C Stand-in: a missing branch behaves like a latch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With sel = 0 the buggy version still outputs 7, the previous value. A real latch also reacts to glitches and is a nightmare for timing analysis, which is why always_comb exists to flag it.

unique, unique0 and priority

A case or if-else chain in hardware can be built two ways. A priority structure checks conditions in order; a parallel (one-hot) structure checks all at once, which is faster but only correct when the conditions are mutually exclusive. SystemVerilog lets you state what you mean:

SYSTEMVERILOG
always_comb begin
  unique case (opcode)          // exactly one item must match
    2'b00: y = a + b;
    2'b01: y = a - b;
    2'b10: y = a & b;
    2'b11: y = a | b;
  endcase

  priority if (req[0]) grant = 4'b0001;
  else if (req[1])     grant = 4'b0010;
  else if (req[2])     grant = 4'b0100;
  else                 grant = 4'b0000;
end
  • unique: exactly one branch must match; simulators report a runtime warning if none or more than one matches, and synthesis may build parallel logic.
  • unique0: at most one branch matches (zero matches allowed).
  • priority: the first match wins and at least one branch must match.

They turn "I believe these cases are exclusive" from a comment into a checked assertion. The second stand-in shows what unique verifies and what priority does when conditions overlap:

C Stand-in: unique versus priority on overlapping conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

For 0110 both bits 1 and 2 are requested: a priority encoder grants bit 1, but a unique assertion would flag the overlap, which tells you the design is not behaving as assumed.

Functions and tasks

SystemVerilog functions can have void return type, default argument values and automatic storage. Make functions in RTL automatic so every call has its own variables (the Verilog default is static, shared between calls):

SYSTEMVERILOG
function automatic logic [3:0] popcount(input logic [7:0] v);
  logic [3:0] n = '0;
  for (int i = 0; i < 8; i++) n += v[i];
  return n;
endfunction

return ends a function early and for (int i ...) declares the loop variable locally. A function must take no simulation time; a task can wait on events and delays and is used in testbenches.

Packages: sharing definitions

Without packages, shared constants and types live in `include files, which are text pasted into every file and easy to break. A package is a real namespace:

SYSTEMVERILOG
package cpu_pkg;
  localparam int XLEN = 32;
  typedef logic [XLEN-1:0] word_t;
  typedef enum logic [1:0] {ADD, SUB, AND_OP, OR_OP} alu_op_t;

  function automatic word_t alu(alu_op_t op, word_t a, b);
    case (op)
      ADD:    return a + b;
      SUB:    return a - b;
      AND_OP: return a & b;
      default: return a | b;
    endcase
  endfunction
endpackage

Use it by import:

SYSTEMVERILOG
module core import cpu_pkg::*; (
  input  word_t a, b,
  input  alu_op_t op,
  output word_t y
);
  always_comb y = alu(op, a, b);
endmodule

Import the whole package with import cpu_pkg::*; or one name with import cpu_pkg::word_t;, or reference with the scope operator cpu_pkg::ADD. Packages must be compiled before the modules that use them, so order files accordingly in your build script.

Other small but useful features

  • '0, '1 and 'x fill a vector of any width.
  • ++, --, += and friends exist for procedural code.
  • localparam int N = 8; gives typed parameters.
  • Named end labels: endmodule : core help with long files.
  • timeunit 1ns; timeprecision 1ps; inside a module replaces the `timescale directive.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does always_comb do that always @* does not?

    always_comb evaluates at time 0 and lets tools check that the block is purely combinational, warning about latches.
  2. 2. Why use always_ff for registers?

    The block must be edge-sensitive, so intent and code agree. Mistakes become compile errors rather than silent mis-synthesis.
  3. 3. What does a unique case promise?

    unique asserts mutual exclusion and completeness, enabling parallel logic and runtime checks.
  4. 4. Why is a package better than `include for shared types?

    Packages avoid duplicate definitions and macro side effects and provide scoping (import and the :: operator).

Summary

  • Use always_comb, always_ff and always_latch so tools can check your intent and flag latches.
  • Give every output a default in combinational code.
  • unique, unique0 and priority document and check whether branches are exclusive.
  • Mark RTL functions automatic; share types, constants and functions with packages and import.

Next: Interfaces and Modports