Structures and Unions in SystemVerilog
SystemVerilog supports C-like structures without the optional tag before braces using struct keyword to group several related signals together.
Both variable and net types can be defined as structures. However, net types cannot be used for members of structures. By default, all structures are variable types. Structures that are defined without typedef are known as anonymous structures.
-
// Anonymous Structure
-
struct {
-
pkt_type_t type;
-
bit [15:0] addr;
-
bit [ 31:0] data;
-
byte crc;
-
} Packet_s;
-
// To assign a value to a struct member
-
Packet_s.type = ETHER_II;
-
-
// User defined struct
-
typedef struct {
-
pkt_type_t type;
-
bit [15:0] addr;
-
bit [ 31:0] data;
-
byte crc;
-
} Packet_s;
-
-
Packet_s pkt;
-
// To assign a value to a struct member
-
pkt.type = ETHER_II;
-
-
// Structures can be initialized using '{ and } operators
-
Packet_s pkt = '{ETHER_II, 16'h40, 32'hffff, 8'b30};
-
-
// Alternate way - explicit
-
Packet_s pkt = '{crc: 8'b30, addr:16'h40, data:32'hffff, type:ETHER_II};
-
-
// Default to zero using default keyword
-
Packet_s pkt = '{default:0};
structures are unpacked by default but packed structures are also possible using packed keyword after the struct - the members are stored as a bit vector with the first member being the MSB. Packed structures can compass only integral values (byte, int, shortint, logic or bit) - real types, enum types are not allowed. This allows mathematical/logical operations on packed structures. packed structures can be either signed or unsigned.
-
typedef struct packed signed {
-
logic [7:0] addr;
-
logic [31:0] data;
-
byte crc;
-
} Packet_s;
-
-
Packet_s pkt_a, pkt_b;
-
-
always @(posedge clock)
-
if (pkt_a < pkt_b) // Arithmetic signed operation
-
..
Structures can be passed through modules and also passed as arguments to tasks and functions if they are not anonymous. structs are also synthesizable.
Unions are supported in SV using union keyword and stores only a single value unlike structures. Unpacked unions can consist of any variable type like real, unpacked structs for abstract modeling and are not synthesizable.
-
typedef union {
-
logic [3:0] data;
-
logic data_valid;
-
} data_u;
-
-
data_u data_ctrl_u;
-
-
//tagged union
-
typedef union tagged {
-
logic [3:0] data;
-
logic data_valid;
-
} data_u;
-
-
data_u data_ctrl_u;
-
-
data_ctrl_u = tagged data_valid 1; // set data_valid in union data_ctrl_u to 1
-
-
data_valid_out = data_ctrl_u.data_valid;
unions can be tagged to include a member with implicit tag - this tag represents the name of the union member last written to. Values are stored in tagged unions using a tagged expression.
unions can also be packed - the members must have same number of bits making them synthesizable.
Sphere: Related Content