SystemVerilog
Testbench Constructs
Alex Wakefield
Synopsys, Inc.
October 21, 2004
Agenda
¾ Introduction
• SystemVerilog Language Features
Data Types
Classes
Constraints
Threads
Functional Coverage
• Conclusion
© 2004 Synopsys, Inc. (2)
SystemVerilog Charter
• Charter: Extend Verilog IEEE 2001 to higher
abstraction levels for Architectural and Algorithmic
Design , and Advanced Verification.
Advanced
Transaction-Level V
As er verification capability
be g
Full Testbench
st ilo
h
se ilog for semiformal and
nc
Te Ver
Language with rt
io formal methods.
Coverage n
IEEE The Assertion
Language Standard
Verilog For Verilog
2001 PI
Ar
A e
Ve itect
Design c
ch
&
ril ur
Abstraction: I rf a
og al
Interface
P
D nte
Direct C interface,
I Assertion API and
semantics, abstract
Coverage API
data types,
abstract operators
and expressions
© 2004 Synopsys, Inc. (3)
SystemVerilog Benefits (Testbench)
• Powerful Testbench features
Classes / Object Oriented Programming
Constrained Random Testing
Functional Coverage
Assertions
Enables Advanced Verification Methodology
• Result is an increase in verification productivity
© 2004 Synopsys, Inc. (4)
SystemVerilog: Verilog 1995
Event handling Basic datatypes (bit, int, reg, wire…)
4 state logic Basic programming (for, if, while,..)
Verilog-95:
Single language
Hardware concurrency Gate level modelling for design &
design entity modularization and timing
testbench
Switch level modeling and timing ASIC timing
© 2004 Synopsys, Inc. (5)
SystemVerilog: VHDL
Operator VHDL adds
Packages Overloading
higher level
Architecture Simple assertions
Dynamic pointers data types and
memory
configuration
User-defined types allocation management
records/ functionality
Dynamic enums structs
multi-D arrays
hardware
generation Automatic variables Signed numbers Strings
Event handling Basic datatypes (bit, int, reg, wire…)
4 state logic Basic programming (for, if, while,..)
Hardware concurrency Gate level modelling
design entity modularization and timing
Switch level modeling and timing ASIC timing
© 2004 Synopsys, Inc. (6)
SystemVerilog: C
Operator
Packages Overloading
Associative
Dynamic & Sparse arrays
Architecture Simple assertions pointers
memory
configuration allocation
User-defined types Void type Further
records/ programming
Dynamic enums structs Unions
multi-D arrays (do while,
hardware
break, continue,
generation Automatic variables Signed numbers Strings
++, --, +=. etc)
Event handling Basic datatypes (bit, int, reg, wire…)
4 state logic Basic programming (for, if, while,..) prog C has
r e
but ammin xtra
lack g
Hardware concurrency Gate level modelling
s all featur
design entity modularization and timing con hardw es
cep are
ts
Switch level modeling and timing ASIC timing
© 2004 Synopsys, Inc. (7)
SystemVerilog: Verilog-2001
Verilog-2001 adds a lot of
VHDL functionality but still
lacks advanced data
structures
Operator
Packages Overloading
Associative
Dynamic & Sparse arrays
Architecture Simple assertions pointers
memory
configuration allocation
User-defined types Void type Further
records/ programming
Dynamic enums structs Unions
multi-D arrays (do while,
hardware
break, continue,
generation Automatic variables Signed numbers Strings
++, --, +=. etc)
Event handling Basic datatypes (bit, int, reg, wire…)
4 state logic Basic programming (for, if, while,..)
Hardware concurrency Gate level modelling
design entity modularization and timing
Switch level modeling and timing ASIC timing
© 2004 Synopsys, Inc. (8)
SystemVerilog: Enhancements
Constrained Program Clocking Enhanced Scheduling for Cycle Sequence
Random Data Block Block Testbench and Assertions Delays Events
Generation
Sequential Semaphores Persistent Functional
Queues
Classes, methods Regular events Coverage
Mailboxes
& inheritance Expressions Process Virtual
Interface Temporal Operator Control Interfaces
Specification Properties Packages Overloading
Associative
Dynamic safe pointers & Sparse arrays
Architecture Simple assertions
memory
configuration allocation
User-defined types Void type Further
records/ programming
Dynamic enums structs Unions
multi-D arrays (do while,
hardware g
rilo Automatic variables
generation Signed numbers Strings
break, continue,
eV ide s ++, --, +=. etc)
m
sEvent ov ed dBasic datatypes (bit, int, reg, wire…)
te rhandling
Sy 1a p anc an
34. state
d vlogicion Basic programming (for, if, while,..)
a cat ing Packed structs
e l
ifi concurrency and unions
e r
Hardware
o d res Gate level modelling
v
design m u
entity tmodularization and timing Coverage & C interface
f ea Assertion
API
Switch level modeling and timing ASIC timing
© 2004 Synopsys, Inc. (9)
Today’s Focus SystemVerilog: Unified Language
Constrained Program Clocking Enhanced Scheduling for Cycle Sequence
Random Data Block Block Testbench and Assertions Delays Events
Generation
Sequential Semaphores Persistent Functional
Queues
Classes, methods Regular events Coverage
Mailboxes
& inheritance Expressions Process Virtual
Interface Temporal Operator Control Interfaces
Specification Properties Packages Overloading
Associative
Dynamic safe pointers & Sparse arrays
Architecture Simple assertions
memory
configuration allocation
User-defined types Void type Further
records/ programming
enums structs Unions
VHDL
Dynamic multi-D arrays (do while,
hardware
break, continue,
generation Automatic variables Signed numbers Strings
++, --, +=. etc)
Event handling Basic datatypes (bit, int, reg, wire…)
4 state logic Basic programming (for, if, while,..)
Packed structs
and unions
Hardware concurrency Gate level modelling
design entity modularization and timing Coverage & C interface
Assertion
API
Switch level modeling and timing ASIC timing
© 2004 Synopsys, Inc. (10)
Agenda
¾ Introduction
• SystemVerilog Language Features
Data Types
Classes
Constraints
Threads
Functional Coverage
• Conclusion
© 2004 Synopsys, Inc. (11)
Program Block
• Purpose: Identifies verification code
• A program differs from a module
Only initial blocks allowed
Special semantics
• Executes in Reactive region
design → clocking/assertions → program
program name (<port_list>);
<declarations>;// type, func, class, clocking…
<continuous_assign>
initial <statement_block>
endprogram
© 2004 Synopsys, Inc. (12)
Basic SystemVerilog Data Types
reg r; // 4-state Verilog-2001 single-bit datatype
integer i; // 4-state Verilog-2001 >= 32-bit datatype
bit b; // single bit 0 or 1
logic w; // 4-valued logic, x 0 1 or z as in Verilog
byte b8; // 8 bit signed integer
int i; // 2-state, 32-bit signed integer
Explicit 2-state Variables Allow Compiler
Optimizations to Improve Performance
The unresolved type “logic” in SystemVerilog
is equivalent to “std_ulogic” in VHDL
© 2004 Synopsys, Inc. (13)
Structures
struct { bit [7:0] opcode;
bit [23:0] addr;
} IR; // anonymous structure
IR is a struct variable
typedef struct { bit [7:0] opcode;
bit [23:0] addr;
} instruction; // named structure type
instruction is a user-
instruction IR; // define variable defined struct type
IR.opcode = 1; // set field in IR
Structure definitions are just like in C but
without the optional structure tag before the ‘{‘
Equivalent to VHDL records
© 2004 Synopsys, Inc. (14)
Packed Structures and Unions
typedef struct packed { typedef union packed {
logic [15:0] source_port; tcp_t tcp_h;
logic [15:0] dest_port; udp_t udp_h; All
logic [31:0] sequence; bit [63:0] bits; members
} tcp_t; bit [7:0][7:0] bytes; must
typedef struct packed { } ip_t; be the
logic [15:0] source_port; same size
logic [15:0] dest_port;
logic [15:0] length;
logic [15:0] checksum ip_t ip_h;
} udp_t;
ip_h.udp_h.length = 5;
ip_h.bits[31:16] = 5;
tcp_t source_port dest_port sequence ip_h.bytes[3:2] = 5;
udp_t source_port dest_port length checksum
Eq
ui
va
Create multiple layouts for accessing data len
t
VHDL records not explicitly packed
© 2004 Synopsys, Inc. (15)
Type Conversion
Unpacked Structure
typedef struct {
logic PARITY;
logic[3:0] ADDR; User-defined type:
logic[3:0] DEST; packed bit vector
} pkt_t;
typedef bit[8:0] vec_t;
pkt_t mypkt;
vec_t myvec;
Cast mypkt as type vec_t
myvec = vec_t’(mypkt);
mypkt = pkt_t’(myvec);
Cast myvec as type pkt_t
User-defined types and explicit casting
improve readability and modularity
Similar to Qualified Expressions
or conversion functions in VHDL
© 2004 Synopsys, Inc. (16)
Data Organization - Enum
• Explicitly Typed
Allows compile time error checking
typedef enum { init, decode, …} fsmstate;
fsmstate pstate, nstate;
case (pstate)
idle: if (sync)
nstate = init;
init: if (rdy)
nstate = decode;
…
endcase
© 2004 Synopsys, Inc. (17)
Queues
• Variable-sized Array: data_type name [$]
Uses array syntax and operators
• Synthesizable if maximum size is known
q[$:25] // maximum size is 25
int q[$] = { 2, 4, 8 }; int e, pos, p[$];
e = q[0]; // read the first (leftmost) item
e = q[$]; // read the last (rightmost) item
q = { q, 6 }; // append: insert ‘6’ at the end
q = { e, q }; // insert ‘e’ at the beginning
q = q[1:$-1]; // delete the first and last items
© 2004 Synopsys, Inc. (18)
Associative Arrays
• Sparse Storage
Elements Not Allocated Until Used
Index Can Be of Any Packed Type, String or Class
<type> <identifier> [<index_type>];
Declaration
Declaration <type> <identifier> [*]; // “arbitrary” type
num(), delete([index]), exists(index);
Methods
Methods first/last/prev/next(ref index);
Example
Example Ideal for Dealing with Sparse Data
struct packed {int a; logic[7:0] b} mystruct;
int myArr [mystruct]; //Assoc array indexed by mystruct
© 2004 Synopsys, Inc. (19)
Packing and Unpacking
• Reshape any aggregate bit-level object
• Packed ⇔ Unpacked, Array ⇔ Structure
typedef struct { A
bit [7:0] f1; f1
bit [7:0] f2;
f2
bit [7:0] f3[0:5];
} Unpacked_s; f30 f31 f32 f33 f34 f35
typedef struct packed {
bit [15:0][0:2] f1;
bit [15:0] f2; B
} Packed_s; f10 f11 f12 f2
Unpacked_s A;
Packed_s B;
…
A = Unpacked_s’(B); Objects
Objectsmust
musthave
have
B = Packed_s’(A); identical
identicalbit
bitsize
size
© 2004 Synopsys, Inc. (20)
Agenda
¾ Introduction
• SystemVerilog Language Features
Data Types
Classes
Constraints
Threads
Functional Coverage
• Conclusion
© 2004 Synopsys, Inc. (21)
Object-Oriented Programming
•Classes pkt_t MyPkt = new;
Encapsulate data and methods cmd
Storage allocated via “new” status get_status
method (User may define custom header
“new” method) set_cmd
cmd = a;
Automatic garbage collection
•Inheritance
err_t extends pkt_t;
Allows hierarchical definition of err_t myPkt = new;
objects. Subclass inherits from cmd
base class status get_status
Can redefine properties, methods header
show_err
and constraints set_cmd
err cmd = a+1;
© 2004 Synopsys, Inc. (22)
Class Definition
Definition syntax
class name;
<data_declarations>; class Packet;
<task/func_decls>; bit[3:0] cmd;
endclass int status;
myStruct header;
extern keyword function int get_status();
allows for out-of-body return(status);
method declaration endfunction
extern task set_cmd(input bit[3:0] a);
endclass
“::” operator links
method declaration to
task Packet::set_cmd(input bit[3:0] a);
Class definition
cmd = a;
endtask
© 2004 Synopsys, Inc. (23)
Class Instantiation
Declare myPkt handle;
No storage allocated yet
Packet myPkt;
myPkt = new;
Call to “new” method
allocates storage for object
myPkt
cmd
status
header
• User may override default “new” method
Assign values, call functions, etc.
User-defined new method may take arguments
• Garbage Collection happens automatically
© 2004 Synopsys, Inc. (24)
Class Inheritance & Extension
•Keyword extends
Denotes Hierarchy of class ErrPkt extends Packet;
bit[3:0] err;
Definitions
function bit[3:0] show_err();
Subclass inherits return(err);
properties, endfunction
constraints and task set_cmd(input bit[3:0] a);
methods from parent cmd = a+1;
Subclass can endtask // overrides Packet::set_cmd
redefine methods endclass
explicitly
Packet: ErrPkt:
cmd cmd
status get_status status get_status
show_err
header header
set_cmd set_cmd
cmd = a; err cmd = a+1;
Allows Customization Without Breaking or Rewriting
Known-Good Functionality in the Base Class
© 2004 Synopsys, Inc. (25)
Class Hierarchy : UML
• Class design can be documented using
Universal Modeling Language diagrams
cell Base
BaseClass
Class
Inheritance
Inheritance
Eth_cell Atm_cell Derived
DerivedClass
Class
© 2004 Synopsys, Inc. (26)
Agenda
¾ Introduction
• SystemVerilog Language Features
Data Types
Classes
Constraints
Threads
Functional Coverage
• Conclusion
© 2004 Synopsys, Inc. (27)
Constraints vs Distribution
Functions
• Constraints allow you to define the
distribution of random variables
No
X correlations A
Y
B
Z
C
© 2004 Synopsys, Inc. (28)
Constrained Random Data
• Constraints
Declarative constraints built into class system
• Built-in randomize method calls constraint solver
• randomize with construct adds constraints in-line
class packet {
rand bit [7:0] src;
rand bit [7:0] dst;
constraint valid { src[0] == 0; }
constraint legal { dst < 10; }
}
packet pkt = new();
void = pkt.randomize() with { dst > 2 };
© 2004 Synopsys, Inc. (29)
Constraints vs Distribution
Functions
Y
•Constraints describe Corner
solution space and can Case
constrain multiple
random variables X
simultaneously
Z
class packet {
rand bit [7:0] src;
rand bit [7:0] dst;
constraint valid { src[0] == 0; }
constraint legal { dst < 10; }
constraint corner { src == dst + 1; }
}
© 2004 Synopsys, Inc. (30)
Layered Constraints
• Constraints Inherited via Class Extension
Just like data and methods, constraints can be inherited
or overridden
All constraints are solved at one time (child and parent)
class packet_src0 extends packet {
constraint src0 { src == 0 };
}
Constraints can be checked in line
Passing “null” argument to randomize
status = class_obj.randomize(null); checks that the current state variable
values satisfy the constraints
0 = valid, 1 = invalid
© 2004 Synopsys, Inc. (31)
Iterative Constraints
• The foreach construct
Specifies iteration over elements of an array
Values of all elements of array can be solved
for simultaneously
Associative
class Instruction; Array
rand Opcode op[];
rand byte Address[]; Consecutive
constraint c1 {foreach(op[i]) Opcodes
Differ
(i<op.size-1)->(op[i+1] != op[i]);}
constraint c2 {foreach(Address[j]) Addres[j] > 2*j;}
extern task init_arrays(n_op, n_addr);
endclass
© 2004 Synopsys, Inc. (32)
Agenda
¾ Introduction
• SystemVerilog Language Features
Data Types
Classes
Constraints
Threads
Functional Coverage
• Conclusion
© 2004 Synopsys, Inc. (33)
Dynamic Processes and Threads
• SystemVerilog adds dynamic parallel processes
using fork/join_any and fork/join_none
fork fork fork
join join_any join_none
• Threads execute until a blocking statement
wait for: (event, mailbox, semaphore, variable, etc.)
disable fork to terminate child processes
wait_child to wait until child processes complete
$exit terminates the main program thread
© 2004 Synopsys, Inc. (34)
Events – Enhanced from V2K
Events are variables
• Can be copied, passed to tasks
wait_order(), wait_any(), wait_all(<events>);
event.triggered;
• Persists throughout time-slice, avoids races
sequence abc;
@(posedge clk) a ##1 b ##1 c;
endsequence program test;
initial begin
@abc $display(“Detected a-b-c seq”);
end
endprogram
© 2004 Synopsys, Inc. (35)
Semaphore
• Semaphores are used to control unique
access to a resource
• Built-in Class and methods
get, put, try_get
semaphore semID = new(1);
semID.get(1); keys
semID.put(1);
© 2004 Synopsys, Inc. (36)
Mailbox
• Mailbox – Built-in Class
Built-in methods: num(), put(), try_put(),
get(), try_get(), peek(), try_peek()
Arbitrary type
mailbox #(type) mbID =
new(5);
packetN
packet1
mbID.get(msg);
mbID.put(msg);
Ensures meaningful, race-free
communication between processes
© 2004 Synopsys, Inc. (37)
Agenda
¾ Introduction
• SystemVerilog Language Features
Data Types
Classes
Constraints
Threads
Functional Coverage
• Conclusion
© 2004 Synopsys, Inc. (38)
Coverage
• Several types of coverage:
Code Coverage
Functional Coverage
Assertion Coverage
• Focus on Functional Coverage in this
presentation…
© 2004 Synopsys, Inc. (39)
Functional Coverage
Coverage Objects
• Random testing:
Did it work?
What did it do?
• Coverage is a list of items to test
Replaces test list
• When you get to 100%, design is done
• Shows testing progress
Design + Coverage Information
Testbench Object Model
© 2004 Synopsys, Inc. (40)
Functional Coverage
Coverage Objects
• Example: 1k FIFO buffer
Sampled: read ptr, write ptr
• 1M coverage points
Of interest: FIFO occupancy level
• Cover: (rd_ptr - wr_ptr) % 1k 0x3FF wr_ptr
• Still 1k coverage points
Of real interest: empty, full
• Cover: occupancy in {0; 1k}
• 2 coverage points
rd_ptr
Other potential points of interests 0x000
• Empty->Full->Empty transitions
• Read ptr ahead of write ptr
• Write ptr ahead of read ptr
• Empty/Full with ptr in {0; 1k}
© 2004 Synopsys, Inc. (41)
Functional Coverage
• New covergroup allows declaration of
Coverage points
• Variables, Expressions, Transitions
Cross coverage
Sampling expression : clocking event
enum { red, green, blue } color;
bit [3:0] pixel_adr; 3 bins for color
covergroup g1 @(posedge clk);
c: coverpoint color; 16 bins for pixel
a: coverpoint pixel_adr;
AxC: cross color, pixel_adr; 48 cross products
endgroup;
© 2004 Synopsys, Inc. (42)
Agenda
¾ Introduction
• SystemVerilog Language Features
Data Types
Classes
Constraints
Threads
Functional Coverage
• Conclusion
© 2004 Synopsys, Inc. (43)
SystemVerilog Feature Overview
Testbench Features
Dynamic Arrays Associative Arrays
Classes Inheritance Parameterized Classes
Program Block Clocking Domain Cycle Delays
Randomization & Constraints Dynamic Processes
Enhanced Events Mailboxes & Semaphores
Enhanced Constraints General Randomization
foreach Process Control Pack/Unpack
Sequence Assertion Features
Functional Virtual Events Sequences Properties
Coverage Interfaces Queues
Expect Sequence Operations
Bind Implication
Design Features Procedural Declarative
Structs Unions Packed Structs & Unions Instantiation Instantiation
Multi-d arrays Multi-d packed arrays
User-defined types Enums Property Composition
Interfaces Modports Property Operations
Implicit Port Connections
Always_comb Always_latch Always_ff
Packages Separate Compilation Operator Overloading
© 2004 Synopsys, Inc. (44)
The Importance of a Single
Language
Unified Scheduling Knowledge of
• Basic Verilog Other Language
won’t work Features
• Ensures Pre/Post- • Testbench and
Synth Consistency Assertions
• Enables • Interfaces and
Performance Classes
Optimizations • Sequences
and Events
Reuse of Syntax/Concepts
• Sampling for assertions and clocking domains
• Method syntax
• Queues use common concat/array operations
• Constraints in classes and procedural code
• Improves Debug Environment
© 2004 Synopsys, Inc. (45)
Thank You
Q&A
© 2004 Synopsys, Inc. (46)