SystemVerilog is not only a verification language. Most new RTL is written in it, because it fixes real weaknesses of Verilog: one data type for every signal, blocks that state what hardware you mean, enums for state machines, structs and packages for shared types, and interfaces for busy port lists.
This tutorial goes through SystemVerilog topic by topic, and many topics are about classes, randomization and coverage, which never reach silicon. This page is the short route for designers: the articles that matter for synthesizable RTL, in a sensible order, with the sections to read where an article covers both design and verification.
5 min read | Reading guide
What You'll Learn
- Which SystemVerilog articles cover the synthesizable subset used for RTL design
- A reading order that builds from data types to blocks, connections and design patterns
- Which sections to read in articles that cover both design and verification
- Which parts of SystemVerilog a designer can safely skip
Before You Start
This guide assumes you can already write RTL in Verilog: modules, ports, always blocks and nonblocking assignments. SystemVerilog is a superset of Verilog, so all of that still works. What follows is what SystemVerilog adds on top for design.
If you want the why first, read SystemVerilog for Design vs. Verification in the tutorial introduction.
1. Data Types
The first thing to change in your RTL is how signals are declared. These articles replace the reg and wire confusion and let you give values names and structure.
- SystemVerilog logic: one 4-state type for almost every signal, driven from a procedural block or a continuous assignment.
- bit, byte and int: the 2-state types. Read Signed and Unsigned, then prefer
logicin RTL so X values from a missing reset stay visible in simulation. - Enumeration: named values with type checking, the basis for readable state machines and opcodes.
- typedef and alias: give a type a name once and reuse it across modules.
- Structure: group related fields. Focus on Packed Structures, which map onto a plain bit vector and are what RTL uses for buses and register fields.
- Union: two views of the same bits. Read the packed, untagged union sections; tagged unions are rarely used in synthesis.
- Packed Arrays and Unpacked Arrays: multi-dimensional vectors and memories. In SystemVerilog Arrays, only static arrays are for design; dynamic and associative arrays and queues are testbench types.
2. Procedural Blocks and Decisions
These are the constructs that describe logic. They let tools check that the code matches the hardware you meant.
- always_comb, always_latch and always_ff: the most important change for RTL. Each block states its intent, and tools warn when the code does not match it. You can skip Using These Blocks in Verification.
- unique and priority case: replace synthesis pragmas with checked keywords. Read Using unique and priority case in Digital Design.
- unique and priority if-else: the same idea for if-else chains. Read Using unique and priority if in Digital Design.
- Loops: only
forandforeachwith fixed bounds describe hardware. Read Loops in Design vs Verification;forever,whileandrepeatare for testbenches. - Functions and Tasks: automatic functions with ANSI-style arguments are useful for repeated combinational logic. Tasks that consume time and pass-by-reference arguments are testbench features.
3. Modules, Ports and Connections
Large designs spend many lines on port lists and wiring. These features cut that down and keep shared definitions in one place.
- Implicit Port Connections:
.nameand.*connect ports whose names match the signals. Read Using These Shortcuts in Design and Verification. - Package: share types, parameters and functions between modules. Read Design Notes: Packages and Synthesis.
- $unit Compilation Scope: why declarations outside any package cause trouble in multi-file builds, and why packages are the safer choice.
- Module Type Parameters: one module definition that works with different data types per instance.
- Interface, Interface Syntax and Connections and Modport: bundle a bus into one port and give each side its directions. Skip the clocking block sections, which are for testbenches.
- Interface Parameters and Interface Array: size an interface per instance, and connect replicated blocks or lanes.
Check your synthesis tool before using interfaces across the top level of a block. Most tools support them inside a design, but some flows still expect plain ports at block boundaries.
4. Design Patterns
- FSM Enum Modeling: the standard way to write state machines, with an enum state type and
unique case, and a lock-up bug to avoid. - Streaming Operators: pack and unpack structs and byte streams in one expression, useful in datapath and protocol logic.
5. Assertions in RTL
Designers write assertions too: a few checks inside the RTL catch misuse of a block at the exact cycle it happens, in simulation and in formal tools. Synthesis ignores them.
- SystemVerilog Assertions: what assertions are and the difference between immediate and concurrent ones.
- Immediate Assertions: read Immediate Assertion in Design.
- Concurrent Assertions and disable iff: multi-cycle checks such as "a request is acknowledged", switched off during reset.
To take assertions further, the Formal Verification tutorial shows how the same properties are proven for every input.
What Designers Can Skip
These parts of the tutorial are for testbenches and never appear in synthesizable RTL:
- Classes, inheritance, polymorphism and everything object-oriented
- Randomization and constraints
- Functional coverage: covergroups, coverpoints and bins
- Dynamic arrays, associative arrays, queues and strings
fork/join, mailboxes, semaphores and events- Program blocks, clocking blocks and virtual interfaces
- DPI and file I/O
They are worth learning later if you need to read or debug a testbench, but none of them is needed to write RTL.
Summary
In this guide, you learned:
- SystemVerilog is used for RTL design as well as verification, through a well-defined synthesizable subset
- Start with
logic, enums, typedefs and packed structs, then move toalways_comb/always_ffandunique/priority - Packages, implicit port connections and interfaces with modports cut down repeated declarations and wiring
- Enum-based FSMs and a few assertions in the RTL are standard practice
- Classes, randomization, coverage and dynamic data types are for testbenches and can be skipped for design
A typedef or a small utility function that several modules in the same file need doesn't always deserve a full package. SystemVerilog lets you declare things directly at the top of a file, outside any module or package, and every module compiled alongside them can use them with no import at all. That scope has a name: $unit.
7 min read | Intermediate Level
What You'll Learn
- What a compilation unit is, and why file grouping is tool-specific
- How to declare something in
$unitscope, and use it from any module compiled alongside it - Why
$unit::only disambiguates a name - it never grants forward visibility - The concrete ways
$unitscope is not just an unnamed package
What Is a Compilation Unit?
A compilation unit is one or more source files compiled together, and exactly how files get grouped into units is tool-specific. Every compliant tool has to support both extremes, though: all files on one compile command line can form a single unit, or each file can be treated as its own separate unit.
Anything declared outside every module, interface, program, package, and class - at the outermost level of a file - lands in that file's compilation-unit scope. A file pulled in with `include becomes part of the including file's own compilation unit, not a separate one.
Declaring Something in $unit Scope
A plain declaration at the top of a file, outside any module, is enough - no special keyword marks it as "$unit scope," it's simply wherever an item ends up when it isn't nested inside anything else:
// Outside any module - this typedef and function live in $unit scope
typedef enum logic [1:0] {OK, WARN, ERROR} status_t;
function automatic string status_str(status_t s);
return s.name();
endfunction
module tb;
initial begin
status_t a = OK;
status_t b = ERROR;
$display("a = %s", status_str(a));
$display("b = %s", status_str(b));
end
endmodule
Output
a = OK b = ERROR
tb uses status_t and status_str directly, with no import statement anywhere - they're simply visible, the same way a locally declared variable would be. Any other module compiled in the same unit as this file could use them exactly the same way.
Accessing It Explicitly with $unit::
Normally you never need to write $unit:: at all - a plain name already resolves to the compilation-unit-scope declaration when nothing closer shadows it. The prefix exists for the one case where something does shadow it:
int counter = 100; // $unit-scope declaration
module tb;
initial begin
int counter = 5; // this local declaration shadows the $unit-scope one
$display("counter = %0d", counter);
$display("$unit::counter = %0d", $unit::counter);
end
endmodule
Output
counter = 5 $unit::counter = 100
Name lookup always checks the nearest enclosing scope first, so the plain counter inside initial begin finds the local variable before it ever considers the one declared at the top of the file. $unit::counter skips straight past that local declaration and reaches the compilation-unit-scope one directly.
Quick Check
Q: If tb had no local counter variable at all, would a plain, unqualified counter inside its initial block still work?
Show Answer
Yes, and it would print 100. $unit:: is only needed to disambiguate a name that's shadowed by something closer. With nothing shadowing it, the plain name already resolves to the compilation-unit-scope declaration on its own.
$unit:: Doesn't Add Forward Visibility
An identifier still has to be declared earlier in the same compilation unit before it can be referenced - the $unit:: prefix only disambiguates a name that already resolves, it doesn't let you reach something declared later in the file:
int x;
module tb;
initial begin
x = 5 + limit; // illegal: 'limit' isn't declared yet at this point
x = 5 + $unit::limit; // also illegal: $unit:: grants no forward visibility
end
endmodule
int limit = 10; // declared after the module that tried to use it
Moving limit's declaration above module tb is the only fix - there's no prefix or keyword that lets a reference reach forward to a declaration that hasn't happened yet in the source text.
$unit Is Not Just an Unnamed Package
$unit scope can hold anything a package can - types, parameters, functions, tasks, variables - but it isn't a package, and the differences matter:
$unit scope | package | |
|---|---|---|
| Has a declared name | No - always accessed as $unit | Yes, its own name |
| Can be imported | No - there's no name to import | Yes, with import pkg::*; or a specific item |
| Visible outside its own compilation unit | No | Yes, from any unit that imports it |
That last row is the one most worth remembering. Whether two files end up sharing one compilation unit or each gets its own is a tool and build-script decision, not something the source code controls - so relying on one file's $unit declarations being visible in another file is only safe if you know for certain they're compiled together as a single unit.
When Is This Actually Useful?
$unit scope suits a handful of small, closely related declarations shared within one file or one tightly-compiled group of files - a couple of typedefs and a helper function used only by the testbench modules in that same compile. Anything meant to be shared deliberately and portably across a whole project's separately compiled files belongs in a real SystemVerilog Package instead, which can be explicitly imported no matter how the build happens to group files.
Common Beginner Mistakes
Mistake #1: Trying to import $unit
import $unit::*; is illegal, because $unit has no declared name for an import statement to reference.
There's also no need to import it - compilation-unit-scope items are already visible everywhere within their own unit, with no import step at all.
Mistake #2: Assuming $unit:: can reach a later declaration
As the forward-reference example shows, $unit:: only disambiguates a name that's already reachable - it adds no special ability to see past the normal declare-before-use rule.
The only fix for a forward-reference error is moving the declaration earlier in the file.
Mistake #3: Assuming $unit content is visible across every file in the project
Whether separate files share one compilation unit, or each file gets its own, is a tool-specific build decision - not something guaranteed by the language itself.
Relying on a $unit declaration from one file being visible in another is fragile unless the build is known to compile them as a single unit; a real package is the portable way to share something across files on purpose.
Practice Exercise
Challenge: Predict the Shadowed Value
Given int limit = 42; declared in $unit scope, and a module with initial begin int limit = 7; $display("%0d %0d", limit, $unit::limit); end, what does the $display print?
Hint
Work out what the plain, unqualified limit resolves to first, then what the explicitly qualified one resolves to - they don't have to be the same value.
Solution
It prints 7 42. The plain limit finds the local variable declared inside the initial block first, since the nested scope is always searched before the compilation-unit scope. $unit::limit skips past that local variable and reaches the compilation-unit-scope declaration directly.
Summary
In this tutorial, you learned:
- A compilation unit is one or more files compiled together; exactly how files are grouped into units is tool-specific
- Anything declared outside every module, interface, program, package, and class lands in that file's compilation-unit ($unit) scope, with no import needed to use it elsewhere in the same unit
$unit::nameexplicitly reaches the compilation-unit-scope declaration, which matters only when something closer shadows that name$unit::never grants forward visibility - the identifier still has to be declared earlier in the source$unithas no name of its own, so it can't be imported, and its declarations are never visible outside their own compilation unit - unlike a package, which can be imported from anywhere
Reassembling a struct's fields into a flat byte stream for a serial link, or splitting a received byte stream back into a struct's fields, normally means writing the shifting and masking by hand, field by field. SystemVerilog's streaming operators, {>>{...}} and {<<{...}}, do this packing and unpacking in a single expression instead.
8 min read | Intermediate Level
What You'll Learn
- How
{>>{...}}and{<<{...}}pack a group of values into a single bit stream - What the optional slice size actually reorders, and why
>>ignores it entirely - How the same operators run in reverse to unpack a stream back into variables
- A realistic design and verification use: converting a struct to and from a byte queue
Packing Values Into a Stream
A streaming concatenation looks like an ordinary concatenation, but with a stream operator and an optional slice size right after the opening brace:
module tb;
initial begin
int j = { "A", "B", "C", "D" }; // packs to 32'h41424344
bit [31:0] s1 = { >> { j } }; // same bit order, unchanged
bit [31:0] s2 = { << byte { j } }; // byte order reversed
bit [31:0] s3 = { << 16 { j } }; // 16-bit halves swapped
$display("j = 0x%0h", j);
$display("s1 = 0x%0h", s1);
$display("s2 = 0x%0h", s2);
$display("s3 = 0x%0h", s3);
end
endmodule
Output
j = 0x41424344 s1 = 0x41424344 s2 = 0x44434241 s3 = 0x43444142
The stream operator, >> or <<, controls the direction blocks are streamed in. >> streams left to right, which is the same order the bits already have - so it simply ignores whatever slice size is given.
<< streams right to left instead. It slices the value into blocks of the given size, starting from the right-most bit, and then reverses the order of those blocks - without reversing the bits inside each block.
That is exactly what s2 and s3 show. { << byte {j} } slices j into four 8-bit (one-byte) blocks and reverses their order, which is the standard way to flip between big-endian and little-endian byte order. { << 16 {j} } instead slices it into two 16-bit blocks and swaps those.
If no slice size is given at all, it defaults to 1 bit - so a bare {<<{expr}} reverses the individual bits of expr, not whole bytes or words.
Unpacking a Stream Back Into Variables
Putting a streaming concatenation on the left-hand side of an assignment runs the same operation in reverse - it unpacks a stream into one or more variables:
module tb;
initial begin
bit [31:0] stream = 32'h41424344;
byte a, b, c, d;
{ >> { a, b, c, d } } = stream;
$display("a = 0x%0h b = 0x%0h c = 0x%0h d = 0x%0h", a, b, c, d);
end
endmodule
Output
a = 0x41 b = 0x42 c = 0x43 d = 0x44
The source on the right supplies the bits, consumed from its most significant end first, and the variables on the left are filled in the order they are listed. If the source has more bits than the targets need, the extra low-order bits are simply left unread. If it has fewer bits than the targets need, that is an error - there is nothing left to fill the remaining variable with.
Packing a Struct Into a Byte Queue
Streaming operators work on more than just integers. A struct, array, or queue can be streamed too, which is what makes them useful for modeling a packet on a byte-wide channel:
module tb;
typedef struct packed {
byte addr;
byte code;
byte payload;
} pkt_t;
initial begin
byte channel [$]; // the byte-wide channel, modeled as a queue
byte pkt_bytes [$];
pkt_t p, rx;
byte rx_bytes [$];
// Send: pack the struct's 3 bytes into a queue, then append that to the channel
p = '{addr: 8'hA0, code: 8'h3C, payload: 8'hFF};
pkt_bytes = { >> byte { p } };
channel = { channel, pkt_bytes };
$display("p = 0x%0h", p);
$display("channel = 0x%0h 0x%0h 0x%0h", channel[0], channel[1], channel[2]);
// Receive: pop 3 bytes back off the channel and unpack them into a struct
rx_bytes = { channel[0], channel[1], channel[2] };
{ >> byte { rx } } = rx_bytes;
$display("rx.addr = 0x%0h", rx.addr);
$display("rx.code = 0x%0h", rx.code);
$display("rx.payload = 0x%0h", rx.payload);
end
endmodule
Output
p = 0xa03cff channel = 0xa0 0x3c 0xff rx.addr = 0xa0 rx.code = 0x3c rx.payload = 0xff
The sender's struct fields are streamed out byte by byte, in declaration order, without the sender ever writing out the individual shifts and masks for addr, code, and payload separately. The receiver does the same operation in reverse, reconstructing the struct's fields directly from the raw bytes pulled off the channel.
The same conversion is equally useful on the design side, for a serializer or deserializer that packs a wide internal bus into one byte at a time for a narrow external interface, and on the verification side, for a driver or monitor that converts between a readable transaction struct and the raw bytes actually seen on a pin-level bus.
Common Beginner Mistakes
Mistake #1: Assuming >> reorders data the same way << does
{ >> N {expr} } and { >> {expr} } produce the exact same result for any slice size N, because left-to-right streaming never reorders anything.
Only << actually uses the slice size to reorder blocks. Reaching for >> out of habit and expecting a reordering effect produces silently unchanged data instead of an error.
Mistake #2: Forgetting the default slice size is 1 bit, not 1 byte
{ << {expr} } with no slice size reverses individual bits, which is rarely what's intended when the goal is byte or word reordering.
Write { << byte {expr} } or an explicit bit count like { << 8 {expr} } whenever the reordering should happen at byte or word granularity instead of bit granularity.
Mistake #3: Unpacking into a target with too few bits available
If the right-hand stream supplies fewer bits than the left-hand variables need, unpacking is an error, not a zero-fill.
Zero-filling only happens the other way around, when a streaming concatenation is packed into a fixed-size target that is wider than the stream: the stream is left-aligned and the remaining low-order bits are zero-filled.
Quick Check
Q: For int j = 32'h11_22_33_44;, what does { << 16 {j} } produce?
Show Answer
32'h3344_1122. j splits into two 16-bit blocks, 'h1122 and 'h3344, and << reverses their order - giving 'h3344 followed by 'h1122 - without touching the bit order inside either block.
Practice Exercise
Challenge: Byte-Swap a 32-bit Value
Write a one-line expression that reverses the byte order of a 32-bit variable data, so that 32'h12_34_56_78 becomes 32'h78_56_34_12.
Hint
This is exactly the big-endian/little-endian conversion shown earlier - it just needs the right slice size for a byte.
Solution
module tb;
initial begin
bit [31:0] data = 32'h12345678;
bit [31:0] swapped = { << byte { data } };
$display("data = 0x%0h", data);
$display("swapped = 0x%0h", swapped);
end
endmodule
Output
data = 0x12345678 swapped = 0x78563412
Slicing into byte-sized blocks and streaming them right to left reverses the four bytes while leaving the bits inside each byte untouched - exactly a byte-swap.
Summary
In this tutorial, you learned:
{>>{...}}and{<<{...}}pack their contents into a single bit stream, with an optional slice size controlling how it gets reordered>>always streams left to right and ignores the slice size; only<<reorders blocks, right to left- The default slice size is 1 bit, so byte or word reordering needs an explicit slice size like
byteor16 - The same operators on the left-hand side of an assignment unpack a stream back into one or more variables
- Structs, arrays, and queues can all be streamed, which makes these operators a natural fit for converting a struct-typed packet to and from a raw byte channel
A value parameter lets one module definition generate different bit widths or depths for different instances.
SystemVerilog extends the same idea one step further: a parameter type lets one module, interface, or program definition generate different data types for different instances, instead of rewriting the whole block for every data type you need to support.
7 min read | Intermediate Level
What You'll Learn
- How to declare a
parameter typeon a module, and use it to type a port or an internal signal - How a value parameter can itself depend on a type parameter declared earlier in the same parameter list
- How to override a type parameter at instantiation, and what happens if that override breaks a dependent value parameter
- That the same mechanism works on interfaces, not just modules
Declaring a Type Parameter
A type parameter is declared with parameter type instead of a plain parameter. Its default is a data type rather than a value:
module generic_reg #(
parameter type T = logic [7:0],
parameter T RESET_VAL = '0
) (
input logic clk,
input logic rst_n,
input logic en,
input T d,
output T q
);
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) q <= RESET_VAL;
else if (en) q <= d;
endmodule
The ports d and q are both declared with type T. By default, that makes them an 8-bit logic vector, since that is T's default. RESET_VAL is an ordinary value parameter, but its own type is T instead of a fixed type like int. That is legal specifically because T was already declared earlier in the same parameter list. A later parameter can depend on the type of an earlier one.
Overriding a Type Parameter at Instantiation
A type parameter is overridden the same way a value parameter is, using #(.name(...)) at the instance - except the thing inside the parentheses is a type instead of a value:
module top;
logic clk, rst_n, en;
// Uses the default: T = logic [7:0], RESET_VAL = '0
generic_reg reg8 (.clk, .rst_n, .en, .d(8'h00), .q());
// Overrides T to a 16-bit vector; RESET_VAL now defaults to a 16-bit '0 automatically
generic_reg #(.T(logic [15:0])) reg16 (.clk, .rst_n, .en, .d(16'hBEEF), .q());
endmodule
reg16 doesn't need to override RESET_VAL at all. Because RESET_VAL's type tracks T, widening T to 16 bits automatically widens RESET_VAL's default to a 16-bit '0 as well. Any data type can be supplied this way, including a user-defined typedefed struct or enum - not just a built-in vector type.
Quick Check
Q: If generic_reg were instantiated as generic_reg #(.T(logic [15:0]), .RESET_VAL(16'hFFFF)) reg16 (...), would that compile?
Show Answer
Yes. Overriding T and explicitly overriding RESET_VAL at the same time is legal - it just means RESET_VAL no longer uses the type-dependent default, since it was given an explicit 16-bit value of its own instead.
Type Parameters Also Work on Interfaces
The same declaration works on an interface, letting one interface definition carry whatever payload type the design around it needs:
interface generic_if #(parameter type T = logic [31:0]);
T data;
logic valid;
logic ready;
endinterface
Connecting this to an 8-bit design and a 64-bit design just means instantiating generic_if twice, once with T left at its default and once overridden to logic [63:0] - no second copy of the interface source needs to exist.
The value-parameter side of interface parameterization - sizing a bus width that stays a plain vector - is covered in full in SystemVerilog Interface Parameters. This same parameter type mechanism is also what parameterized classes use, covered in SystemVerilog Parameterized Classes.
Restrictions Worth Knowing
- A type parameter can only ever be set to a data type, never a plain value, and the reverse is also true.
- Mixing up which kind of parameter a given name is produces a compile error.
- A type parameter cannot be overridden with a
defparamstatement. It can only be overridden at the point of instantiation. - A type parameter's override expression cannot be a hierarchical name. A plain type name, a
typedefed name, or a package-scoped type reference are all legal; a path through the design hierarchy is not.
Common Beginner Mistakes
Mistake #1: Overriding a type parameter without checking what depends on it
In the generic_reg example, RESET_VAL's default depends on T. Overriding T to an incompatible type - a class handle, for instance, where RESET_VAL's default of '0 no longer makes sense - causes elaboration to fail on the dependent parameter, not on the type override itself. The error points at the symptom, not the cause, which makes this easy to misdiagnose the first time it happens.
Mistake #2: Expecting a type parameter to flow into the connected module automatically
Just like a value parameter, overriding a type parameter on one instance does not change any other instance, and does not change a separate module that happens to be connected to this one. Each parameterized module, interface, or program is still an independent entity - connecting them doesn't share parameters between them unless each side is explicitly given a matching override.
Practice Exercise
Challenge: A Generic Comparator
Write a module generic_eq with a type parameter T defaulting to logic [7:0], two input ports a and b of type T, and one output port match that is high whenever a == b. Then instantiate it once with the default type, and once overridden to compare two 32-bit values.
Hint
match doesn't need to be type T itself - it's always a single bit, regardless of how wide a and b are.
Solution
module generic_eq #(
parameter type T = logic [7:0]
) (
input T a,
input T b,
output logic match
);
assign match = (a == b);
endmodule
module top;
logic [7:0] a8, b8;
logic [31:0] a32, b32;
logic m8, m32;
generic_eq cmp8 (.a(a8), .b(b8), .match(m8));
generic_eq #(.T(logic [31:0])) cmp32 (.a(a32), .b(b32), .match(m32));
endmodule
match stays a plain 1-bit logic in both instances. Only a and b change width, since only they are declared with type T.
Summary
In this tutorial, you learned:
parameter typedeclares a parameter whose default and override are both data types, usable directly as the type of a port or an internal signal- A value parameter declared later in the same list can depend on a type parameter declared earlier, and its default is recomputed if that type parameter is overridden
- Type parameters are overridden the same way value parameters are, with
#(.name(...))at the instance - Type parameters work the same way on modules, interfaces, and programs
- A type parameter can't be set with
defparam, and its override can't be a hierarchical name
A finite state machine built from parameter or localparam constants compiles and simulates fine, but it gives up two things SystemVerilog can offer for free: strong type checking on the state variable, and a built-in safety net for missed states.
Enumerated types and the unique case statement together close both gaps, which is why they are the standard way to model FSMs in SystemVerilog RTL.
8 min read | Intermediate Level
What You'll Learn
- How to declare FSM states as an enumerated type with an explicit 4-state base type
- Why
unique caseis the right choice for state decode logic, and what it checks for you - Why FSM decode logic rarely needs an explicit enum cast, and where to look if it does
- A classic FSM lock-up bug caused by enum default values, and the two ways to fix it
Declaring States as an Enumerated Type
A state register is really just a variable restricted to a small, named set of legal values - exactly what an enumerated type is for. Declaring it with typedef enum, an explicit base type, and explicit bit values documents the encoding directly in the state declaration instead of in a separate block of parameter lines:
typedef enum logic [1:0] {
IDLE = 2'b00,
READ = 2'b01,
BUSY = 2'b10,
DONE = 2'b11
} state_t;
state_t state, next_state;
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) state <= IDLE;
else state <= next_state;
Two choices in that declaration matter more than they look. First, the base type is logic, a 4-state type, instead of the enum default of int. Second, every label has an explicit value instead of letting SystemVerilog number them 0, 1, 2, 3 automatically.
Both choices keep the RTL model's encoding visible and predictable instead of leaving it to whatever the tool happens to pick. That matters for comparing a pre-synthesis simulation against the gate-level netlist, and for the reset bug described later in this article.
Decoding State with unique case
Next-state and output logic read naturally as a case statement over the state variable. Adding the unique modifier turns that case statement into a semantic check, not just a style choice:
always_comb begin
next_state = state; // default: hold current state
unique case (state)
IDLE: if (start) next_state = READ;
READ: next_state = BUSY;
BUSY: if (mem_ready) next_state = DONE;
DONE: next_state = IDLE;
endcase
end
always_comb begin
{mem_req, done} = '0;
unique case (state)
READ: mem_req = 1'b1;
DONE: done = 1'b1;
default: ; // IDLE and BUSY drive nothing extra
endcase
end
unique case gives you three things at once.
First, it tells synthesis the branches can be decoded in parallel, with no priority chain - the same hint as a parallel_case pragma.
Second, it flags a run-time warning if two branches ever match the same value at once.
Third, and most useful for an enumerated state variable, it flags a run-time warning if the case expression takes a value that no branch covers. That is exactly the "full coverage" check a full_case pragma gives synthesis, except unique case enforces it in simulation too, instead of only at synthesis time.
Because state is restricted to the four labels in state_t, listing those four branches is already exhaustive. There is no need for a default branch that assigns an X "just in case," the way a plain reg-based state register would need one.
The enumerated type and unique case already guarantee that any value state can legally hold is covered. The one exception is simulation time zero: state is a 4-state variable, so it is x until reset first assigns it, and each always_comb block runs once at time zero. Since x matches none of the labels, unique case can issue a one-time violation report before reset. That report is expected and harmless; it can be silenced during reset with the assertion control system tasks, or avoided by using unique0 case, which does not report when nothing matches.
If an FSM uses one-hot encoding, some codebases write the case expression as the constant 1'b1 and each case item as a bit-select of the state register, such as state[READ_BIT]. This "reversed" case style can synthesize to more efficient decode logic for one-hot state machines, though the ordinary style above works correctly for any encoding.
Casting Into the State Variable
next_state can only ever be assigned a label from state_t, since enumerated types are strongly typed. The unique case block above already only assigns full labels on every branch, so this never comes up for ordinary FSM decode logic written that way.
It only matters if a next state is ever computed from an expression instead of chosen in a case branch - for example, stepping to the next encoding with next_state = state_t'(state + 1); instead of a case item.
That needs an explicit cast, because the result of arithmetic on a state variable is an integer expression, which is not automatically assignment-compatible with the enum type. The built-in .next method needs no cast, since it already returns a value of the enum type.
See SystemVerilog Enumeration for the full casting rules and the built-in first()/last()/next()/prev()/num()/name() methods.
Common Beginner Mistakes
Mistake #1: A default enum base type hides an FSM lock-up at time zero
An enum declared without an explicit base type defaults to int, a 2-state type that starts simulation at 0 - the same value as the first label in the list.
If the decode logic is written as always @(state) rather than always_comb, that block never fires before the first real transition, because state hasn't changed yet from its initial value. The design can sit locked on the first state indefinitely, even after reset, since reset simply reassigns the same value the variable already holds.
Declaring the enum with an explicit 4-state base type (logic, as in the example above) fixes this: simulation now starts at X instead of 0, so the first legal assignment from reset is a genuine transition. Switching the decode block to always_comb fixes it independently, since always_comb always executes once at time zero regardless of whether anything in its sensitivity list has changed yet.
Mistake #2: Assigning a bit-select of a one-hot state variable directly
Clearing a one-hot next_state to all zeros and then setting a single bit, a common style with plain reg state registers, does not work with an enumerated type - a bare '0 is not a label in the enumeration.
Setting one bit of an enum variable can also leave it holding a combination that was never declared.
Assign a full label from the type's list on every branch instead of touching individual bits, and let the unique case default (next_state = state; in the example above) cover the "no change" case.
Quick Check
Q: Why doesn't the FSM in this article need a default branch inside its unique case statements?
Show Answer
Because state is of type state_t, it can only ever legally hold one of the four declared labels once reset has assigned it. Before that, a 4-state state is x.
Listing all four case items already covers every value the variable can hold, so there is no remaining value for a default branch to catch. unique case will flag a run-time warning if that assumption is ever violated.
Practice Exercise
Challenge: Add an Error State
Extend the state_t enumeration with a fifth label, ERROR, that the FSM enters from BUSY if a signal mem_err is asserted, and that only returns to IDLE after an external clear_err signal. Update the next-state unique case block accordingly.
Hint
Add the new label to the typedef enum list with its own explicit 2-bit value, then add one more case item for BUSY that checks mem_err before the existing mem_ready check, plus a new case item for ERROR itself.
Solution
typedef enum logic [2:0] {
IDLE = 3'b000,
READ = 3'b001,
BUSY = 3'b010,
DONE = 3'b011,
ERROR = 3'b100
} state_t;
always_comb begin
next_state = state;
unique case (state)
IDLE: if (start) next_state = READ;
READ: next_state = BUSY;
BUSY: if (mem_err) next_state = ERROR;
else if (mem_ready) next_state = DONE;
DONE: next_state = IDLE;
ERROR: if (clear_err) next_state = IDLE;
endcase
end
Widening the base type to 3 bits was necessary because the original 2-bit encoding had no room left for a fifth label.
Every branch still assigns a full label, and the unique case still has no need for a default, since the five listed items remain exhaustive for a 5-value enumeration.
Summary
In this tutorial, you learned:
- Declare FSM states as a
typedef enumwith an explicit 4-state base type and explicit label values, rather than relying on the defaults unique casegives parallel-decode synthesis behavior plus run-time warnings for overlapping or uncovered case values- FSM decode logic only assigns full labels, so it rarely needs a cast - that only comes up when computing a next state from an expression rather than a case branch
- A 2-state (or default
int) enum combined with an edge-sensitive decode block can lock an FSM up at time zero - fix it with a 4-state base type,always_comb, or both
Quiz
No quiz questions available for this article.