System Verilog
INTRODUCTION, DATA
TYPES
⚫ System Verilog is a hardware description and
Verification language (HDVL).
⚫ It was developed by Accellera Systems Initiative and the IEEE
Standards Association to address the growing complexity of
modern digital systems.
⚫ System Verilog (IEEE Standard 1800-2005) is an extensive set of
enhancements to IEEE 1364 Verilog- 2001 standards.
⚫ It inherits features from Verilog, VHDL, C and C++.
⚫ One of the key advantages of using SV is its ability to streamline
the design and verification process.
⚫ Another significant advantage of System Verilog is its support
for advanced verification techniques, such as the Universal
Verification Methodology (UVM).
What is SV?
Features of SV
OOPS
Constrained
Randomizatio
n
Functiona
l
Coverage
Synchronizatio
n
Improved
Data
Types
Assertion
s
System
Verilog
Regions in SV
Inactive
NBA
Observed
Re-Active
Re-Inactive
Postpone
d
$strobe,
$monitor, PLI
Calls
Assertions are evaluated
Execute statements with #0 delay
Re-NBA
Preponed
Sample Data
before
entering
current time
slot (#1step)
Continuous, Blocking and RHS
of Non Blocking Assignment.
$display,
Non Blocking Assignments
Pass/ Fail code of
concurrent
assertions
#0 Statements in Program Block
NBA inside Program Block
Active
From Current
Time Slot
To Next
Time Slot
⚫System Verilog offers following Data
Types:
o 4-State
Type
o 2-State
Type
o Real
o Arrays
o User Define
Data Type
o Structures
o Unions
o Strings
o Enumerated
Type
o Class
⚫Allowed values are 0, 1, X and Z.
⚫Following 4-State types are included from
Verilog:
o wire //Size: 1-bit Value: Z
o reg //Size: 1-bit Value: X
o integer // Size: 32-bit Value: X
o time // Size: 64-bit Value: X
⚫User can define size for wire and reg.
⚫integer is signed, all others are
unsigned.
4-State Type
⚫Addition to System Verilog
o logic //Size: 1-
bit
⚫User can define size for
logic.
Value: X
⚫Logic is improved reg data type.
⚫Logic can be driven by continuous as well
as procedural assignments.
⚫Logic has a limitation that it cannot be
driven by
multiple drivers in such case use wire.
4-State Type
Logic
endmodul
Example1:
module and_gate ( input logic a,
b,
output logic c);
//driving logic using
continuous
assign c= a &
b; assignment
endmodule
Example2:
module flip_flop ( input logic din, clk,
output logic
dout); always @ (posedge clk)
dout<=din; //driving logic
using procedural assignment
Logic
driver
.
Example3:
module example3 ( input logic a, b,
output logic c);
assign c= a & b; //driving logic using
continuous assignment
always @ *
c= a | b;
assignmen
t
//driving logic using
procedural
eTnhdismcoodduelewill give compilation error
because of multiple
Logic
Compilation error, use wire to achieve this functionality.
Example4:
module example4 ( input logic a, b, ctrl,
output logic c);
assign c= ctrl?a:1’bZ; //driving logic using
continuous assignment
assign c= !ctrl?b:1’bZ; //driving logic using
continuous
assignmen
t
endmodul
e
⚫Allowed values are 0 and 1.
⚫System Verilog offers following 2-State Data
Types :
⚫ All are signed except bit which is
unsigned.
o shortint //Size: 16-bit Value: 0
o int //Size: 32-bit Value: 0
o longint //Size: 64-bit Value: 0
o byte //Size: 8-bit Value: 0
o bit //Size: 1-bit Value: 0
⚫User can define size for
bit.
2-State Type
Example1
c=‘0;
end
endmodul
e
// locations with given
number
module
example1; int a;
int unsigned b;
bit signed [7:0]
c;
initia
l
begi
n
a=-32’d127;
b=‘1;
//unsigned
integer
//same as byte
//SV offers un-sized literal to fill
all
Example2
module
example2; int a;
logic [31:0] b=‘Z;
initia
l
begi
n
a=b;
b=32
’h12
3x_5
678;
//b=32’hzzzz_zzzz
//
a=32’h0000_0000
if($unknown(b)) $display(“b is
unknown”); $display(“b is
known”);
else
end
end
mo
dul
⚫Included from Verilog
o real //Default Value
: 0
⚫real is same as double in C.
⚫Addition to System Verilog
o shortreal //Default Value : 0
o realtime //Default Value : 0
⚫shortreal is same as float in C.
⚫realtime and real can be used
interchangeably.
Real Type
⚫void data type represents non existing data.
⚫It can be used as return type of functions to
indicate nothing is returned.
Void
Usage:
display()
;
Example
:
function void
display;
$display(“Hello”)
; endfunction
⚫Arrays are used to group elements of same
type.
⚫Arrays can be categorized as following:
o Fixed Array
o Dynamic Array
o Packed Array
o Unpacked Array
o Queues
o Associative Array
Arrays
⚫Array whose size is fixed during compilation
time is called as Fixed Array.
⚫Size of fixed array cannot be modified during
run time.
element
Fixed Array
Examples
int array1
[15];
elements
//array of int containing
15
//Equivalent to int array1 [0:14]
int array2 [0:14];
logic array3 [7:0]; //array of logic
containing 8
⚫Unpacked Arrays can be declared by adding size
after array name.
⚫Unpacked Arrays can be made of any data
type. Example:
⚫System Verilog stores each element of an
unpacked
array in a longword (32-bit).
Unpacked Array
int array1 [16] [8];
bit array2 [3:0]
[7:0];
bit [7:0] array3 [4];
//16 rows , 8 columns
//4 rows , 8 columns
//4 rows each containing 8
bits
Unpacked Array
bit [7:0] array1
[4];
array1
[2]
array1
[3]
Unus ed 7 6 5 4 3 2 1 0
Unu sed 7 6 5 4 3 2 1 0
array1 [0]
Memory
array1 [1]
Memory
Unu sed 7 6 5 4 3 2 1 0
Memory
Unu sed 7 6 5 4 3 2 1 0
Memory
Unpacked Array
};
Initializing Array:
int array1 [2] [4] = ‘{ ‘{ 1, 2, 3, 4 } , ‘{ 5, 6, 7, 8 } };
int array2 [2] [3] = ‘{ ‘{ 1, 3, 6 } , ‘{ 3 {2} };
// same as ‘{ 1, 3, 6 } , ‘{ 2, 2, 2 }
int array3 [0:5] = ‘{1:5, 3:1, default: 0};
// same as ‘{0, 5, 0, 1, 0, 0}
int array4 [0:2] [1:4] = ‘{3 { ‘{ 2 {1, 2} } } };
// same as ‘{ ‘{1, 2, 1, 2} , ‘{1, 2, 1, 2} , ‘{1, 2, 1, 2} }
int array5 [2] [2] [2] = ‘{ ‘{ ‘{4, 5}, ‘{3, 1} }, ‘{ ‘{1, 7}, ‘{2,
5} }
Unpacked Array
Accessing
Array int
array1 [2] [4];
int array2 [0:5];
byte array3 [0:2]
[1:4]; int a, b;
byte c;
a= array1[1]
[3]; b=
array2[4];
c= array3[1]
[2];
Basic Array Operation
⚫Arrays can be manipulated using for and foreach
loop
bit [7:0] array1[10], array2[10] ;
initia
l
begi
n
for
( int
i=0; i
<$siz
e(arr
ay1);
//$size returns size
of
//k is defined
implicitly
Basic Array Operation
Example:
bit [7:0] array1[10] [20];
initia
l
begi
n
array
1=‘{1
0
{ ‘{0:
2, 1 :
0 ,
⚫Packed Arrays can be declared by adding size
before array name.
⚫One dimensional packed arrays are also referred
as vectors.
⚫Packed array is a mechanism of subdividing a vector
into subfields which can be accessed as array
elements.
⚫Packed array represents contiguous set of bits.
⚫Packed array can be made of single bit data (logic,
bit, reg), enumerated type or other packed arrays.
Packed Array
Packed Array
bit [3:0] [7:0]
array1;
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
array1[3
]
bit [7:0] a,
b;
bit [15:0] c;
bit d;
bit [31:0] e;
]
array1[1 array1[0]
[4]
array1[3:2
]
array
1
e=array1
;
a=array1[3];
b=array1[1];
c=array1[3:2];
d=array1[0]
[4];
Packed Array
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
Mixture of Packed and Unpacked
Array bit [3:0] [7:0] b [4];
b[0]
7 6 5 4 3 2 1 0 7 6 5
[
2
4]
3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
b[1
]
b[2
]
b[3
]
b[0]
[2]
b[1
]
b[2]
[2]
b[3]
[0]
b[0] [1]
[4:0]
Packed vs. Unpacked Array
⚫ Packed arrays are handy if user wants to access array with different
combination.
⚫ If user want to wait for change in array(i.e. @), in that case packed
array will be preferred over unpacked array.
⚫ Only fixed size arrays can be packed. Therefore it is not possible to
pack following arrays:
o Dynamic Arrays
o Queues
o Associative Arrays
Operation on Arrays
int A [0:7] [15:0] , B [0:7] [15:0];
⚫Following operation are possible for both packed
and
unpacked arrays.
⚫Both array A and B should be of same type and
size.
A=B;
A[0:3]= B[0:3];
A[1+:4]=
B[3+:4];
A[5]=B[5];
A==B A[2:4]!
=B[2:4];
//Copy
Operation
//Slice and Copy
//Comparison
Operations
Operation on Arrays
bit [3:0] [7:0] A;
⚫Following operation are only allowed in packed
arrays: A=0;
A=A + 3;
A=A * 2;
A=‘1;
A=A & 32’d255;
A[3:1]=16’b1101_1110_0000_1010;
⚫Dynamic arrays are unpacked arrays whose size can be
set
and changed during simulation time.
⚫new constructor is used to set or change size of
Dynamic Array.
⚫size() method returns current size of array.
⚫delete() method is used to delete all elements of the
array.
Dynamic Array
Dynamic Array
int dyn1 [ ];
int dyn2 [4]
[ ];
//Defining Dynamic Array (empty
subscript)
initial
begin
dyn1=new[10];
foreach (dyn1[ i ])
dyn1[ i ]=$random; dyn1=new[20]
(dyn1);
//Allocate 10
elements
// Initializing Array
// Resizing array and
// Copying older values
// Resizing to 50 elements Old Values are
lost
// Delete all elements
dyn1=new[50
]; dyn1.delete;
end
Dynamic Array
int dyn1 [ ]= ‘{5, 6, 7, 8} ; //Alternative way to define
size
initial
begin
repeat (2)
if (dyn1.size !=
0) begin
foreach(dyn1
[ i ] )
$display(“dyn1
[%0d]=%0d”, i,
dyn[ i ] );
dyn1.delete;
en
d
else
⚫A Queue is a variable size, ordered collection
of homogenous elements.
⚫Queues support constant time access to all
its elements.
⚫User can Add and Remove elements from
anywhere in
a queue.
⚫Queue is analogous to 1-D array that grows and
shrinks automatically.
⚫0 represents 1st element and $ represents last
element.
Queue
Queue
b > $ returns q [a:
$]
// Unbounded Queue
// Bounded Queue max size
is
0 < a < b returns queue with b - a + 1
elements. a = b = n returns q[n]
a > b returns empty queue
a or b is either x or z returns empty
queue a < 0 returns q [0: b]
Declaration:
int q1 [ $ ];
int q2 [ $ :
100 ]; 101
Operators
: q [ a :
b ];
⚫size() method returns number of elements in a
queue.
x=A.size();
Queue Methods
int A [$] = ‘{ 0, 1, 2, 3, 4, 5,
6 };
int x, y, z;
0 1 2 3 4 5 6
A
7
A.delete(5)
;
x
0 1 2 7 3 4 5 6
0 1 2 7 3 5 6
⚫insert(index, item) method is used to insert item
at a given index.
A.insert(3, 7); A
⚫delete(index) method is used to delete a queue if
index is not specified else it is used to delete item
at given index.
A
⚫pop_front() method removes and returns 1st element of
the queue.
y=A.pop_front()
;
⚫pop_back() method removes and returns last element of
the queue.
z=A.pop_back();
⚫push_front(item) method inserts item at the front
of the
queue.
A.push_front(9)
;
⚫push_back(item) method inserts item at the back of
the
queue.
A.push_back(8);
Queue Methods
1 2 7 3 5 6
A
1 2 7 3 5
A
9 1 2 7 3 5
A
9 1 2 7 3 5 8
A
y 0
6
z
Queue
int q [$] = ‘{ 5, 7, 9, 11,
2};
q = { q,
6 };
q = { 3,
q };
q = q
[1:$];
q = q[0:$-
1];
q = { q[0:3], 9,
q[4:$] }; q = {};
// q.push_back(6)
// q.push_front(3)
//
void'(q.pop_front())
// or q.delete(0)
//
void'(q.pop_back())
// or q.delete(q.size-
1)
// q.insert(4, 9)
// q.delete()
q = q[2:$];
q = q[1:$-
1];
// a new queue lacking the first two
items
// a new queue lacking the first and last
items
Array Query Functions
⚫$left returns the left bound of the dimension.
⚫$right returns the right bound of the dimension.
⚫$increment returns 1 if $left is greater than or equal
to
$right and –1 if $left is less than $right.
⚫$low returns the same value as $left if $increment
returns –1, and the same value as $right if $increment
returns 1.
Array Query Functions
⚫$high returns the same value as $right if $increment
returns –
1, and the same value as $left if $increment returns 1.
⚫$size returns the number of elements in the dimension.
⚫$dimensions returns total number of dimensions in the
array.
⚫$unpacked_dimensions returns total number of
unpacked dimensions for an array.
Array Locator Methods
⚫ Array locator methods works on unpacked arrays and returns
queue.
⚫ with clause is mandatory for the following locator methods:
⚫ find() returns all the elements satisfying the given expression.
⚫ find_index() returns the indices of all the elements satisfying the
given
expression.
⚫ find_first() returns the first element satisfying the given
expression.
Array Locator Methods
⚫find_first_index() returns the index of the first
element satisfying the given expression.
⚫find_last() returns the last element satisfying the
given expression.
⚫find_last_index() returns the index of the last
element satisfying the given expression.
Array Locator Methods
⚫ with clause is not mandatory for the following locator methods:
⚫ min() returns the element with the minimum value or
whose expression evaluates to a minimum.
⚫ max() returns the element with the maximum value or
whose
expression evaluates to a maximum.
⚫ unique() returns all elements with unique values or whose
expression evaluates to a unique value.
⚫ unique_index() returns the indices of all elements with unique
values
or whose expression evaluates.
Array Locator Methods
int a [6] = ‘{9, 1, 8, 3, 4, 4};
int b [$], c [$] = ‘{1, 3, 5, 7};
b = c.min; // {1}
b = c.max; // {7}
b = a.unique; // {1, 3, 4, 8,
9}
b = a.find with (item > 3); // {9, 8, 4, 4}
b = a.find_index with (item > 3); // {0, 2, 4, 5}
b = a.find_first with (item > 3); // {9}
b = a.find_first_index with (item==8); // {2}
b = a.find_last with (item==4); // {4}
b = a.find_last_index with (item==4); // {5}
Array Ordering Methods
⚫reverse() reverses the order of elements in an array.
⚫sort() sort array in ascending order with optional with
clause.
⚫rsort() sort array in descending order with optional
with clause.
⚫shuffle() randomizes the order of elements in an
array. 5 3 1 9 8 2 7
A
A
A
int A [7] = ‘{ 5, 3, 1, 9, 8, 2,
7};
A.reverse();
A.sort();
A.rsort()
;
7 2 8 9 1 3 5
1 2 3 5 7 8 9
9 8 7 5 3 2 1
A
Array Reduction Methods
⚫sum() returns sum of all elements in an array or specific elements if
with clause is present.
⚫product() returns product of all elements in an array or specific
elements if with clause is present.
⚫and() returns bitwise and of all array elements or specific elements if
with clause is present.
⚫or() returns bitwise or of all array elements or specific elements if
with clause is present.
⚫xor() returns bitwise xor of all array elements or specific elements if
• with clause is present.
⚫ In case size of data is not known or data space is sparse,
Associative array is a better option.
⚫ System Verilog allocates memory for an associative element
when they are assigned.
⚫ Index of associative can be of any type.
⚫ If index is specified as * , then the array can be indexed by
any integral expression of arbitrary size.
⚫ real and shortreal are illegal index type.
Associative Array
int array1 [ * ];
int array2
[ int ];
//Array can be
indexed by
any integral
expression.
int array3
[ string ];
//Indices can
be strings or
Associative Array
int xyz
[ * ];
0
xyz[0]=5;
xyz[1]=7;
xyz[2]=2;
xyz[3]=1;
xyz[7]=3;
xyz[10]=
9;
3 7 10
//Memory allocated during
assignment
5 7 2 1 3 9
Associative Array
1 2
⚫ num() and size() method returns number of elements in
associative
array.
⚫ delete(index) deletes element at given index if index is
specified else deletes entire array.
⚫ exists(index) checks whether an element exists at the
specified
index.
⚫ first(index) method assigns to the given index variable the
value of the first (smallest) index. first (smallest) index.
It returns 0 if the array is empty; otherwise, it returns 1.
Associative Array Methods
⚫ last(index) method assigns to the given index variable the
value of the last (largest) index in the associative array.
It returns 0 if the array is empty; otherwise, it returns 1.
⚫ next(index) method finds the smallest index whose value is
greater than the given index argument. Returns 1 if
new index is different as old index else 0.
⚫ prev(index) function finds the largest index whose value is
smaller than the given index argument. Returns 1 if
new index is different as old index else 0.
Associative Array Methods
int a [string]= ‘{“Jan”: 1, “Feb”: 2, “Mar”: 3, “April”: 4,
“May”:
5};
string index;
initia
l
begi
n
a.firs
t(ind
ex);
$display(a[index]);
while(a.next(index
//
index=Jan
//Go through all
index
Associative Array Methods
⚫System Verilog allows user to define new data
types using typedef keyword.
User Defined
typedef byte unsigned
uint8; typedef bit [15:0]
word;
//Defining
uint8
//Defining word
uint8 a,
b; word c,
d;
a=8’d10;
c=16’d25;
⚫Structure and Unions are used to group
non- homogenous data types.
⚫By default structure are unpacked.
⚫Unpacked structure can contain any data
type.
Declaration :
Structures
struct { bit [7:0] opcode;
bit [15:0] addr; }
IR;
struct {bit [7:0] r, g, b;}
pixel;
struct {int a, b; real b;}
mix;
Structures
IR=‘{opcode : 7’d8, addr :
15’d1}; pixel=‘{ 128, 255, 100};
pixel=‘{ r :128, g : 255, b :100};
pixel=‘{ int :0};
mix=‘{ 3, 5, 5.6};
mix=‘{ int : 1, real :
1.0}; mix=‘{ default :
0};
Initializing
:
int x;
bit [7:0] y;
pixel.r=200
; mix.a=3;
mix.c=4.5;
x=mix.b;
y=pixel.g;
Accessing :
Packed Structures
⚫Packed Structure is made up of bit fields which
are packed together in memory without gaps.
⚫A packed structure can be used as a whole to
perform arithmetic and logical operations.
⚫First member of packed array occupies MSB and
subsequent members follow decreasing
significance.
⚫Structures can be packed by writing packed
keyword which can be followed by signed or
unsigned keyword.
Packed Structures
Example :
typedef struct packed signed
{ shortint a;
//16-bits
[31:16]
byte b; //8-
bits
[15:8
]
[7:0]
bit [7:0] c; //8-
bits
} exam_st;
exam_st pack1;
bit [7:0] a, b, c;
pack1=‘{a: ’1, b: -10, c: 8’b1001_0101};
a=pack1.b;
b=pack1.c;
c=pack1[9:2]
;
Packed Structures
⚫Only packed data type and integer data types are
allowed inside packed structures
struct
packed
{ bit [3:0] a;
bit [7:0] b;
// default
unsigned
bit [15:0] c [7:0] ; } pack2;
Compilation Error packed structure cannot have
unpacked
element
Packed vs Unpacked Structures
struct { bit [7:0]
a;
bit [15:0]
b; int c;
} str1;
struct packed { bit [7:0]
a;
bit [15:0]
b; int c;
} str2;
31:24 23:16 15:8 7:0
Unused a
Unused b
c
55:48 47:32 31:0
a b c
⚫Union represents a single piece of storage element
that can be accessed by any of its member.
⚫Only one data types in union can be used at a
time. Example :
Unions
union
{
real a;
int b;
bit [7:0]
union packed
{
real a;
int b;
bit [7:0] c;
Unions
Example :
typedef
union
{
shortint
a; int b;
bit [7:0] c;
} my_un;
my_un un1;
un1.a=16’hf0f0
;
00 00 00 00
00 00 F0 F0
00 00 F0 AA
Structures vs Unions
Structure Union
Memory is allocated to
each and every
element.
Common memory is
allocated for all the
members.
Size of structure is sum of
size of each member or
more.
Size of union is equal to size
of largest member
First member is at offset 0. All member have 0 offset.
Modifying value of one
member
has no effect on other
members
Modifying value of one
member
modifies value of all members
⚫System Verilog string type is used to store
variable length strings.
⚫Each character of string is of type byte.
⚫There is no null character at the end of string.
⚫String uses dynamic memory allocation, so size of
string is no longer a concern.
Example :
string
s=“hello”;
String
String Operators
⚫str1 == str2 checks whether strings are equal or
not.
⚫str1 != str2 checks for inequality of strings.
⚫Comparison using lexicographical ordering of
strings.
o str1 < str2
o str1 <= str2
o str1 > str2
o str1 >= str2
⚫{str1, str2, str3, .. , strn} concatenation of strings.
String Operators
Example :
string s1=“hello”, s2=“Hello”,
s3=“xyz”; initial
begin
if(s1 != s2)
$display(“strings are
different”); if(s1 > s3)
$display(“s1 is more than
s3”); else
$display(“s3 is more than
s1”);
$display({s1, s2,
s3}); end
String Methods
⚫len() method returns length of a string.
⚫putc(position, character) method replaces
character at given position by character passed as
an argument.
⚫getc(position) method returns ASCII value of
character
at given position.
⚫toupper() method returns a string with all
characters in uppercase.
String Methods
⚫tolower() method returns a string with all
characters in lowercase.
⚫compare(string) compares given string with
string passed as an argument.
⚫icompare(string) same as above but comparison is
case insensitive.
⚫substr(i, j) returns a string formed between
characters at
position i and j.
String Methods
⚫atoi() method returns integer corresponding to
ASCII decimal representation.
⚫The conversion scans all leading digits and
underscore characters ( _ ) and stops as soon as it
encounters any other character or the end of the
string.
⚫itoa(i) stores the ASCII decimal representation of
i in sEtrxinagm.ple :
string s1=“12_3xyz”,
s2;
int a, b=127;
a=s1.atoi(); //a=123
s2.itoa(b); //
s2=“127”
String Methods
//Display: 83 (‘S’)
// Display: SYSTEMVERILOG
// "SystemVerilog3.1b"
// change b-> a
// Display: stem
s2=$psprintf("%s %0d", s1, 5);
$display(s2); // Display: SystemVerilog3.1a
5 end
Example :
string s1,
s2; initial
begin
s1 =
"SystemVeri
log";
$display(s1.
getc(0));
$display(s1.toupper()
); s1 = {s1, "3.1b"};
s1.putc(s1.len()-1,
"a");
$display(s1.substr(2,
5));
⚫An enumeration creates a strong variable type
that is limited to a set of specified names.
Example :
enum { RED, GREEN, BLUE } color;
typedef enum { FETCH, DECODE, EXECUTE } operation_e;
⚫enum are stored as int unless specified.
typedef enum bit [2:0] { RED, GREEN, BLUE }
color_e;
⚫First member in enum gets value 0, second value 1
and so on.
⚫User can give different values to member if
required.
Enumerated Type
Enumerated Type
Example :
enum { RED, GREEN, BLUE } color;
//RED=0, GREEN=1, BLUE=2
enum { GOLD, SILVER=3, BRONZE} medals;
//GOLD=0, SILVER=3, BRONZE=4
enum {A=1, B=3, C, D=4} alphabet;
//Compilation error C and D have same value
enum logic [1:0] {A=0; B=‘Z, C=1, D} exam;
//A=00, B=ZZ, C=01, D=10 Default value of exam is
X
⚫first() method returns first member of enumeration.
⚫last() method returns last member of enumeration.
⚫next(N) method returns the Nth next member
(default is
1) starting from current position.
⚫previous(N) method returns Nth previous
member (default is 1) starting from current
position.
Enumerated Type Methods
⚫Both next() and prev() wraps around to start and
end of enumeration respectively.
⚫num() method returns number of elements in
given enumeration.
⚫name() method returns the string
representation of given enumeration value.
Enumerated Type Methods
Enumerated Type Methods
Example
typedef enum { RED, BLUE, GREEN} color_e;
color_e mycolor;
mycolor =
mycolor.first; do
begin
$display("Color = %0d %0s", mycolor,
mycolor.name); mycolor = mycolor.next;
end
while (mycolor != mycolor.first); // Done at
wrap- around
const
⚫const keyword is used to define constants in
System Verilog.
⚫localparam constants are set during elaboration
time.
⚫const constants are set during simulation time.
Example:
const byte colon=
“:”; const real
pi=3.14;
Events
• Events are static objects useful for synchronization between the
process.
• Events operations are of two staged processes in which one process will
trigger the event, and the other processes will wait for an event to be
triggered.
• Events are triggered using -> operator or ->> operator.
• wait for an event to be triggered using @ operator or wait() construct
• System Verilog events act as handles to synchronization queues. thus,
they can be passed as arguments to tasks, and they can be assigned to
one another or compared.
• Syntax:
a) ->event_name;
b) @(event_name.triggered);
Casting
⚫Casting is used convert data from one type to other.
⚫There are two ways to perform casting :
o Static Casting: destination = return_type’ (source). This
type of casting always succeeds at run time and does
not give any error.
o Dynamic Casting: using $cast system task or function.
Example :
int a;
initial a=int’(3.0 * 2.0);
Casting
⚫System Verilog provides the $cast system task to
assign values to variables that might not ordinarily
be valid because of differing data type.
⚫ $cast can be called as either a task or a function.
$cast used as a function
if ($cast(destination,
source)) source
// should be singular
$cast used as a task
$cast(destination, source);
//destination
and
Casting
int a;
real b=3.0;
if($cast(a, b)) //Returns 1 if casting succeeds else
0
$display(“casting success”);
$cast(a, b); //If casting fails run time error
occurs
In both cases if casting fails then destination
value remains unchanged.
Casting
Example
: int a=-
10;
initia
l
begi
n
$dis
play(
a>>>
1);
$dis
// -5
// positive value
// changing to
constant
Casting
typedef enum { red, green, blue, yellow, white,
black } Colors;
Colors
col; int a,
b;
initial begin
col=green;
//col=3;
a= blue * 2;
b= col +
green; end
Runtime
error
Casting
en
d
typedef enum { red, green, blue, yellow, white,
black } Colors;
Colors col;
initial begin
$cast( col, 2 + 3 ); //
col=black
if ( ! $cast( col, 2 + 8 ) )
$display( "Error in
cast" );
//10: invalid
cast
col = Colors’(2 + 1);
col = Colors’(4 + 3);
//col=yellow
//value is
empty
System Verilog
OPERATORS,
SUBPROGRAMS
Operators
⚫Included from
Verilog
 Arithmetic
 Logical
 Relational
 Equality
 Bitwise
 Reduction
 Shift
 Concatenation
 Replication
 Conditional
+ - * / % **
! && ||
> < >= <=
== != === !==
~ & | ^ ~^ ^~
~^
^~
&
>>
~& | ~| ^
<< >>> <<<
{ op1, op2, op3, .. , opn }
{ no_of_times { a } }
cond ? True_Stm : False_Stm
Operators
>>>= <<<=
+= -= *= /=
%=
++ --
-> <->
&= |
=
^=
>>=
<<=
=?=
!?=
⚫Additions to System
Verilog
 Arithmetic
 Increment/Decrement
 Logical
 Bitwise
 Shift
 Wildcard Equality
 Set Membership
 Distribution
 Stream
insid
e dist
{<<{}} {>>{}
}
Example1
int a, b, c=2, d=6,
e=10; initial begin
a=d++;
b=+
+d;
c*=d;
c>>=1;
e%=3;
e+=2;
end
Result
: a = 6
b= 8
c= 8
d= 8
e= 3
Example2
int a, b, c,
d; initial
begin b=3;
if((a=b))
//brackets
compulsor
y
$display(“a=%d b=%d”, a,
b); (a=(b=(c=4)));
end
Result:
a=3
b=3 c=4
b=
4
a=4
//
Display
if ((a=b)) is same
as a=b;
if (a)
Example3
int a=1,
b=2; initial
begin if(a-
>b)
$display(“a
implies b”);
if (a<-> b)
$display(“a is logically equivalent
to b”);
end
a->b is same as !a || b
a<-> b is same as (!a || b) && (!b
|| a)
Result:
a implies b
a is logically equivalent to
b
Example4
int i=11,
range=0; bit
a=5’b10101;
initial begin
if(a=?=5’b1XZ01)
range+=1
; end
if(i inside { [1:5], [10:15], 17,18})// i is 1-5 or 10-15 or 17or 18
range+=1;
Result:
range=
2
//X and Z acts like don’t
care
Loops
⚫Included from Verilog
• for
• forever
• repeat
• while
⚫Additions to System Verilog
o foreach
o do while
Loops
inital
begin int
a [8] [5];
foreach ( a
[i, j] )
a[i]
[j]=$rando
m;
end
inital
begin int
i=10; do
begin
i -=1;
//statements end
while (i
>5) end
Statements executed first
an then execution depends
upon condition
Used to access
all elements in
an array
Break and Continue
inital
begin int
i;
repeat(10)
begin
if(i==7)
break;
i+=1;
en
d
en
inital
begin int
i;
repeat(10)
begin
if(i==7)
continue;
i+=1;
en
d
en
package
⚫Packages provide ways to have common code to
be shared across multiple modules.
⚫A package can contain any of the following:
o Data Types
o Subprograms (Tasks/Functions)
o Sequence
o property
⚫Elements of a package can be accessed by:
o :: (Scope Resolution Operator)
o import keyword
`include vs import
⚫`include is used to include the content of specified
file to the given location.
⚫It is equivalent to copying the content and pasting
at the given location.
`include “xyz.v”
⚫Import is used to access elements defined inside
the package without copying them to current
location.
import ::
element_name; import
:: *;
Example
“file1.sv”
function int add (input int a,
b );
add= a + b;
endfunctio
n
“file2.sv”
function int add (input int a,
b, c
);
add= a + b + c;
endfunction
`include “file1.sv”
`include
“file2.sv”
module test;
initial begin
int x=add(1, 2,
3);
int y=add(3, 4);
end
endmodule
Compilation error add
already exists
Example
“pack1.sv”
package
mypack1; int x;
add= a + b;
endfunctio
n
function int add (input int a, b ); function int add (input int
a, b, c
endpackag
e
“pack2.sv”
package
mypack2; int y;
);
add= a + b +
c; endfunction
endpackag
e
Example
`include “pack1.sv”
`include
“pack2.sv”
module test;
import
mypack1::*;
import
mypack2::*;
initial begin
x=mypack1 :: add(3, 6);
y=mypack2 :: add(4, 5,
3);
//x=9
//
y=12
unique and priority
⚫Improperly coded case statements can frequently
cause unintended synthesis optimizations or
unintended latches.
⚫System Verilog unique and priority keywords
are designed to address improperly coded
case and if statements.
⚫unique and priority keywords can be placed before
an if, case, casez, casex statement.
unique
⚫A unique keyword performs following checks:
o Each choice of statement is unique or mutually
exclusive.
o All the possible choices are covered.
⚫A unique keyword causes simulator to perform run
time checks and report warning if any of the following
conditions are true:
o More than one case item matches the case
expression.
o No case item matches the case expression, and there
is
no default case
unique
always @ *
unique case
(sel) 2’b00: y=a;
2’b01: y=b;
2’b01: y=c;
2’b10: y=d;
2’b11: y=e;
endcase
Result
:
Inputs
00 :
01 :
issue
d
x1 :
issue
d
11 :
Output
s y=a;
y=b;
warnin
g
Latch;
warning
y=e;
unique
always @*
casez (ip) 4’b1???
: y=2’b11;
4’b?1?? : y=2’b10;
4’b??1? : y=2’b01;
4’b???1 : y=2’b00;
default:
y=2’b00;
endcase
Synthesis
Result: Priority
Encoder
unique
always @*
unique casez (ip)
4’b1??? : y=2’b11;
4’b?1?? : y=2’b10;
4’b??1? : y=2’b01;
4’b???1 : y=2’b00;
default:
y=2’b00;
endcase
Synthesis
Result: Encoder
priority
⚫A priority instruct tools that choices should be
evaluated in order they occur.
⚫A priority case will cause simulation to report a
warning if all possible choices are not covered and
there is no default statement.
⚫A priority if will cause simulators to report a warning
if all of the if…if else conditions are false, and there is
no final else branch.
priority
always @ *
priority case
(sel) 2’b00: y=a;
2’b01: y=b;
2’b01: y=c;
2’b10: y=d;
2’b11: y=e;
endcase
Result
:
Inputs
00 :
01 :
x1 :
issue
d
11 :
Output
s y=a;
y=b;
Latch;
warnin
g
y=e;
priority
always @ *
Result:
Inputs Outputs
priority if (sel==2’b00) y=a; 00 : y=a;
else if (sel==2’b01) y=b; 01 : y=b;
else if (sel==2’b10) y=c; 10 : y=c;
else if (sel==2’b10) y=d; 11 : y=e;
else if (sel==2’b11) y=e; 1x : Latch;
warning
issue
d z1 :
issu
ed
Latch;
warning
Procedural Statements
⚫If there is label on begin/fork then you can put same
label on the matching end/join.
⚫User can also put label on other System Verilog
end statements such as endmodule, endfunction,
endtask, endpackage etc.
module
test; initial
for (int i=0; i<15; i+
+) begin : loop
…………….
end : loop
endmodul
e : test
Scope and Lifetime
⚫System Verilog adds the concept of global scope.
Any declaration and definitions which are declared
outside module, interface, subprograms etc has a
global scope.
⚫These declaration and definitions can be accessed by
any scope that lies below the current scope including
the current scope.
⚫All global variables have static lifetime i.e. they
exist till end of simulation. Global members can be
explicitly referred by $root.
Example
int i;
//task
increment
module test;
//task
decrement
initial begin :
label i=5;
#6 $root.i=3;
#3 increment;
#4 decrement;
end : label
task
increment;
i+= 1;
endtask
task
decrement;
$root.i-
=1;
endtask
Scope and Lifetime
Futurewiz
www.futurewiz.co.i
⚫Local declarations and definitions are accessible
at
scope where they are defined or scopes below it.
⚫By default all the variables are static in a local
scope.
⚫These variables can be made automatic.
⚫Static variables can be accessed by hierarchal
names.
Scope and Lifetime
⚫automatic variables cannot be accessed by hierarchical
name.
⚫automatic variables declared in an task, function, or block
are local in scope, default to the lifetime of the call or
block, and are initialized on each entry to the call or block.
⚫Static variables are initialized only once during the
simulation period at the time they are declared.
⚫Advantage of defining variables local to scope is that
there is no side effect i.e the variable is getting modified
by operations local to it.
Example1
int i;
module test;
int i;
initial
begin int i;
for (int
i=0; i<5; i+
+)
test.i=i
; i=6;
end
endm
//Global Declaration
//Local to module
//Local to initial block
//Local to for loop
//Modifies i inside
test
//Modifies i inside
initial
Example2
int svar1 =
1; optional
initial begin
for (int i=0; i<3; i++) begin :
l1 automatic int loop3 =
0;
for (int k=0; k<3; k++)
begin : l2
loop3++;
$display(loop3);
end : l2
// static
keyword
// executes every
loop
//loop3 destroyed
here
end :
l1
end
Result: 1 2 3 1 2 3 1 2 3
Example3
initial begin
for (int i=0; i<3; i++) begin :
l1 static int loop3 = 0;
for (int k=0; k<3; k++) begin : l2
loop3++;
$display(loop3);
end : l2
end :
l1 end
// executes
once
//loop3 stays till end
of
//simulation
Result: 1 2 3 4 5 6 7 8 9
Type Parameter
⚫A parameter constant can also specify a data type.
⚫This allows modules, interfaces, or programs to
have ports and data objects whose type can be set
for each instance.
module test #( parameter p1=1, parameter type
p2= logic)
( input p2 [p1:0] in, output p2 [p1:0]
op);
p2
[p1:0] x;
endmodul
e
Subprograms
⚫Following advancement has been done to
System Verilog Subprograms (Functions and
Task) :
o Default Port Direction : default port is input,
unless specified. Following types of ports
are allowed:
o input : value captured during subprogram
call.
o output: value assigned at end of
subprogram.
o inout : value captured at start assigned at
the end.
Subprograms
⚫Following advancement has been done to System Verilog
Subprograms (Functions and Task) :
o Default Data Type : Unless declared, data types of
ports is logic type.
o Default Value : Input ports can have default values. If
few
arguments are not passed, there default values are
taken.
o begin..end : begin end is no longer required.
o Return : return keyword can be used to return value in
case of functions and to exit subprogram in case of tasks.
o Life Time : Variables can be defined as static or automatic.
Function and Tasks
⚫Both Functions and Tasks can have zero or
more arguments of type input, output, inout
or ref.
⚫Only Functions can return a value, tasks cannot
return a value.
⚫A void return type can be specified for a function
that is not suppose to return any value.
⚫Functions executes in zero simulation time, where
as
tasks may execute in non zero simulation time.
Example1
function int add (int a=0, b=0,
c=0); return a + b+ c;
endfunction
initial begin
int y;
y=add(3, 5); //3+5+0
#3 y=add(); //0+0+0
#3 y=add(1, 2, 3); //1+2+3
#3 y=add(, 2, 1); //0+2+1
end
Example2
function void display (int a=0,
b=0);
$display(“a is %0d b=%0d”, a,
b); endfunction
//void
function
initial begin
display(3, 5); //a=3 b=5
#3 display(); // a=0 b=0
#3 display(1); // a=1 b=0
#3 display( , 3); // a=0 b=3
end
Example3
function int initialize(ref int a
[7:0]); foreach( a[ i ] )
a[ i ]=$rando
m; return 1;
endfunction
int b[7:0], status;
initial begin
status=initialize(b);
#3
void’(initialize(b));
end
//same as pointer concept
in c
// ignore return value
Example4
//If argument is const then subprogram cannot
modify it function void copy(const ref int a [7:0], ref
b [7:0]); foreach( a[ i ] )
b[ i ]=a[ i ];
endfunctio
n
int a[7:0],
b [7:0];
initial
begin
foreach (a [i] ) a
[ i ]=$random; copy(a, b);
Example5
task check (int a, output
b); if (!a) begin
b=1;
$display(“error”
); return; end
b=0;
endtask
initial begin
#3 check(5,
error);
#3 check(0,
error);
end
//
error=0
//
error=1
Example6
task add (int a=0, b=0, output int z); //Variables are
static by
//default
#2 z=a +
b; endtask
int x,
y;
initial fork
add(3, 5,
x);
#1 add(2,
4, y);
join
Resul
t
:
x=6
y=6
Example6
task add (int a=0, b=0, output int z); //Variables are
static by
//default
#2 z=a +
b; endtask
int x,
y;
initial
begin
add(3, 5,
x);
#1 add(2,
4, y);
Resul
t
:
x=8
y=6
Example7
task automatic add (int a=0, b=0, output
int
z); #2 z=a + b;
endtask
int x, y;
initial fork
add(3, 5 ,
x);
#1 y=add(2, 4 ,
y); join
Resul
t
:
x=8
y=6
System Verilog
CLASSES
Introduction
Futurewiz
www.futurewiz.co.i
⚫System Verilog introduces an object-oriented class
data type.
⚫Classes allow objects to be dynamically created,
deleted, assigned, and accessed via object handles.
⚫A class is a type that includes data and
subroutines (functions and tasks) that operate
on that data.
⚫class’s data is referred to as class properties,
and its
subroutines are called methods.
Example1
Futurewiz
www.futurewiz.co.i
class rectangle;
int lenght,
width;
function int area();
return lenght *
width; endfunction
function int perimeter();
return 2*(lenght +
width); endfunction
endclass
//class
properties
//class method
//class
method
Example2
Futurewiz
www.futurewiz.co.i
class person;
string name,
address;
properties
int number;
//
class
function void set_name(string
user); method
name=user
;
endfunctio
n endclass
//
class
Example3
Futurewiz
www.futurewiz.co.i
class
packet; bit
[7:0] data;
//class
property
tast
randomize();
data=$random;
endtask
//class
method
task display();
$display(“data is %d”,
data); endtask
endclass
Objects
Futurewiz
www.futurewiz.co.i
⚫A class defines a data type. An object is an instance of
that class.
⚫An object is created by defining a handler of class type
and then calling new function which allocates memory
to the object.
packet
p;
p=new();
//p is handler to class
packet
//Object is constructed
⚫If objects are not created then handler points to
null.
Default Constructor
Futurewiz
www.futurewiz.co.i
⚫new() is a default constructor which allocates memory
and initializes class variables for an object.
rectangle rec;
initial
begin
rec=new;
int a, p;
rec.set_size(3, 5);
a=rec.area;
//memory allocated to length and
width
p=rec.perimeter;
end
Constructor
endfunctio Futurewiz
www.futurewiz.co.i
⚫User can define customized constructers by writing
there own new function inside a class.
⚫The new method is defined as a function with no
return type.
⚫It is also possible to pass arguments to the
constructor,
which allows run-time customization of an object.
function new (int x=0,
y=0); length=x;
width=y;
Example
Futurewiz
www.futurewiz.co.i
class rectangle;
int lenght,
width;
function
new(int
x=1,y=1);.....
function int
area();
.............
function int
perimeter();
..........
rectangle r1, r2,
r3; int a1, a3, p1;
initial begin
r1=new(3, 5);
r2=new(4);
a1=r1.area;
p1=r2.perimete
r;
a3=r3.area;
//error r3 is null
end
Parameterized Class
• class packet #(number=10, type dtype= bit); dtype data
[number];
• function void randomize(); foreach(data[i])
data[i]=$random; endfunction
• function void display();
• foreach(data[i]) $display(“data[%0d”]=%0d”, i, data[i]); endfunction
• endclass
Futurewiz
www.futurewiz.co.i
Parameterized Class
Futurewiz
www.futurewiz.co.i
packet p1;
packet p2#(20);
packet p3#( ,
int);
packet p4#(30,
bit [3:0]);
initial begin
p1=new();
p2=new(); p4.display;
p4.randomize;
p4.display;
//number=10, dtype=bit
//number=20, dtype=bit
//number=10, dtype=int
//number=30, dtype=bit
[3:0]
p3=new()
;
p4=new()
;
This
Futurewiz
www.futurewiz.co.i
⚫The this keyword is used to unambiguously refer to
class properties or methods of the current instance.
int a;
function new(int
a); a=a;
endfunction
endclass
⚫The this keyword shall only be used within non-
static class methods, otherwise an error shall be
issued.
class example;
Now a is property of class as
well as
argument of function
new.
SV will look in local scope to
resolve reference to a, which in
this case is subroutine argument.
This
Futurewiz
www.futurewiz.co.i
class
example; int
a;
function new(int
a); this.a=a;
endfunction
endclass
⚫To solve this issue this keyword is used which now
refers to property a in current class instance.
example x,
y; initial
begin
x=new(5);
y=new(3);
$display(x.a)
;
$display(y.a)
; end
Fundamental Principles of OOP
Futurewiz
www.futurewiz.co.i
⚫Encapsulation
o It’s a concept that binds together the data and
functions
that manipulate the data.
o Encapsulation keeps both data and function safe
from outside world i.e. data hiding.
⚫Abstraction
o Abstraction is the concept of moving the focus from
the details and concrete implementation of things,
to the types of things, the operations available thus
making the programming simpler, more
general.
Fundamental Principles of OOP
the
function.
Futurewiz
www.futurewiz.co.i
⚫Inheritance
o New classes are created by inheriting properties
and
method defined in an existing class.
o Existing class is called the base class(parent
class), and the new class is referred to as
the derived class(child class).
⚫Polymorphism
o polymorphism means having many forms.
o A member function will cause a different
function to be
executed depending on the type of object that
Inheritance
Futurewiz
www.futurewiz.co.i
⚫Inheritance allows user to create classes which
are derived from other classes.
⚫The derived class (child class) inherits all the
properties and methods defined in base class
(parent class).
⚫Additional properties and methods can be defined in
child class.
⚫properties and methods defined in base class can
be overridden by redefining them in child class.
This phenomenon is called as overriding.
Example1
Futurewiz
www.futurewiz.co.i
class parent;
int a, b;
task display();
$display(“Paren
t Class”);
endtask
endclas
s
class child
extends parent;
int c;
task print();
$display(“Child
Class”); endtask
endclass
Example1
Futurewiz
www.futurewiz.co.i
parent p;
child c;
initial
begin
p=new;
c=new;
c.print;
c.display;
c.a=3;
p.a=4;
end
parent p child c
a=4 ; a=3 ;
b=0; b=0;
c=0;
Child Class
Parent
Class
Example2
Futurewiz
www.futurewiz.co.i
class
parent; int
a, b;
task
display();
$display(“Paren
t Class”);
endtask
endclas
s
class child extends
parent;
int a;
task display();
$display(“Child
Class”);
endtask
endclas
s
Display method and property a is overridden in
child
class
Example2
Futurewiz
www.futurewiz.co.i
parent p;
child c;
initial
begin
p=new;
c=new;
c.display;
p.display;
c.a=7;
p.a=2
; end
parent p child c
a=2 ; a=7 ;
b=0; b=0;
c=0;
Child Class
Parent
Class
Example3
endclas
s
Futurewiz
www.futurewiz.co.i
class
parent; int
a;
task
display();
$display(“Paren
t Class”);
endtask
endclas
class child
extends parent;
int a, b;
task display();
$display(“Child
Class”); super.display;
$display(super.a);
endtask
⚫A super keyword can be used to access properties
and methods defined in parent class from a child
class.
Example3
parent p;
child c;
initial
begin
p=new;
c=new;
p.a=5;
c.a=6;
p.display
;
c.display
; end
parent
p a=5 ;
Futurewiz
www.futurewiz.co.i
child
c
a=6 ;
b=0;
Parent
Class
Child Class
Parent
Class
0
Inheritance
Futurewiz
www.futurewiz.co.i
⚫Every time when child object is created,
constructer of parent (super.new) is called first
implicitly.
⚫If a new function has been defined in parent which
accepts a set of arguments and arguments don’t
have default values. In such a case super.new has
to be explicitly specified with required arguments.
⚫It is because of this reason that child class is able to
access properties and methods defined in parent
class.
Example4
Futurewiz
www.futurewiz.co.i
class parent;
function
new();
$display(“Paren
t Class”);
endfunctio
n endclass
initial
begin
child c;
c=new
; end
class child
extends parent;
function new();
$display(“Child
Class”); endfunction
endclass
Parent
Class
Child
Class
Example5
Futurewiz
www.futurewiz.co.i
class parent;
function
new(string
str);
$display(str)
;
endfunction
endclass
initial begin
child
c;
c=new
class child
extends parent;
function new();
$display(“Child Class”);
endfunction
endclass
Error super.new is
not called
Example6
Futurewiz
www.futurewiz.co.i
class parent;
function new(string
str=“
”);
$display(str)
;
endfunction
endclass
initial begin
child
c;
c=new
class child
extends parent;
function new();
$display(“Child
Class”); endfunction
endclass
en
d
Child Class
No error, parent constructor has
default value
Example7
Futurewiz
www.futurewiz.co.i
class parent;
function
new(string
str);
$display(str)
;
endfunction
endclass
initial begin
child
c;
c=new
class child
extends parent;
function new();
super.new(“Pare
nt
Class”);
$display(“Child
Class”);
endfunctio
n
ePnadrcela
Example8
•class
rectangle; int
length, width;
•function new(int x,
y); this.length=x;
this.width=y;
endfunction
•function int area(int x,
y);.... function int
perimeter(int x,
• y);...
Futurewiz
www.futurewiz.co.i
class square
extends rectangle;
int size;
function new(int
size); this.size=size;
super.new(size,
size); endfunction
endclas
s
square sq=
new(5);
sq.area;
sq.perimete
r;
Encapsulation
members can also be accessed by child class.Futurewiz
www.futurewiz.co.in
⚫Till now classes have members which were accessible
to rest of the program. However in many situation
such functionality are not desired.
⚫Example: In cars we are not concerned by how
engine works but we our focus is how to control it.
⚫System Verilog provides various ways of hiding
class members:
o local keyword will ensure that the members
are available only to the method of the
same class.
o protected keyword is similar to local keyword
but
Example1
Futurewiz
www.futurewiz.co.i
class rectangle;
int length,
width;
function new(int x,
y); this.length=x;
this.width=y;
endfunction
function int area;
…. endclass
rectangle rec;
initial begin
rec=new(2,
3); rec.area;
rec.length=5;
//length is
modified
rec.area;
en
d
Example2
Futurewiz
www.futurewiz.co.i
class rectangle;
local int length,
width;
function new(int x,
y); this.length=x;
this.width=y;
endfunction
function int area; ….
en
d
endclass
rectangle
rec;
initial begin
rec=new(2,
3); rec.area;
rec.length=5;
rec.area;
//
error
Example3
Futurewiz
www.futurewiz.co.i
class rectangle;
local int length,
width;
function new(int x,
y); this.length=x;
this.width=y;
endfunction
function int area;
….
endclas
s
class square extends
rectangle;
function new (int
x); super.new(x, x);
endfunction
endclas
s
square sq;
initial
sq=new(3);
Error length and width are local to
class rectangle
Example4
squar
e
Futurewiz
www.futurewiz.co.i
class rectangle;
protected int length,
width;
function new(int x,
y); this.length=x;
this.width=y;
endfunction
function int area;
….
endclass
class square extends
rectangle; function new (int
x); super.new(x, x);
endfunctio
n endclass
square sq;
initial
sq=new(3);
Now length and width are accessible to both rectangle
and
Lifetime in Class
Futurewiz
www.futurewiz.co.i
⚫By default properties and methods defined inside a
class
have automatic lifetime.
⚫Memory to properties are allocated dynamically
when a new instance of the class is created.
⚫User can define properties and methods as static. A
static property is a class variable that is associated
with the class, rather than an instance of the class.
Lifetime in Class
Futurewiz
www.futurewiz.co.i
⚫Memory to static properties and methods are
allocated
during elaboration time.
⚫Scope resolution operator ( :: ) can be used to
access static property and methods defined inside
a class.
⚫Static properties and methods can be accessed
without creating any instance of a class.
Example1
Futurewiz
www.futurewiz.co.i
packet p1, p2, p3;
class packet;
static int id; initial begin
int val; //default: automatic p1=new; $display(p1.id,
p1.val);
function
new(); id++;
val++;
endfunctio
n
endclas
s
p2=new; $display(p2.id,
p2.val); p3=new;
$display(p3.id, p3.val);
p2.id=7; p2.val=3;
$display(p1.id, p1.val);
$display(p2.id, p2.val);
$display(packet :: id);
end
Example1
Futurewiz
www.futurewiz.co.i
Result
:
p1.id=
1
p2.id=
2
p3.id=
3
p1.id=
7
p2.id=
7
p1.val=
1
p2.val=
1
p3.val=
1
p1.val=
1
p2.val=
3
packet ::
7
Example2
Futurewiz
www.futurewiz.co.i
class packet;
static int id;
int val; //default:
automatic
function
new();
id=id+1;
val=val+1;
endfunction
endclas
s
initial begin
packet::
id=3;
$display(packet::id
); packet p1;
p1=new;
$display(packet::id
); end
Resul
t
id=3;
id=4
;
Functions and Tasks
Futurewiz
www.futurewiz.co.i
⚫Task and Functions defined inside class have
automatic
lifetime for their arguments and variables.
⚫A static keyword can be added after Task/Function
to make arguments and variables static in nature.
⚫A function prototype can be declared inside a class
and body can be defined outside class with help of
extern keyword.
Example1
Futurewiz
www.futurewiz.co.i
class
test;
task
increment; int
i;
i++;
$display(“i=%d”,
i); endtask
endclass
initial begin
test t1;
t1=new;
t1.incremen
t;
t1.incremen
t;
t1.incremen
t; end
Resul
t
:
i=1
i=1
i=
1
Example2
Futurewiz
www.futurewiz.co.i
class
test;
task
increment;
static int x;
int y; x+
+; y++;
$display(“x=%d y=%d”,
x, y);
endtask
endclass
initial begin
test t1;
t1=new;
t1.incremen
t;
t1.incremen
t;
t1.incremen
t; end
Result:
x=1 y=1
x=2 y=1
x=3
y=1
Example3
endclas
s Futurewiz
www.futurewiz.co.i
class
test;
task static
increment; int x;
int y; x+
+; y++;
$display(“x=%d y=%d”,
x, y);
endtask
initial begin
test t1;
t1=new;
t1.incremen
t;
t1.incremen
t;
t1.incremen
t; end
Result:
x=1 y=1
x=2 y=2
x=3
y=3
Example4
Futurewiz
www.futurewiz.co.i
class
test;
task static
increment; int x;
automatic int
y; x++; y++;
$display(“x=%d y=%d”,
x, y);
endtask
endclass
initial begin
test t1;
t1=new;
t1.incremen
t;
t1.incremen
t;
t1.incremen
t; end
Result:
x=1 y=1
x=2 y=1
x=3
y=1
Example5
Futurewiz
www.futurewiz.co.i
class rectangle;
local int length, width;
extern function new(int x,
y); extern function int
area();
endclass
function rectangle ::
new(int
x, y);
this.length=
x;
this.widht=y;
endfunction
function int
rectangle::area(); return
length*width; endfunction
Functions and Tasks
Futurewiz
www.futurewiz.co.i
⚫ Functions and Tasks can be local as well as protected.
⚫ Functions and Tasks can also be declared as static. The lifetime
of variables inside static methods are automatic by
default.
⚫ Memory to static methods are allocated during elaboration
time.
⚫ A static methods can only access static members of a class.
⚫ A static method can be called without creating instance of a
class. They can be accessed by scope resolution operator(::).
Example1
Futurewiz
www.futurewiz.co.i
class
test; int i;
local function void
increment; i++; $display(“i=
%0d”, i); endtask
function void
inc; increment;
endfunction
endclass
initial
begin test
t1;
t1=new;
t1.inc;
t1.inc;
//
t1.increme
nt;
will give
//compilation
error end
Resul
t
:
i=1
i=2
Example2
endclas
s Futurewiz
www.futurewiz.co.i
class test;
static function int add(int
x, y);
int
i; i+
+;
$di
spl
ay(“
i=
%0
initial begin
$display(test::add(3,2))
;
$display(test::add(1,1))
; end
Result:
5
i=1
2
i=1
Example3
endclas
s Futurewiz
www.futurewiz.co.i
class test;
int i;
static function int add(int
x, y);
i++;
$display(“i=%0d”, i);
return x +
y;
endfunctio
n
initial begin
$display(test::add(3,2))
;
$display(test::add(1,1))
; end
Result :
Error, Static function cannot
access non-static class properties
Example4
•class test;
•static int i;
• static function int
add(int x, y);
•i++;
•$display(“i=%0d”,
i); return x + y;
•endfunction
endclas
s Futurewiz
www.futurewiz.co.i
initial begin
$display(test::add(3,2))
;
$display(test::add(1,1))
; end
Result:
5
i=1
2
i=2
Polymorphism
Futurewiz
www.futurewiz.co.i
⚫Polymorphism is an ability to appear in many
forms.
⚫In OOPS multiple routines sharing a common name
is
termed as Polymorphism.
⚫In SV, Polymorphism allows a parent class handler
to hold sub class object and access the methods of
those child classes from the parent class handler.
⚫To achieve this, functions/tasks in SV are declared
as virtual functions/tasks which allow child
classes to override the behaviour of the
Example1
Futurewiz
www.futurewiz.co.i
class shape;
protected x, y,
z;
virtual function
void display();
$display(“I am
shape”); endfunction
//Main
Class
//Function call can
be
// overridden, will call
//child function
instead
virtual function void
perimeter();
$display(“I don’t know
perimeter”); endfunction
endclass
Example1
Futurewiz
www.futurewiz.co.i
class rectangle extends
shape; virtual function void
display();
$display(“I am
rectangle”); endfunction
virtual function void
perimeter();
$display(“perimeter=%0d”, 2*(x +
y)); endfunction
function new (int x,
y); ..... endclass
Example1
Futurewiz
www.futurewiz.co.i
class square extends
rectangle; //This function call
//cannot be
overridden
function void display();
$display(“I am
square”); endfunction
function void perimeter();
$display(“perimeter=%0d”,
4*x); endfunction
function new (int
x); ..... endclass
Example1
Futurewiz
www.futurewiz.co.i
class triangle extends
shape; function void
display();
$display(“I am a
triangle”); endfunction
function void
perimeter();
$display(“perimeter=%0d”, (x + y +
z)); endfunction
function new (int x, y,
z); ..... endclass
Example1
Futurewiz
www.futurewiz.co.i
shape s1, s2;
rectangle
r1,r2; square
sq1; triangle
t1;
initial begin
s1=new;
r1=new(2, 3);
sq1=new(4);
t1=new(1, 2,
3);
s1.display
;
r1.display
;
t1.display;
s2=t1;
s2.display
; r2=sq1;
r2.display
; s2=r1;
s2.display
s1.perimete
r;
r1.perimeter
;
t1.perimeter
;
s2.
perimeter;
r2.
perimeter;
s2.
perimeter;
Example1
Futurewiz
www.futurewiz.co.i
Result :
I don’t
know
I am
shape
perimete
r
I am
rectangle I
am triangle
I am triangle
I am square
I am
Perimeter=
10
Perimeter= 6
Perimeter= 6
Perimeter=
16
Perimeter=
10
Example2
•class parent;
int a=3;
•function void
d1();
•$display(“Parent d1”);
endfunction
•virtual function void
d2();
•$display(“Parent d2”);
endfunction
•endclass
• class child extends
parent;
• int b=8;
• function void d1();
• $display(“Child d1”);
• endfunction
• function void d2();
• $display(“Child d2”);
• endfunction
endclas
s
Futurewiz
www.futurewiz.co.i
Example2
Futurewiz
www.futurewiz.co.i
initial begin
parent p1; child
c1;
c1=new;
$cast(p1, c1);
//p1=c1;
// checks run-time casting
errors
//checks compile time casting
errors
//properties and virtual methods in parent
class
//points to one defined in child
class p1.d1; p1.d2;
$display(“p1.a=%0d”, p1.a);
c1.a=9;
$display(“p1.a=%0d”,
Example2
Result :
Parent
d1
Child
d2
p1.a=5
p1.a=9
parent p child c
null a : inherited
b : local;
d1 : inherited;
d2 : inherited;
d1 :
overridden;
d2 :
overridde
n;
parent p
after
p1=c1;
parent points to child memory
for inherited properties and
virtual methods
child c
a : inherited
b : local;
d1 : inherited;
d2 : inherited;
d1 :
overridden;
d2 :
overridde
n;
Futurewiz
www.futurewiz.co.i
Example3
•class parent;
int a=3;
•function void
d1();
•$display(“Parent d1”);
endfunction
•virtual function void
d2();
•$display(“Parent d2”);
endfunction
•endclass
• class child extends
parent;
• int a=5; b=8;
• function void d1();
• $display(“Child d1”);
• endfunction
• function void d2();
• $display(“Child d2”);
• endfunction
endclas
s
Futurewiz
www.futurewiz.co.i
Example3
Futurewiz
www.futurewiz.co.i
initial begin
parent p1; child c1;
c1=new;
p1=c1; //Polymorphism
occurs
//c1=p2; will give
compilation error p1.d1; p1.d2;
$display(“p1.a=%0d”, p1.a);
c1.a=9;
$display(“p1.a=%0d”,
p1.a); end
Example3
Result
:
Paren
t d1
Child
d2
p1.a=3
p1.a=3
Modifying parent’s a will not
modify child’s a since it is
overridden in
parent p child c
null a : inherited
a : overridden
b : local;
d1 : inherited;
d2 : inherited;
d1 :
overridden;
d2 :
overridde
n;
parent p
after
p1=c1;
child c
a : inherited
a : overridden
b : local;
d1 : inherited;
d2 : inherited;
d1 :
overridden;
d2
:
overridde
n;
child
.
Futurewiz
www.futurewiz.co.i
Abstraction
Futurewiz
www.futurewiz.co.i
⚫Sometimes, it is useful to create a class without
intending to create any objects of the class.
⚫The class exists simply as a base class from which
other classes can be derived.
⚫In System Verilog this is called an abstract class and
is declared by using the word virtual.
⚫A virtual class object can not be constructed but
handle to
the virtual class can be defined.
Abstraction
Futurewiz
www.futurewiz.co.i
⚫Virtual methods can be declared without any body.
⚫These methods can be overridden in a derived class.
⚫The method overriding virtual method should have
same signature i.e. (return type, number and type of
arguments) must be the same as that of the virtual
method.
⚫If a virtual method is defined as pure then these
methods must be defined in child classes. A pure
virtual method forces child classes to implement
standard set of methods.
Example1
Futurewiz
www.futurewiz.co.i
virtual class
abstract;
//Abstract
Class
virtual task
display();
//Virtual Method
//Body not
defined
function int increment(int
x);
return x +
1;
endfunctio
n endclass
Example1
endclas
s
Futurewiz
www.futurewiz.co.i
class abc extends
abstract;
task
display();
defined
$display(“abc”)
; endtask
// display may or may not
be
function int increment(int x);
//Overriding return x + 2;
endfunction
Example1
Futurewiz
www.futurewiz.co.i
class xyz extends
abstract;
task
display();
defined
$display(“xyz”)
; endtask
// display may or may not
be
//Increment function may not be
defined endclass
Example1
Futurewiz
www.futurewiz.co.i
abstract
ab; abc a;
xyz x;
int p1,
p2;
initial begin
//ab=new; not allowed
//will give compilation
error a=new;x=new;
a.display;
x.display;
p1=a.increment(2);
p2=x.increment(5);
ab=x; ab.display;
ab=a; ab.display;
end
Results:
abc
4
xyz
xyz
6
abc
Example2
Futurewiz
www.futurewiz.co.i
virtual class
abstract;
//Abstract
Class
pure virtual task display();
//Pure Virtual Method
virtual function int increment(int x);
//Virtual
Function
//Body may not be
defined
endclass
Example2
Futurewiz
www.futurewiz.co.i
class abc extends
abstract;
task display();
$display(“abc”)
; endtask
//display method needs to be defined
//will give compilation error if not
defined
function int increment(int
x);
return x +
2;
endfunctio
n
//Increment function
may
// or may not be
defined
endclas
s
Nested Class
Futurewiz
www.futurewiz.co.i
⚫A class can contain instance of another class using
handle to an object. Such classes are called as
Nested Classes.
⚫Common reasons for using containment are reuse
and controlling complexity.
class Node;
Node left,
right;
//properties and methods
for Node
endclass
Example
endclas
s
Futurewiz
www.futurewiz.co.i
class timestat;
time
start_time,
end_time;
function void
start;
start_time=$time
; endfunction
function void
end;
end_time=$time;
Example
Futurewiz
www.futurewiz.co.i
class
packet; int
data[7:0];
timestat t;
function
new; t=new;
endfunction
extern task
transmit; endclass
task packet ::
transmit(); t.start;
//do some
operation t.end;
endtask
Typedef Class
Futurewiz
www.futurewiz.co.i
⚫A forward declaration is a declaration of a object
which
the programmer has not yet given a complete
definition.
⚫System Verilog language supports the typedef class
construct for forward referencing of a class
declaration.
⚫This allows for the compiler to read a file from
beginning to end without concern for the
positioning of the class declaration.
Example
Futurewiz
www.futurewiz.co.i
module
test; class
packet;
timestat t;
//
definitions
endclass
class
timestat;
//
definitions
Compilation error
class
timestat is not
defined.
Timestat is referred
before it is defined
Example
Futurewiz
www.futurewiz.co.i
module test;
typedef class
timestat;
class
packet;
timestat t;
//
definitions
endclass
class
timestat;
//
definitions
enclass
typedef allows
compiler to process
packet class before
timestat class.
Copy
Futurewiz
www.futurewiz.co.i
⚫User can make a copy of an object to keep a routine
from modifying the original.
⚫There are two ways of copying an object:
o Using built-in copy with new function (Shallow
Copy)
o Writing your own complex copy function (Deep
Copy)
⚫Using new to copy an object is easy and reliable. A
new object is constructed and all variables from the
existing object are copied.
Shallow Copy
Futurewiz
www.futurewiz.co.i
class pkt;
bit addr
[15:0];
bit [7:0]
data; int
status;
function new();
addr=$randomiz
e;
data=$randomiz
e; status=0;
endfunction
endclass
pkt src, dst;
initial begin
src=new;
dst=new
src; end
//create
object
//copy to dst
src dst
addr=5 ; addr=5 ;
data=10; data=10;
status=0; status=0;
Shallow Copy
Futurewiz
www.futurewiz.co.i
⚫Shallow copy is similar to photocopy, blindly
copying values from source to destination.
⚫If a class contains handle to another class then only
top level objects are copied by new, not the lower
one.
⚫When using new to copy objects, the user define
new constructer is not called. New function just
copies the value of variables and object handle.
Example
Futurewiz
www.futurewiz.co.i
class pkt;
bit addr [15:0];
bit [7:0] data;
int id; static int
count;
timestat t;
function
new();
id=count++;
t=new;
endfunction
endclass
class timestat;
time
start_time,
end_time;
endclass
Example
packet src, dst;
initial begin
src=new;
src.t.start_time=1
0;
dst=new src;
//handle of t is
copied
//id is not
incremented
dst.t.start_time=1
4;
//modifies t since
// handler is
common end
src
id=1
;
dst
id=1
;
t
start_time=14 ;
Futurewiz
www.futurewiz.co.i
Deep Copy
Futurewiz
www.futurewiz.co.i
⚫User can write his own deep copy function.
⚫This user defined copy function should copy the
content of class handle, not handle itself.
Example
Futurewiz
www.futurewiz.co.i
class pkt;
bit addr [15:0];
bit [7:0] data;
int id; static int count;
timestat t;
function
new();
id=count++;
t=new;
endfunction
extern function pkt
copy; endclass
function pkt pkt :: copy;
copy=new;
copy.addr=this.addr;
copy.data=this.data;
copy.t.start_time=this.t.start_
ti me;
copy.t.end_time=this.t.end_ti
m e;
endfunction
Example
initial
begin pkt
src, dst;
src=new;
src.t.start_time=
3; dst=src.copy;
dst.t.start_time=
7; end
src
id=1
;
dst
id=2
;
t
start_time=3 ;
t
start_time=7 ;
Futurewiz
www.futurewiz.co.i
Interface Class
Futurewiz
www.futurewiz.co.i
⚫ A set of classes can be created that have a common set
of behaviors. This set is called Interface class.
⚫ An interface class can only contain pure virtual functions,
type declaration and Parameter declarations.
⚫ Pure functions are function that don’t have any
implementation.
⚫ implements keyword is used to define a class that
implements
function defined in interface class.
⚫ When interface class is implemented then nothing is
extended, implementation of pure virtual function is
defined in class that implements interface class.
Interface Class
Futurewiz
www.futurewiz.co.i
interface class shape #(type
id=int); int a;
pure virtual function id area(id x=0, y=0);
pure virtual function id perimeter(id x=0,
y=0); endclass
Interface Class
Futurewiz
www.futurewiz.co.i
class int_rectangle implements shape
#(int);
virtual function int area(int x=0,
y=0); return x*y;
endfunction
//virtual
keyword
//compulsory
virtual function int perimeter(int x=0,
y=0); return 2*(x+y);
endfunction
//a defined in interface class cannot be
accessed
endclass
Interface Class
Futurewiz
www.futurewiz.co.i
class real_rectangle implements
shape #(real);
virtual function real area(real x=0,
y=0); return x*y;
endfunction
virtual function real perimeter(real x=0,
y=0); return 2*(x+y);
endfunction
endclass
Singleton Class
Futurewiz
www.futurewiz.co.i
class
singleton; int
a;
static
singleton obj;
local function new (int
a); this.a=a;
endfunction
//static function
endclass
static function singleton
create(int a);
if
(obj==null)
obj=new(a);
return obj;
endfunctio
n initial
begin
singleton
s1;
⚫These are classes that restricts instantiation of class
to just one object.
Semaphore
Futurewiz
www.futurewiz.co.i
⚫ Semaphore is a built-in class which conceptually is a bucket.
⚫ When semaphore is allocated, then a bucket containing fixed
number of keys is created.
⚫ Process using semaphore must first procure a key from bucket
before
they can continue to execute.
⚫ Once process is over, key should be returned back to the bucket.
⚫ Semaphore is basically used to control access to shared
resources.
Semaphore - Methods
Futurewiz
www.futurewiz.co.i
⚫new() method is used to create semaphore with
specified
number of keys. Default key count is 0.
⚫put() method is used to return specified number of
keys to semaphore. Default value is 1.
⚫get() method is used to procure specified number of
keys from semaphore. Default value is 1.
Semaphore - Methods
Futurewiz
www.futurewiz.co.i
⚫In get() method if the specified number of keys is
not available, the process blocks until the keys
become available.
⚫try_get() method is used to procure a specified
number of
keys from a semaphore, but without blocking.
⚫In try_get() method if the specified number of keys are
not available, the method returns 0 else a positive
value and continues.
Example
semaphore
smp; int got=0;
initial begin
smp=new(5);
#5
smp.get(3);
#6
smp.get(1);
got=got +1;
#2 if(smp.try_get(3)) got=got
+1; end
initia
l
begi
n
#8
smp.
get(2
);
#7
smp. Futurewiz
www.futurewiz.co.i
Example
Futurewiz
www.futurewiz.co.i
module test;
semaphore
smp; int a=0;
smp=new(1);
initial
fork
//statement1
//
statement2
join
begin :
statement1
smp.get;
a=7;
#3 smp.put;
end
statement1
begin :
statement2
smp.get;
a=3;
Mailbox
Futurewiz
www.futurewiz.co.i
⚫Mailbox is a built-in class that allows messages to
be exchanged between processes.
⚫Data can be sent to mailbox by one process and
retrieved by another.
⚫Mailbox can be bounded or unbounded queues.
⚫Mailbox can be parameterized or Non-parameterized.
⚫Non-Parameterized mailboxes are typeless , that is
single
mailbox can send and receive different type of data.
Mailbox - Methods
Futurewiz
www.futurewiz.co.i
⚫new() method is used to create mailbox with size
specified as an argument.
⚫If size is defined as 0 (default) then mailbox is
unbound.
⚫num() method is returns the number of message
currently present inside mailbox.
⚫put() method places a message in a mailbox in a
FIFO order.
⚫If the mailbox is bounded, the process shall be
suspended
until there is enough room in the queue.
Mailbox - Methods
Futurewiz
www.futurewiz.co.i
⚫try_put() method attempts to place a message in
mailbox. This method is meaningful only for bounded
mailboxes.
⚫If mailbox is full this method returns 0 and message is
not placed else it returns 1 and message is placed.
⚫get() method retrieves a message from a mailbox.
⚫This method removes message from a mailbox and
calling process is blocked if mailbox is empty.
⚫try_get() method attempts to retrieves a message from
a
mailbox without blocking.
Mailbox - Methods
Futurewiz
www.futurewiz.co.i
⚫ peek() method copies message from a mailbox without
removing message from the queue.
⚫ If mailbox is empty then current process is blocked till a
message is placed in the mailbox.
⚫ If the type of the message variable is not equivalent to the type
of the
message in the mailbox, a run-time error is generated.
⚫ try_peek() method attempts to copy a message from a mailbox
without blocking. If the mailbox is empty, then the method
returns 0 else if variable type is different it returns negative
number else positive number is returned.
Parameterized Mailboxes
Futurewiz
www.futurewiz.co.i
⚫By default mailboxes are typeless. They can send
and receive different data types. This may lead to
runtime errors.
⚫Mailbox type can be parameterized by passing type
as a argument.
mailbox #(string) mbox;
⚫In parameterized mailboxes, tools catches type
mismatch errors at compilation time.
Example
Futurewiz
www.futurewiz.co.i
module
test;
mailbox
mb;
//typeless
Mailbox
string s; int
i; initial
begin
mb=new();
//Unbound
Mailbox
$monitor(“s=%s and i=%0d at time=%0d”, s, i,
$time); fork gen_data;
rec_data;
join end
endmodul
e
Example
Futurewiz
www.futurewiz.co.i
task gen_data;
mb.put(“Hello”
); #3
mb.put(7);
#4
mb.put(“Test”);
#3 mb.put(3);
#3
mb.put(“Hi”);
#2
mb.put(9);
endtask
task rec_data;
#1
mb.peek(s);
#2 mb.get(s);
#2 mb.get(i);
#1
mb.peek(s);
#2
void’(mb.try_g
et(s));
#1
void’(mb.try_g
et(i));
Example
Futurewiz
www.futurewiz.co.i
Result:
# s= and i=0 at time=0
# s=Hello and i=0 at
time=1 # s=Hello and i=7
at time=5 # s=Test and i=7
at time=7 # s=Test and i=3
at time=16
Example
Futurewiz
www.futurewiz.co.i
module test;
mailbox #(int)
mb;
int i;
initial
begin
mb=new(3)
;
//Parameterized
Mailbox
//bound
mailbox
$monitor(“i=%0d at %0d”, i ,
$time); fork gen_data;
rec_data;
join end
endmodul
e
Example
Futurewiz
www.futurewiz.co.i
task
gen_data;
mb.put(1);
#1 mb.put(7);
#1 mb.put(4);
#2 mb.put(3);
#2
void’(mb.try
_put(2));
#10
mb.put(5);
#2 mb.put(6);
task rec_data;
#1
mb.peek(i);
#5 mb.get(i);
#2 mb.get(i);
#2
void’(mb.try_
get(i));
#1 mb.get(i);
#2
void’(mb.try_
get(i));
Example
Futurewiz
www.futurewiz.co.i
Result:
# i=0 at time=0
# i=1 at time=1
# i=7 at time=8
# i=4 at
time=10 # i=3
at time=11 #
i=2 at time=13
# i=5 at
time=18
System Verilog
RANDOMIZATION
Why Randomize?
Futurewiz
www.futurewiz.co.i
⚫As designs grow it becomes more difficult to verify
their functionally through directed test cases.
⚫Directed test cases checks specific features of a
design and can only detect anticipated bugs.
⚫Verifying your design using this approach is a
time consuming process.
⚫Randomization helps us detecting bugs that we do
not expect in our design.
Comparison
Directed
o Verifies
specific
scenarios.
o Time
Consuming.
o Linear
progress.
Futurewiz
www.futurewiz.co.i
Random
o Broader Coverage.
o TB’s are easy to
write.
o Tests are redundant.
o Takes longer time
to achieve
functionality.
Constrained
Random
o Broad and Deep
o Tests are
more
productive
o Finds corner
cases
o Constrained
to
achieve
What to Randomize?
Futurewiz
www.futurewiz.co.i
⚫Device configuration
⚫Environment
configuration
⚫Primary input data
⚫Encapsulated input data
⚫Protocol exceptions
⚫Errors and violations
⚫Delays
⚫Test order
⚫Seed for the random
test
Verilog Constrained Randomization
Futurewiz
www.futurewiz.co.i
Random in range
Futurewiz
www.futurewiz.co.i
module test;
integer a, b,
c;
initial
repeat(20) begin
a=$random %
10;
b={$random} %
20;
c=$unsigned($random)
%15; range)
//-9 to 9 (Random
range)
//0 to 19 (Random
range)
//0 to 14 (Random
module test;
integer a, b,
c;
initial
repeat(20)
begin
a=10 +
{$random} %
6;
Futurewiz
www.futurewiz.co.i
//10 to
15
(positive
range)
b=-5 - {$random} % 6; //-5 to -10 (negative
range)
c =-5 + {$random} % 16; //-5 to 10 (mix range)
#2; end
endmodule
Random in range
Algorithms
• Positive Range:
• result= min + {$random} % (max – min + 1);
• Negative Range:
• result= -min - {$random} % (max – min + 1);
• Mix Range:
• result= -min + {$random} % (max + min + 1);
• //min is the magnitude of minimum number
• //max is the magnitude of maximum number
Futurewiz
www.futurewiz.co.i
module
test;
integer a;
initial
repeat(20
)
if
({$rando
m} % 2)
#2 a=10 + {$random} %
6; else Futurewiz
www.futurewiz.co.i
//10 to
15
// 3 to
7
Random between ranges
module test;
integer a,
count=0;
always if(count< 10) #2 count=count+1; else #2
count=0; initial repeat(20)
if (count<3)
Futurewiz
www.futurewiz.co.i
//1 to
9
// 11 to 18 Higher
weight
#2 a=1 + {$random} %
9; else
#2 a=11 + {$random} %
8;
endmodule
Weighted Random numbers
module test;
reg sign; reg [7:0] exp;
reg [22:0] mantisa; real
a;
initial repeat(20)
begin
sign=$random;
exp=$random;
mantisa=$random;
a=$bitstoshortreal({sign, exp,
mantisa}); #2; end Futurewiz
www.futurewiz.co.i
Real random numbers
while(index!=10)
begin
temp=$random;
begin: loop
for(i=0; i<index;
i=i+1)
if(rec[i]==temp)
disable loop;
rec[index]=temp;
index=index + 1;
num=temp; #2; end
Futurewiz
www.futurewiz.co.i
Generate 10 unique
random numbers
integer rec [0:9];
integer i, temp, num,
index=0;
initial begin
$monitor(“num=%0d”,
num);
Unique random numbers
Result
Futurewiz
www.futurewiz.co.i
# num=303379748
# num=-
1064739199 #
num=-2071669239
# num=-
1309649309 #
num=112818957
#
num=1189058957
# num=-
1295874971 #
num=-1992863214
# num=15983361
while(index!=10) begin
temp={$random} %
100;
begin: loop
for(i=0; i<index;
i=i+1)
if(rec[i]==temp)
disable loop;
rec[index]=temp;
index=index + 1;
rand=temp; #2; end
Futurewiz
www.futurewiz.co.i
Generate 10 unique
random numbers
between 0 to 99
integer rec [0:9];
integer i, temp, rand,
index=0;
Unique random numbers
Result
Futurewiz
www.futurewiz.co.i
#
num=48
#
num=97
#
num=57
#
num=87
#
num=57
#
num=25
#
⚫Verilog also offers few more randomization system
functions apart from $random. They can be
categorized as following:
o$dist_uniform (seed, start, end)
o$dist_normal (seed, mean,
standard_deviation) o$dist_exponential (seed,
mean) o$dist_poisson (seed, mean)
o$dist_chi_square (seed,
degree_of_freedom) o$dist_t (seed,
degree_of_freedom) o$dist_erlang (seed,
k_stage, mean)
Futurewiz
www.futurewiz.co.i
Other types
module test;
integer num1, num2, seed;
initial
repeat(20) begin
num1=$dist_uniform (seed, 5,
15);
num2=$dist_uniform (seed, -5,
10);
10
#2; end
endmodul
Futurewiz
www.futurewiz.co.i
//5 to
15
//-5 to
$dist_uniform
SV Constrained Randomization
Futurewiz
www.futurewiz.co.i
module test;
integer num1, num2,
seed;
initial
repeat(20) begin
#2 num1=$urandom
(seed);
Futurewiz
www.futurewiz.co.i
//Unsigned 32-
bit
//Random
Number
num2=$urando
m; end
endmodule
$urandom
module test;
integer num1, num2 ,
num3;
Futurewiz
www.futurewiz.co.i
initial
repeat(20) begin
#2 num1=$urandom_range(35,
20); num2=$urandom_range(9);
num3=$urandom_range(10,15);
end
endmodule
//35:max to
20:min
//9:max to 0:min
//10:min to
15:max
$urandom_range
Result
Futurewiz
www.futurewiz.co.i
# num1=27 num2=8
num3=10 # num1=32
num2=0 num3=11 #
num1=26 num2=0 num3=14
# num1=29 num2=0
num3=13 # num1=21
num2=6 num3=12 #
num1=25 num2=4 num3=10
# num1=20 num2=7
num3=12 # num1=23
num2=2 num3=12 #
num1=33 num2=2 num3=13
# num1=22 num2=1
num3=11 # num1=34
num2=8 num3=14 #
num1=24 num2=2 num3=15
⚫SV provides scope randomize function which is used
to randomize variables present in current scope.
⚫randomize() function can accept any number of
variables which have to be randomized as an
arguments.
⚫This function returns true if randomization was
successful else false.
⚫User can also provide inline constraints to control
range of Futurewiz
www.futurewiz.co.i
Randomize function
module test;
integer num1, num2;
initial
repeat(20) begin
if(randomize(num1,
num2))
num2
endmodul
e Futurewiz
www.futurewiz.co.i
//Randomize num1
and
$display(“Randomization
Successful”); else
$display(“Randomization Failed”); #2
; end
Randomize function
module
test;
integer
num;
initial
repeat(20)
begin
if(randomiz
e(num)
with
{num>10;
num<20;} )
endmodul
e Futurewiz
www.futurewiz.co.i
Randomize function with constraint
Result
Futurewiz
www.futurewiz.co.i
#
num=19
#
num=15
#
num=11
#
num=13
#
num=15
#
num=14
#
num=16
Randomize Object Properties
Futurewiz
www.futurewiz.co.i
⚫In SV properties (variables) inside a class can also
be randomized.
⚫Variables declared with rand and randc are only
considered for randomization.
⚫A class built-in randomize function is used to
randomized rand and randc variables.
⚫User can also specify constraint blocks to constrain
random
value generation.
rand vs randc
Futurewiz
www.futurewiz.co.i
⚫ Variables defined with rand keyword, distribute values
uniformly.
rand bit [1:0] num1;
num1: 3, 2 , 0, 3, 0, 1, 2, 1, 3
⚫ Variables defined with randc keyword, distribute values in a
cyclic fashion without any repetition within an iteration.
randc bit [1:0] num2;
num2
:
3, 2, 0, 1
0, 2, 1, 3
1, 3, 0, 2
program
test; sample
sm; initial
begin
sm=new;
repeat(20)
assert(sm.ra
ndomize())
Futurewiz
www.futurewiz.co.i
class sample;
rand int
num1; int
num2;
endclass
//assert checks randomization status
$display(“num1=%0d num2=%0d”, sm.num1,
sm.num2); end
endprogram
num1 is randomized num2 remains
untouched
Example1
Result
Futurewiz
www.futurewiz.co.i
# num1=-
1884196597
num2=
0
# num1=-326718039 num2=
0
# num1=1452745934 num2=0
# num1=-
2130312236
num2=
0
# num1=1572468983 num2=0
# num1=131041957 num2=0
# num1=1115460554 num2=0
# num1=-818992270 num2=
0
# num1=2000525113 num2=0
# num1=1547354947 num2=0
program
test; main
m; initial
begin
m=new;
repeat(20)
assert(m.ran
domize())
$display(m.sm.num
); end
endprogram
Futurewiz
www.futurewiz.co.i
class
sample;
rand bit[1:0]
num;
endclass
class
main;
rand
sample
sm; //rand
is must to
/
/
Example2
program
test; sample
sm; initial
begin
sm=new;
repeat(20)
assert(sm.ra
ndomize()
)
$display(sm.st.a)
; end
endprogramFuturewiz
www.futurewiz.co.i
class sample;
typedef struct { randc int
a;
bit [3:0] b;
} st_t;
rand st_t st;
//rand is must to
randomize
//int present inside
structure endclass
Example3
program
test; main
m; initial
begin
m=new;
repeat(20) begin
assert(m.randomize())
;
$display(m.sm1.num);
$display(m.sm2.num
); end
end
endprogram
Futurewiz
www.futurewiz.co.i
class sample;
rand bit[3:0]
num; endclass
class main;
rand sample
sm1; sample
sm2; function
new;
sm1=new;
sm2=new;
endfunction
endclass
Example4
Result
Futurewiz
www.futurewiz.co.i
# 14 # 0
# 4 # 0
# 9 # 0
# 6 # 0
# 5 # 0
# 15 # 0
# 4 # 0
# 13 # 0
# 1 # 0
# 8 # 0
# 9 # 0
# 14 # 0
Specifying Constraints
Futurewiz
www.futurewiz.co.i
class
sample1;
rand int num;
constraint c
{ num>10;
nu
m
<1
00
; }
endclass
class sample2;
class
sample3;
randc int
num; int Max,
Min;
constraint c1 { num>Min;
} constraint c2
{ num<Max; } endclass
class packet;
rand bit [7:0]
data;
int Max=50, Min=10;
constraint c1
{ data>Min;
data<Max;
}
endclass
program
test; packet Futurewiz
www.futurewiz.co.i
Example1
repeat(10)
assert(pkt.randomize(
))
$display(pkt.data);
pkt.Min=30;
pkt.Max=100;
repeat(10)
assert(pkt.randomize(
))
$display(pkt.data
); end
endprogram
Result
Futurewiz
www.futurewiz.co.i
# 22 # 72
# 22 # 53
# 29 # 66
# 27 # 79
# 46 # 68
# 43 # 69
# 33 # 78
# 43 # 95
# 46 # 65
# 36 # 34
class packet;
rand bit [7:0]
data;
constraint c2
{ data>50;
data<10; }
endclass
Futurewiz
www.futurewiz.co.i
endprogra
Example2
program
test; packet
pkt; initial
begin
pkt=new;
repeat(10)
if(pkt.rando
mize())
$display(“Randomizatio
n Success”);
else
$display(“Randomization
Result
Futurewiz
www.futurewiz.co.i
# Randomization
Fails #
Randomization Fails
# Randomization
Fails #
Randomization Fails
# Randomization
Fails #
Randomization Fails
# Randomization
Fails #
Randomization Fails
# Randomization
Fails #
Randomization Fails
⚫ Every class contains pre_randomize and post_randomize
functions which are evoked every time randomize
function is called.
⚫ When randomize function is called, it first evokes pre_randomize
and then randomization is done.
⚫ post_randomize function is only called if randomization was
successful.
⚫ pre_randomize and post_randomize functions can be written in a
class to offer user defined functionality before and after
randomization.
Futurewiz
www.futurewiz.co.i
pre_randomize and post_randomize
class packet;
rand bit [7:0] data;
function void
pre_randomize;
$display(“Pre-
Randomize”); endfunction
function void
post_randomize;
$display(“Post-
Randomize”); endfunction
endclass
Futurewiz
www.futurewiz.co.i
Example1
program
test; packet
pkt;
initial begin
pkt=new;
repeat(5)
begin
void'(pkt.rand
omize);
$display(pkt.data
); end
Result
Futurewiz
www.futurewiz.co.i
# Pre-Randomize
# Post-Randomize # 33
# Pre-Randomize
# Post-Randomize # 25
# Pre-Randomize
# Post-Randomize #
202
# Pre-Randomize
# Post-Randomize #
138 # Pre-Randomize
# Post-Randomize #
15
class A;
function void pre_randomize;
$display(“A: Pre-
Randomize”); endfunction
function void
post_randomize;
$display(“A: Post-
Randomize”); endfunction
endclass
Futurewiz
www.futurewiz.co.i
Example2
class B extends A;
function void pre_randomize;
$display(“B: Pre-
Randomize”); endfunction
function void
post_randomize;
$display(“B: Post-
Randomize”); endfunction
endclass
Example2
overridde
n
Futurewiz
www.futurewiz.co.i
program
test; B b1;
initial
begin
b1=new;
repeat(2)
void'(b1.randomize
); end
endprogram
Result
# B: Pre-
Randomiz
e # B:
Post-
Randomiz
e # B: Pre-
Randomiz
e # B:
Post-
Randomiz
e
Pre-Randomize and
⚫ Randomization nature of rand and randc variables can be turned
on/off dynamically.
⚫ rand_mode method is used to change randomization status of
rand and randc variable.
⚫ When used as a task, the argument determines the state of rand
and
randc variables.
⚫ When argument is 0 then randomization is disabled(turned-off),
when argument is 1 then randomization is enabled(turned-on).
Futurewiz
www.futurewiz.co.i
Controlling Randomization
⚫When used as a function, rand_mode returns the
current status of rand and randc variables.
⚫It returns 1 if randomization is on else it returns 0.
⚫Hierarchal reference of variables in an object can also
be
given to disable/enable specific rand and randc
variables.
⚫Randomization is enabled by default.
Futurewiz
www.futurewiz.co.i
Controlling Randomization
class packet;
rand bit [7:0]
data;
endclass
program
test; packet
pkt;
initial
begin
Futurewiz
www.futurewiz.co.i
Example1
•repeat(4) begin
void'(pkt.randomize)
;
•$display(pkt.data);
end pkt.rand_mode(0);
•//Disabling
Randomization repeat(3)
begin
void'(pkt.randomize)
•$display(pkt.data)
; end end
Result
Futurewiz
www.futurewiz.co.i
# 33
# 25
#
202
#
138
#
138
#
138
#
138
class packet;
rand bit [7:0]
data1;
rand int
data2;
endclass
Futurewiz
www.futurewiz.co.i
Example2
if(pkt.rand_mode()) //Check current
Status
$display(“Randomization on”);
else $display(“Randomization
off”); end
pkt.rand_mode(0);
void'(pkt.randomize
);
if(pkt.rand_mode())
$display(“Randomiz
ation on”);
else $display(“Randomization off”);
end endprogram
program test;
packet pkt;
initial begin
pkt=new;
repeat(10)
begin
void'(pkt.rando
mize);
class packet;
rand bit [7:0]
data1; rand byte
data2;
endclass
program
test; packet
pkt;
initial
begin
pkt=new; Futurewiz
www.futurewiz.co.i
Example3
repeat(10) if(pkt.randomize)
$display(pkt.data1,
pkt.data2);
pkt.data2.rand_mode(0);
//turn off for data2
repeat(10)
if(pkt.randomize)
$display(pkt.data1,
pkt.data2);
pkt.data2.rand_mode(1);
repeat(10) if(pkt.randomize)
$display(pkt.data1, pkt.data2);
end endprogram
Result
# 9 -34 Futurewiz
www.futurewiz.co.i
# 238 94
# 85 48
# 202 -92
# 29 38
# 155 48
# 225 -91
# 81 -66
# 232 -82
# 85 -112
# 141 -34
# 244 -34
# 32 -34
class packet;
rand bit [7:0]
data1;
byte data2;
endclass
program
test; packet
pkt;
initial
begin Futurewiz
www.futurewiz.co.i
Example4
repeat(10)
if(pkt.randomiz
e)
$display(pkt.data1,
pkt.data2); repeat(10)
if(pkt.randomize(data2))
//will only randomize data2
$display(pkt.data1,
pkt.data2); end
endprogram
Result
Futurewiz
www.futurewiz.co.i
# 238 0
# 85 0
# 202 0
# 29 0
# 155 0
# 225 0
# 141 75
# 141 115
# 141 -24
# 141 111
# 141 -119
class
packet; rand
int data; int
Max, Min;
constraint c1{ data> Min;
data<Max; } constraint c2 { Max>
Min; }
task set(int Min,
Max); this.Min=Min;
this.Max=Max;
endtask
endclass
Futurewiz
www.futurewiz.co.i
Example5
initial begin
packet
p1=new;
p1.set(5, 25);
repeat(5)
if(p1.randomiz
e)
$display(“Random value=%0d”,
p1.data); p1.set(35, 20);
repeat(5) if(p1.randomize)
$display(“Random value=%0d”,
p1.data); else $display(“Randomization
Failed”); end
Futurewiz
www.futurewiz.co.i
Example5
Result
Futurewiz
www.futurewiz.co.i
# Random
value=14 #
Random value=18
# Random
value=15 #
Random value=16
# Random
value=16
# Randomization
Failed #
Randomization Failed
# Randomization
Failed #
Randomization Failed
# Randomization
module
test; class
A;
rand bit [3:0]
data; endclass
A a1, a2;
Futurewiz
www.futurewiz.co.i
initial begin
a1=new;
//Random seed
initialized a2=new;
//Random seed initialized with next seed
value
Random Stability
repeat(5)
if(a1.randomiz
e)
$display("a1.data=
%0d",a1.data); repeat(5)
if(a2.randomize)
$display("a2.data=
%0d",a2.data);
end
endmodule
Result
Futurewiz
www.futurewiz.co.i
#
a1.data=12
# a1.data=7
#
a1.data=15
# a1.data=6
# a1.data=9
#
a2.data=13
#
a2.data=13
# a2.data=6
# a2.data=2
Random Stability
Futurewiz
www.futurewiz.co.i
module
test; class
A;
rand bit [3:0]
data; endclass
A a1, a2;
initial
begin
a1=new;
//Random seed
initialized a2=new;
//Random seed initialized with next seed
value
repeat(5)
if(a2.randomiz
e)
$display("a2.da
ta=
%0d",a2.data
);
repeat(5)
if(a1.randomiz
e)
$display("a1.da
ta=
%0d",a1.data
Result
Futurewiz
www.futurewiz.co.i
#
a2.data=13
#
a2.data=13
# a2.data=6
# a2.data=2
#
a2.data=15
#
a1.data=12
# a1.data=7
#
a1.data=15
module
test; class
A;
rand bit [3:0] data;
function new(int
seed);
srandom(seed);
//set a particular
seed endfunction
endclass
A a1, a2;
Futurewiz
www.futurewiz.co.i
Random Stability
initial begin
a1=new(3);
a2=new(3); repeat(5)
if(a1.randomize)
$display("a1.data=
%0d",a1.data); repeat(5)
if(a2.randomize)
$display("a2.data=
%0d",a2.data); end
endmodule
Result
Futurewiz
www.futurewiz.co.i
# a1.data=5
# a1.data=7
#
a1.data=12
#
a1.data=13
# a1.data=5
# a2.data=5
# a2.data=7
#
a2.data=12
#
a2.data=13
Relation in Constraints
Futurewiz
www.futurewiz.co.i
⚫ Each constraint expression should only contain 1 relation
operator.
< <= == > >= -> <-> || ! &&
⚫ lo < med is evaluated. Results in 0 or
1
⚫ hi > (0 or 1) is evaluated.
class bad_cons;
rand bit [7:0] low, med, hi;
constraint bad {low < med <
hi;} endclass
low=20, med=224,
hi=164
low=114, med=39,
hi=189
low=186, med=148,
hi=161 low=214,
med=223,
hi=201
⚫User can use == to constraint random value to a
particular expression. Using = will give compilation
error.
class packet;
rand int length, data, address;
constraint len { length==address *
5}; endclass
Futurewiz
www.futurewiz.co.i
constraint good{ low <
med;
med < hi; }
low=20, med=40,
hi=100 low=10,
med=25, hi=90
Relation in Constraints
Set Membership
Futurewiz
www.futurewiz.co.i
⚫User can use inside operator to set membership
in a constraint block.
⚫Example: To limit address in range from 1 to 5, 7 to 11
and to a set of values 15, 18, 25.
class packet;
rand int
address;
constraint limit
{address inside
{ [1:5],
Set Membership
Futurewiz
www.futurewiz.co.i
⚫ A ! Operator can be used to exclude set of
values class packet;
rand int address;
constraint limit { !(address inside { 6,
[12:14]} ) ;} endclass
⚫ Using arrays to set membership.
class packet;
int arr [ ]= `{ 5, 7, 11, 13, 19};
rand int address;
constraint limit { address inside { arr }; }
endclass
Set Membership
• class packet; rand
int data;
• constraint limit { ( (data==5) || (data==7) || (data==9) );} endclass
• There is a better way of providing such
• constraints:
• class packet;
• rand int data;
• constraint limit { data inside { 5, 7, 9}; } endclass
Futurewiz
www.futurewiz.co.i
Weighted Distribution
Futurewiz
www.futurewiz.co.i
⚫User can provide weights for random numbers to
obtain non-uniform distribution.
⚫:= operator is used to assign same weight to all the
values.
⚫:/ operator is used to distribute weight among all
the values.
⚫dist operator is used to specify distribution.
⚫Weighted distribution does not work on randc
variables.
⚫Example
:
constraint con { src dist { 0:=40, [1:3] :=60
};
dst dist { 0:/40 , [1:3] :/60 }; }
class
packet; rand
int data;
constraint con { data dist { 0:=40, [1:4] :=60,
[6:7]:=20 }; } endclass
//Total weight= 40 + 60 + 60 + 60 + 60 + 20 + 20=320
Futurewiz
www.futurewiz.co.i
Example1
data=3
weight=60/320=18.75%
data=4
weight=60/320=18.75%
data=6 weight=20/320=6.25%
data=7 weight=20/320=6.25%
data=0 weight=40/320=12.5%
data=1
weight=60/320=18.75%
data=2
weight=60/320=18.75%
class
packet; rand
int data;
constraint con { data dist { 0:/20, [1:3] :/60, [6:7]:/20
}; } endclass
//Total weight= 20 + 60 + 20=100
Futurewiz
www.futurewiz.co.i
Example2
data=3
weight=20/100=20%
data=6
weight=10/100=10%
data=7
weight=10/100=10%
data=0
weight=20/100=20%
data=1
weight=20/100=20%
data=2
weight=20/100=20%
typedef enum {Red, Green, Blue}
color; class temp;
rand color col;
int redw=5, greenw=3, bluew=4;
constraint weight { col dist
{ Red:=redw,
Green:=green
w,
Blue:=bluew};
}
endclass Futurewiz
www.futurewiz.co.i
Example3
Bidirectional Constraints
Futurewiz
www.futurewiz.co.i
⚫Constraints are not procedural but declarative.
⚫All constraints should be active at same time.
rand bit [15:0] a, b,
c; constraint cp { a <
c;
b == a;
c < 10;
b > 5;
}
⚫Even though there is no direct constraint on lower
value of c, constraint on b restricts choices.
Solution a b c
S1 6 6 7
S2 6 6 8
S3 6 6 9
S4 7 7 8
S5 7 7 9
S6 8 8 9
Implication Constraints
Futurewiz
www.futurewiz.co.i
constraint mode_c { if (mode == small)
len < 10;
else if (mode ==
large) len > 100; }
Is equivalent to
constraint mode_c{ (mode == small) -> len < 10;
(mode == large) -> len > 100; }
⚫ If mode is small that implies length should be
less than 10.
⚫ If mode is large that implies length should be
more than 100.
⚫ Implication helps in creating case like blocks.
Efficient Constraints
Futurewiz
www.futurewiz.co.i
rand bit [31:0] addr;
constraint slow { addr % 4096 inside { [0:20],
[4075:4095] };
}
rand bit [31:0] addr;
constraint fast { addr [11:0] inside { [0:20], [4075:4095]
};
}
⚫In slow, first addr is evaluated and then % is
performed and then constraints are applied. In fast,
constraints are
directly applied on selected bits hence faster and
Solution Probabilities
Futurewiz
www.futurewiz.co.i
Solution x y
Probabilit
y
S1 0 0 1/8
S2 0 1 1/8
S3 0 2 1/8
S4 0 3 1/8
S5 1 0 1/8
S6 1 1 1/8
S7 1 2 1/8
S8 1 3 1/8
class
Unconstrained;
rand bit x;
// 0 or 1
rand bit [1:0] y;
// 0, 1, 2, or 3
endclass
Solution Probabilities
Futurewiz
www.futurewiz.co.i
Solution x y
Probabilit
y
S1 0 0 1/2
S2 0 1 0
S3 0 2 0
S4 0 3 0
S5 1 0 1/8
S6 1 1 1/8
S7 1 2 1/8
S8 1 3 1/8
class
Implication1;
rand bit x;
// 0 or 1
rand bit [1:0] y;
// 0, 1, 2, or 3
constraint c
{ (x==0) -> (y==0);
}
endclass
Solution Probabilities
Futurewiz
www.futurewiz.co.i
Solution x y
Probabilit
y
S1 0 0 0
S2 0 1 0
S3 0 2 0
S4 0 3 0
S5 1 0 0
S6 1 1 1/3
S7 1 2 1/3
S8 1 3 1/3
class
Implication2;
rand bit x;
// 0 or 1
rand bit [1:0] y;
// 0, 1, 2, or
3 constraint
c { y>0;
(x==0) ->
(y==0); }
endclass
Solution x y
Probabilit
y
S1 0 0 1/2
S2 0 1 0
S3 0 2 0
S4 0 3 0
S5 1 0 1/8
S6 1 1 1/8
S7 1 2 1/8
S8 1 3 1/8
Futurewiz
Solve before
www.futurewiz.co.i
n
⚫A solve before keyword can be used to specify
order in which random variables would be solved.
class
solvebefore;
rand bit x;
// 0 or 1
rand bit [1:0] y;
// 0, 1, 2, or 3
constraint c
{ (x==0) ->
(y==0);
solve x before
y; }
Solve before
Futurewiz
www.futurewiz.co.i
Solution x y
Probabilit
y
S1 0 0 1/8
S2 0 1 0
S3 0 2 0
S4 0 3 0
S5 1 0 1/8
S6 1 1 1/4
S7 1 2 1/4
S8 1 3 1/4
class
solvebefore;
rand bit x;
// 0 or 1
rand bit [1:0] y;
// 0, 1, 2, or 3
constraint c
{ (x==0) ->
(y==0);
solve y before
x; }
endclass
⚫ Constraints can be turned on/off during runtime.
⚫ constraint_mode() is used to achieve this capability.
⚫ When used with handle.constraint, this method controls a
single constraint.
⚫ When used with just handle, it controls all constraints for an
object.
⚫ To turn off constraint, 0 is passed as an argument to
constraint_mode and to turn on, 1 is passed as an
argument.
Futurewiz
www.futurewiz.co.i
Controlling Constraints
class Packet;
rand int
length;
constraint c_short { length inside { [1:32] }; }
constraint c_long { length inside
{ [1000:1023]};
}
endclass
Futurewiz
www.futurewiz.co.i
Example
Example
Futurewiz
www.futurewiz.co.i
Packet p;
initial
begin p =
new;
// Create a long packet by disabling short
constraint p.c_short.constraint_mode(0);
assert (p.randomize());
// Create a short packet by disabling all
constraints
// then enabling only the short
constraint p.constraint_mode(0);
p.c_short.constraint_mode(1);
assert
(p.randomize()); end
Inline Constraints
Futurewiz
www.futurewiz.co.i
⚫New constraints can be added to existing constraints
while calling randomize function using randomize with.
⚫constraint_mode can be used disable any
conflicting constraints.
class Transaction;
rand bit [31:0] addr, data;
constraint c1 { addr inside { [0:100],
[1000:2000] }; } endclass
Inline Constraints
Futurewiz
www.futurewiz.co.i
// addr is 50-100, 1000-1500, data <
10
Transaction
t; initial
begin
t =
new();
repeat(5)
assert(t.randomize() with { addr >= 50;
addr <= 1500;
data < 10;} );
repeat(5) // force addr to a specific value, data >
10 assert(t.randomize() with { addr == 2000;
data > 10; } );
end
Constraint in Inheritance
Futurewiz
www.futurewiz.co.i
⚫Additional constraints can be provided in a subclass
class(child class). Child class object has to fulfill both
the constraints (parent and child).
class base;
rand int
data;
constraint
limit1
{ data> 0;
d
a
t
class child extends base;
constraint limit2 { data >
50;
}
endclass
Child: 50 < data <
100
Example2
Futurewiz
www.futurewiz.co.i
class base;
rand int data;
constraint limit1 { data>
0;
data<
100;
}
endclass
class child extends
base;
constraint limit2 { data
== 50;
}
endclass
Parent: 0 < data <
100
Child:
data=50
Example3
Futurewiz
www.futurewiz.co.i
class base;
rand int data;
constraint limit1 { data>
40;
data< 50;
}
endclass
class child extends base;
constraint limit2 { data >
10;
data< 30;
}
endclass
Parent: 40 < data < 50 Child: 10 < data <
30
Randomization Fails because both constraints are not
satisfied
Example 4
Futurewiz
www.futurewiz.co.i
class base;
rand int
data;
constraint
limit1
{ data> 40;
d
a
t
a
<
5
class child extends
base; rand int data;
constraint limit2 { data
> 10;
data<
30;
}
endclass
Parent: 40 < data < 50 Child: 10 < data < 30
Parent data is different as compared to child data. Data
Overridden
Constraint in Inheritance
Futurewiz
www.futurewiz.co.i
⚫Constraints are overridden in child class if they are
defined with same name as that present in parent
class.
class base;
rand int
data;
constraint limit { data>
20;
data< 40; }
endclass
class child extends base;
constraint limit { data >
50;
data < 90; }
endclass
Parent: 20 < data < 40 Child: 50 < data <
90
Constraints are overridden
randcase
Futurewiz
www.futurewiz.co.i
⚫A randcase keyword can be used to make a
weighted choice between several actions.
initial
begin int
len;
repeat(20)
begin randcase
// 10%: 0 to
2
// 80%: 3 to 5
// 10%: 6 to 7
1: len = $urandom_range(0,
2);
8: len = $urandom_range(3,
5);
1: len = $urandom_range(6,
7); endcase
$display("len=%0d", len); end
end
randsequence
Futurewiz
www.futurewiz.co.i
⚫The random sequence generator is useful for
randomly
generating structured sequences of stimulus.
⚫randsequence is composed of one or more
productions.
⚫Each production contains a name and one or
more production list.
⚫Production list contains one or more
production_item.
Example1
Futurewiz
www.futurewiz.co.i
module
rand_sequence1(); initial
begin
repeat(5) begin //main is production
//main contains one production
list
//one two three are production
items
randsequence( main
) main : one two
three ; one :
{$write("one");};
two :
{$write("two");};
three:
{$display("three");};
endsequence
en
d
en
d
en
dm
od
Result
Futurewiz
www.futurewiz.co.i
# one two
three # one
two three #
one two three
# one two
three # one
two three
Example2
Futurewiz
www.futurewiz.co.i
//main contains three production
list
//one two three are production list
//one list will be chosen randomly
module
rand_sequence2(); initial
begin
repeat(7) begin
randsequence( main )
main : one| two |
three ; one :
{$display("one"); };
two :
{$display("two"); };
three: {$display("three");
}; endsequence
en
d
en
d
endmodule :
rand_sequence2
Result
Futurewiz
www.futurewiz.co.i
# one
# one
# one
# one
#
three
# one
# two
Example3
endmodule :
rand_sequence3
Futurewiz
www.futurewiz.co.i
module
rand_sequence3(); initial
begin
repeat(50) begin
randsequence( main
)
main : one:=5 | two:=2 | three:=3 ; //production
list with weights
one : {$display("one");};
two : {$display("two");};
three: {$display("three");};
endsequenc
e end
end
Example4
Futurewiz
www.futurewiz.co.i
module rand_sequence4();
int one_1, two_2, three_3; bit
on; initial begin
repeat(100) begin
randsequence( main
) main : one three;
one : if(on) incr_one else
incr_two; incr_one : {one_1 ++;
on=~on;}; incr_two : {two_2 ++; };
three: {three_3++;};
endsequence end end
endmodule :
rand_sequence4
Example5
Futurewiz
www.futurewiz.co.i
module rand_sequence5();
initial for (int i = 0 ; i < 10 ; i+
+) randsequence( main )
main : case(i %3)
0 : zero;
1, 2 :
non_zero;
default : def;
endcase
zero : {$display("zero");};
non_zero :
{$display("non_zero");}; def :
{$display("default");};
endsequence
endmodule : rand_sequence5
System Verilog
PROGRAM BLOCK & INTERFACE
Program Block
Futurewiz
www.futurewiz.co.i
⚫Verilog module works well for design but when used
for Test benches may lead to race-around condition
between design and Test bench.
⚫System Verilog adds program block which is used
meant for writing Test Bench.
⚫program and endprogram keywords are used to
define a program block.
Program Block
Futurewiz
www.futurewiz.co.i
⚫program block has following features:
o They separate test benches from design unit.
o Statements are executed in Reactive Region.
o always blocks are not allowed in program block.
o They can be instantiated inside other modules.
o Instance of module or program block is not allowed
inside program block.
o They have access to variables present inside a
module where they are instantiated but vice
versa is not true.
o Implicit system task $exit is called when program
block terminates.
Program Block Region
Inactive
NBA
Observed
Re-Active
Re-Inactive
Postponed Re-NBA
Preponed Active
From Current
Time Slot
To Next
Time
Slot
Program
Block Runs
Here
Futurewiz
www.futurewiz.co.i
Test Bench
runs once all
design related
activities are
over.
Example1
Futurewiz
www.futurewiz.co.i
module tff (q, clk,
t); input clk, t;
output reg q=0;
always @ (posedge
clk) if(t) q<= ~ q;
endmodule
module tb;
reg clk=0,
t=1; wire q=0;
always #5
clk=~clk; tff u0 (q,
clk, t);
always @
(posedge clk)
$display($time,
“q=%d”, q);
Example1
Futurewiz
www.futurewiz.co.i
Result:
5 q= 0
15 q= 1
25 q= 0
35 q= 1
45 q= 0
55 q= 1
Example2
Futurewiz
www.futurewiz.co.i
module tff (q, clk, t);
input clk, t;
output reg
q=0;
always @ (posedge
clk) if(t) q<= ~ q;
endmodule
initial
allowe
d
begin
program tb (input
clk);
//always not
forever @ (posedge
clk)
$display($time, “q=%d”,
q); end
initial
t=1;
endprogra
m
Example2
Futurewiz
www.futurewiz.co.i
module
top; reg
clk=0, t;
wire q;
always #5
clk=~clk;
tff u0 (q, clk,
t); tb u1 (clk);
q
//program has access to t
and
endmodul
e
Example2
Futurewiz
www.futurewiz.co.i
Result:
5 q= 1
15 q= 0
25 q= 1
35 q= 0
45 q= 1
55 q= 0
Example3
Futurewiz
www.futurewiz.co.i
program
tb; int a;
initial $monitor(“result is
%d”, a);
initial begin
#3 a= a + 2;
#4 a= a + 3;
end
endprogram
Result :
result is 2 a=5
$monitor does not
execute
for a=5 because of
implicit
$exit
Example4
Futurewiz
www.futurewiz.co.i
program
tb; int a;
initial
$monitor(“
result is
%d”, a);
initial
begin
#3 a= a +
2;
#4 a= a +
3;
#1 ;
end
endprogra
m
Result :
result is
2
result is
5
Interface
Futurewiz
www.futurewiz.co.i
⚫ Interface is used to encapsulate communication between design
blocks, and between design and verification blocks.
⚫ Encapsulating communication between blocks facilitates design
reuse. Interfaces can be accessed through ports as a single item.
⚫ Signals can be added to and remove easily from an interface
without modifying any port list.
⚫ Interface can contain the connectivity, synchronization, and
optionally, the functionality of the communication between
two or more blocks.
Design
Futurewiz
www.futurewiz.co.i
module adder (input bit clk,
input logic [3:0] a, b,
output logic [4:0]
sum);
always @ (posedge
clk) sum= a + b;
endmodule
Test Bench
Futurewiz
www.futurewiz.co.i
program tb (input bit clk,
input logic [4:0] sum,
output logic [3:0] a, b);
initia
l
begi
n
$monitor (“a=%0d b=%0d sum=%0d”, a, b,
sum); forever begin a=$random; b=$random;
#10; end end
endprogram
Top Level
Futurewiz
www.futurewiz.co.i
module top
(); bit clk=0;
logic [3:0] a,
b; logic [4:0]
sum;
always #5
clk=~clk;
adder a0
(.*); have
tb t0 (.*);
endmodule
//connect variables to ports
that
// same name and same data
type
Now in case you have to add
one more input c, you have to
define c at three place adder,
tb and top.
Defining Interface
Futurewiz
www.futurewiz.co.i
interface intf (input
bit clk);
logic [3:0] a, b;
logic [4:0]
sum;
endinterface :
inf
Design
Futurewiz
www.futurewiz.co.i
module adder (intf
inf);
always @
(posedge inf.clk)
inf.sum= inf.a +
inf.b;
endmodule :
adder
Test Bench
Futurewiz
www.futurewiz.co.i
program tb (inft inf);
initial begin
$monitor (“a=%0d b=%0d sum=%0d”, inf.a,
inf.b, inf.sum);
forever begin
inf.a=$rando
m;
inf.b=$rando
m; #10; end
end
endprogram :
Top Level
Futurewiz
www.futurewiz.co.i
module top
(); bit clk=0;
always #5
clk=~clk;
intf inf(clk);
adder a0
(inf); tb t0
(inf);
//inf is interface
instance
endmodul
e
Modport
Futurewiz
www.futurewiz.co.i
⚫modport construct is to used to provide
direction information for module ports.
interface intf (input bit clk);
logic [3:0] a,
b; logic [4:0]
sum;
//incase of
inout port use
wire
modport DUT (input clk, a, b, output
sum); modport TB (input clk, sum,
Design
Futurewiz
www.futurewiz.co.i
module adder (intf.DUT
inf);
always @ (posedge
inf.clk) inf.sum= inf.a +
inf.b;
endmodule : adder
Test Bench
Futurewiz
www.futurewiz.co.i
program tb (intf.TB inf);
initial begin
$monitor (“a=%0d b=%0d sum=%0d”, inf.a,
inf.b, inf.sum);
forever begin
inf.a=$rando
m;
inf.b=$rando
m; #10; end
end
endprogram :
Top Level
Futurewiz
www.futurewiz.co.i
module top
(); bit clk=0;
always #5
clk=~clk
;
intf i0 (.*);
adder a0
(.*);
tb t0 (.*);
endmodu
Clocking Block
Futurewiz
www.futurewiz.co.i
⚫Clocking block construct identifies clock signals and
captures the timing and synchronization
requirements of the blocks being modeled.
⚫Clocking block assembles signals that are
synchronous to a particular clock and makes their
timing explicit.
⚫Clocking block separates the timing and
synchronization details from the structural,
functional, and procedural elements of a test bench.
Clocking Block
Futurewiz
www.futurewiz.co.i
⚫In case of synchronous circuits, input should be
sampled just before the clock and output should be
driven just after the clock.
⚫So from test bench point of view, design outputs
should be sampled just before the clock and design
inputs should be driven just after the clock.
⚫By default design outputs are sampled at #1step
(Prepone Region) and design inputs are driven at #0
(Inactive /Re- Inactive Region).
Clocking Block
endinterfac
e Futurewiz
www.futurewiz.co.i
interface intf(input bit clk);
…………
modport TB (input clk, clocking
cb);
clocking cb @ (posedge
clk); edge
input sum;
output a, b;
endclocking :
cb
…………
//specifying active
clock
//sampled in prepone
region
//driven in inactive region
//Directions w.r.t Test
Bench
Clocking Block
Output of Test
Bench
Clk
en
DUT Futurewiz
www.futurewiz.co.i
en
Output of Clocking Block / Input
to
Clocking Block
Output of DUT/ Input to
Clocking Block
Clk
coun
t
coun
t
1
Futurewiz
www.futurewiz.co.i
2 3 4 5
6 7
6
0 1 2 3
4
Input to Test Bench
5
Clocking Block
Futurewiz
www.futurewiz.co.i
……………………… clocking cb
@ (posedge clk);
default input #3ns output
#2ns;
//specifying active clock
edge
//Specifying user default for sampling and
driving
input sum,
reset; output a,
b; endclocking :
cb
//sampled 3ns before active clock
edge
//driven 2ns after active clock edge
…………………………
Clocking Block
Futurewiz
www.futurewiz.co.i
……………………… clocking cb
@ (posedge clk);
default input #3ns output
#2ns;
//specifying active clock
edge
//Specifying user default for sampling and
driving
input sum;
output a,
b;
//sampled 3ns before active clock
edge
//driven 2ns after active clock edge
input negedge reset; //Overriding default sampling for
reset endclocking : cb
…………………………
Interface
Futurewiz
www.futurewiz.co.i
interface intf(input bit
clk); logic [3:0] count;
logic en;
modport DUT (input clk, en, output count);
//DUT modport TB (input clk,
clocking cb); //Test
Bench
clocking cb @ (posedge
clk); input count;
output en;
endclockin
g
endinterfac
e
//Clocking
Block
Design
Futurewiz
www.futurewiz.co.i
module counter (intf.DUT
inf);
always @ (posedge
inf.clk) if(inf.en)
inf.count+=1;
endmodule : counter
Test Bench
Futurewiz
www.futurewiz.co.i
program tb (intf.TB
inf);
initial begin
@inf.cb;
#3 inf.cb.en<=1;
##8
inf.cb.en<=0;
repeat(2)
@inf.cb;
inf.cb.en<=1;
//continue on active edge in
cb
// use NBA for signals in cb
//wait for 8 active edges in cb
//wait for 2 active edges in
cb
wait (inf.cb.count==3) inf.cb.en<=0; //wait for count to
become 3 end
endprogram : tb
Parameterized Interface
Futurewiz
www.futurewiz.co.i
interface intf #(size=3, type typ=logic) (input bit
clk); typ [size-1:0] count;
typ en;
modport DUT (input clk, en, output count);
//DUT modport TB (input clk, count, output en);
//Test Bench
endinterface
Virtual Interface
Futurewiz
www.futurewiz.co.i
⚫ A virtual interface is a variable that represents an interface
instance.
This interface is not use to represent physical connections.
⚫ Virtual interface variables can be passed as arguments to tasks,
and functions.
⚫ Tasks and functions can modify variables present in a virtual
interface which has the same effect as accessing physical
interface.
⚫ A virtual interface can be declared as class property, should be
initialize before usage.
Virtual Interface
Futurewiz
www.futurewiz.co.i
interface intf (input bit
clk); logic req, gnt;
always @(posedge
clk); interface
if(req) begin
repeat(2) @(posedge
clk); gnt<=1; end
else
gnt<=0;
endinterfac
e
//functionality
inside
Virtual Interface
endtas
k
Futurewiz
www.futurewiz.co.i
module
test; bit
clk=0;
always #5
clk=~clk; intf
inf(clk);
initia
l
fork
gen_
req(i
nf);
task gen_req(virtual intf a);
@(posedge a.clk) a.req<=1;
@(posedge a.clk) a.req<=0;
repeat (5) @(posedge
a.clk);
a.req<=1;
@(posedge a.clk) a.req<=0;
endtask
task rec_gnt(virtual intf b);
forever begin
@(posedge
b.gnt)
$display($time, “
Virtual Interface
Futurewiz
www.futurewiz.co.i
class test;
virtual intf
t1 ;
function new(virtual intf
t2); t1=t2; //initializing
virtual
//interface
endfunction
//task
gen_req;
//task
rec_gnt;
endclas
s
module
top; bit
clk=0;
always #5
clk=~clk; intf
inf(clk);
initial begin
test c1= new(inf);
fork
c1.gen_req
;
c1.rec_gnt;
System Verilog
PROCESSES
final block
en
d
Futurewiz
www.futurewiz.co.i
⚫final block is a procedural statement that occurs at the
end of simulation.
⚫Delays are not allowed inside final block.
⚫Final block can only occur once during simulation.
⚫$finish can be used to trigger final block.
final
begi
n
$dis
play(
“Sim
Block Statements
Futurewiz
www.futurewiz.co.i
⚫Block statements are used to group procedural
statements together.
⚫There are two types of blocks :
o Sequential blocks (begin - end)
o Parallel blocks (fork - join)
⚫System Verilog introduces three types of Parallel
blocks:
o fork – join
o fork – join_any
o fork – join_none
fork - join
Futurewiz
www.futurewiz.co.i
⚫In fork-join, the process executing the fork
statement is blocked until the termination of all
forked processes.
module test;
initial begin $display(“Before
Fork”); fork
begin #3 $display(“#3 occurs at %0d”, $time);
end begin #6 $display(“#6 occurs at %0d”,
$time); end begin #8 $display(“#8 occurs at
%0d”, $time); end begin #5 $display(“#5 occurs
at %0d”, $time); end join
$display(“Out of Fork at %0d”, $time);
end endmodule
fork - join
Futurewiz
www.futurewiz.co.i
Result :
Before Fork
#3 occurs at
3
#5 occurs at
5
#6 occurs at
6
#8 occurs at 8
Out of Fork at
8
fork – join_any
Futurewiz
www.futurewiz.co.i
⚫In fork-join_any, the process executing the fork
statement is blocked until any one of the processes
spawned by fork
completes
.
module test;
initial begin $display(“Before
Fork”); fork
begin #3 $display(“#3 occurs at %0d”, $time);
end begin #6 $display(“#6 occurs at %0d”,
$time); end begin #8 $display(“#8 occurs at
%0d”, $time); end begin #5 $display(“#5 occurs
at %0d”, $time); end join _any
$display(“Out of Fork at %0d”, $time);
end endmodule
fork – join_any
Futurewiz
www.futurewiz.co.i
Result :
Before Fork
#3 occurs at
3
Out of Fork at
3 #5 occurs at
5
#6 occurs at 6
#8 occurs at 8
fork – join_none
Futurewiz
www.futurewiz.co.i
⚫In fork-join_none, the process executing the fork
statement continues to execute with all processes
spawned by fork.
module test;
initial begin $display(“Before
Fork”); fork
begin #3 $display(“#3 occurs at %0d”, $time);
end begin #6 $display(“#6 occurs at %0d”,
$time); end begin #8 $display(“#8 occurs at
%0d”, $time); end begin #5 $display(“#5 occurs
at %0d”, $time); end join_none
$display(“Out of Fork at %0d”, $time);
end endmodule
fork – join_none
Futurewiz
www.futurewiz.co.i
Result :
Before Fork
Out of Fork at
0 #3 occurs at
3
#5 occurs at 5
#6 occurs at 6
#8 occurs at 8
wait fork
Futurewiz
www.futurewiz.co.i
program test;
initial begin $display(“Before
Fork”); fork
begin #3 $display(“#3 occurs at %0d”, $time);
end begin #6 $display(“#6 occurs at %0d”,
$time); end begin #8 $display(“#8 occurs at
%0d”, $time); end begin #5 $display(“#5 occurs
at %0d”, $time); end join_none
$display(“Out of Fork at %0d”, $time); end
endprogram
program block exits simulation once it reaches end of
initial block
wait fork
Futurewiz
www.futurewiz.co.i
Result :
Before
Fork
Out of
Fork at 0
program test;
initial begin $display(“Before Fork”);
fork
begin #3 $display(“#3 occurs at %0d”, $time);
end begin #6 $display(“#6 occurs at %0d”,
$time); end begin #8 $display(“#8 occurs at
%0d”, $time); end begin #5 $display(“#5 occurs
at %0d”, $time); end join_none
$display(“Out of Fork at %0d”,
$time); wait fork; end
endprogram
Waits till all forked processed are
completed
Futurewiz
www.futurewiz.co.i
n
wait fork
wait fork
Futurewiz
www.futurewiz.co.i
Result :
Before
Fork
Out of Fork at
0 #3 occurs at
3
#5 occurs at 5
#6 occurs at 6
#8 occurs at 8
disable fork
Futurewiz
www.futurewiz.co.i
module test;
initial begin $display(“Before Fork”);
fork
begin #3 $display(“#3 occurs at %0d”, $time);
end begin #6 $display(“#6 occurs at %0d”,
$time); end begin #8 $display(“#8 occurs at
%0d”, $time); end begin #5 $display(“#5 occurs
at %0d”, $time); end join_any
$display(“Out of Fork at %0d”,
$time); disable fork; end
endmodule
Disable fork kills all forked
processes
disable fork
Futurewiz
www.futurewiz.co.i
Result :
Before Fork
#3 occurs at
3
Out of Fork
at 3
Conditional Event Control
Futurewiz
www.futurewiz.co.i
⚫@ event control can have an iff qualifier.
⚫event expression only triggers if the expression after
the iff
is true.
always @(a iff
en==1) begin
y<= a;
end
always @(posedge clk iff
en)
begin
y<=din
; end
Both the event expression (@a and (@posedge
clk))
occurs only if en==1
Sequence Event Control
Futurewiz
www.futurewiz.co.i
⚫A sequence instance can be used in event expressions
to control the execution of procedural statements
based on the successful match of the sequence.
sequence abc;
@ (posedge clk) a ##1 b ##1
c; endsequence
always @(abc)
$display(“event occurred on
a, b and c in order”);
Named Events
Futurewiz
www.futurewiz.co.i
⚫System Verilog allows used to define events and
trigger them.
⚫There are two ways to trigger an event
o Blocking (->)
o Non-Blocking(->>)
⚫There are two ways to wait for an event
o @ (event_name)
o wait(even_name.triggered)
Example1
Futurewiz
www.futurewiz.co.i
event
myevent; int
count=0;
//User defined
event
initia
l
begi
n
-> myevent;
#3 ->
myevent; end
//Triggering
event
always
@(myevent)
count+=1;
//waiting for
event
Result :
count=
2
Example2
Futurewiz
www.futurewiz.co.i
event
myevent;
event
int count=0;
//User
defined
initia
l
begi
n
-> myevent;
@(myevent
) count+=1;
//Triggering
event
//waiting for
event
end
while using @, waiting should start before
event is
triggered
Result :
count=
0
Example3
Futurewiz
www.futurewiz.co.i
event
myevent;
event
int count=0;
//User
defined
initia
l
begi
n
@(m
yeve
nt)
->
myevent;
count+=1;
//waiting for
event
//Triggering
event
end
@ is waiting for event but event is never
triggered.
Result :
count=
0
Example4
Futurewiz
www.futurewiz.co.i
event
myevent; int
count=0;
//User defined
event
initia
l
begi
n
-
>>myevent;
@(myevent)
count+=1;
end
//Triggering event in NBA
region
//waiting for event
Result :
count=
1
Event is scheduled to triggered in NBA region
because of which waiting starts before triggering and
count increments
Example5
Futurewiz
www.futurewiz.co.i
event
myevent; int
count=0;
//User defined
event
initia
l
fork
->myevent;
@(myevent
) count+=1;
join
//Triggering
event
//waiting for
event
count value depends upon which statement is
executed
first result varies from simulator to simulator.
Example6
Futurewiz
www.futurewiz.co.i
event
myevent; int
count=0;
//User defined
event
initia
l
begi
n
-
>my
even
t;
wait
(myevent.triggered)
count+=1;
//Triggering
event
//waiting for
event
When using .triggered, waiting should start before
or at
same time when event is triggered.
Result :
count=
1
Example7
Futurewiz
www.futurewiz.co.i
event
myevent; int
count=0;
//User defined
event
initia
l
fork
->myevent;
wait(myevent.triggere
d) count+=1;
join
//Triggering
event
//waiting for
event
Result :
count=
1
always_comb
Futurewiz
www.futurewiz.co.i
⚫ System Verilog provides always_comb procedure for
modeling combinational logic behavior.
always_comb
c= a & b;
⚫ There is an inferred sensitivity list.
⚫ The variables written on the left-hand side of assignments
shall not be
written to by any other process.
⚫ The procedure is automatically triggered once at time zero,
after all initial and always procedures.
⚫ Software tools will perform additional check to warn if
behavior within
always_comb does not match a combinational logic.
always_latch
Futurewiz
www.futurewiz.co.i
⚫System Verilog provides always_latch procedure
for modeling latched logic behavior.
always_latc
h if(en) b=a;
⚫This construct is identical to always_comb, except that
the tools will perform additionsal check to warn if
behavior does not match a latch logic.
always_ff
Futurewiz
www.futurewiz.co.i
⚫ always_ff procedure can be used to model synthesizable
sequential logic behavior.
always_ff @ (posedge clk iff !rst or posedge
rst) if(rst)
q<=0;
else
q<=d;
⚫ The always_ff procedure imposes the restriction that it contains
one and only one event control and no blocking timing
controls.
⚫ Tools should perform additional checks to warn if the behavior
does not
represent sequential logic.
Fine Grain process control
Futurewiz
www.futurewiz.co.i
⚫A process is a built-in class that allows one process
to
access and control another process once it has
started.
⚫Users can declare variables of type process and
safely pass them through tasks.
⚫Objects of type process are created internally when
processes are spawned. An attempt to call new()
would give error.
Fine Grain process control
Futurewiz
www.futurewiz.co.i
⚫self() function returns handle to current process.
⚫status() function returns process status which could be
any of the following:
o FINISHED : Terminated Normally
o RUNNING : Currently Running
o WAITING : Waiting in a blocking statement
o SUSPENDED : Stopped, Waiting for resume
o KILLED : Forcibly terminated
Fine Grain process control
Futurewiz
www.futurewiz.co.i
⚫kill() function terminates the current process and all its
sub processes.
⚫await() task allows one process to wait for
completion of another process.
⚫suspend() function allows a process to suspend
either its own execution or that of another process.
⚫resume() function restarts previously suspended
process.
Example
Futurewiz
www.futurewiz.co.i
task run1();
p1=process ::
self(); forever
#2 count+=1;
end
endtas
k
module test;
process p1,
p2; int count,
i=1;
//task
definitions
//On next
slide
endmodule
Example
Futurewiz
www.futurewiz.co.i
task run2 (ref process
p2); p2=process :: self();
repeat (6)
begin
#4
i*=2;
end
endtas
k
initial begin
$monitor($time,
count, i);
fork
run1()
;
run2(
p2);
join
en
d
Example
Futurewiz
www.futurewiz.co.i
initial begin
#3 p1.suspend();
#10 p2.suspend();
#5 p1.resume();
$display(“%s”,p1.status())
;
$display(“%s”,p2.status())
;
#2 p2.resume();
#1 p2.await();
#1 p1.kill();
end
System Verilog
COVERAGE
Coverage
Futurewiz
www.futurewiz.co.i
⚫ Coverage is the metric of completeness of
verification.
⚫ Why we need coverage?
o Direct Testing is not possible for complex
designs.
o Solution is constrained random verification but :
o How do we make sure what is getting
verified?
o Are all importance design states getting
verified?
⚫ Types of Coverage's:
o Code Coverage.
o Functional Coverage.
Code Coverage
Futurewiz
www.futurewiz.co.i
⚫ Code Coverage is a measure used to describe how much
part of code has been covered (executed).
⚫ Categories of Code Coverage
o Statement coverage
o Checks whether each statement in source is
executed.
o Branch coverage
o Checks whether each branch of control statement (if,
case) has been covered.
o Example: choices in case statements.
Code Coverage
Futurewiz
www.futurewiz.co.i
o Condition coverage
o Has Boolean expression in each condition evaluated to both
true and false.
o Toggle coverage
o Checks that each bit of every signal has toggled from 0 to 1
and 1 to 0.
o Transition coverage
o Checks that all possible transitions in FSM has been covered.
o State coverage
o Checks that all states of FSM has been covered.
Functional Coverage
Futurewiz
www.futurewiz.co.i
⚫ Functional Coverage is used to verify that DUT meets all
the described functionality.
⚫ Functional Coverage is derived from design
specifications.
o DUT Inputs : Are all interested combinations of
inputs injected.
o DUT Outputs : Are all desired responses observed
from
every output port.
o DUT internals : Are all interested design events
verified.
e.g. FIFO full/empty, bus
arbitration.
Examples
⚫ Have I exercised all the protocol request types and combinations?
o Burst reads, writes etc.
⚫ Have we accessed different memory alignments?
o Byte aligned, word aligned, dword aligned, etc.
⚫ Did we verify sequence of transactions?
o Reads followed by writes.
⚫ Did we verify queue full and empty conditions?
• o input and output queues getting full and new requests getting
back pressured.
Futurewiz
www.futurewiz.co.i
Code vs. Functional Coverage
Futurewiz
www.futurewiz.co.i
Needs more
Functional Coverage
points, Check for
unused code
Good Coverage
Start of Project Code may be incomplete
Code
Coverage
Functional
Coverage
Hig
h
Low
Hig
h
Low
Coverage Driven Verification
Create initial cover metrics
Generate Random Tests
Run Tests, Collect Coverage
Identify Coverage Holes
Coverage Met ?
Add tests to target holes,
Enhance stimulus
generator, Enhance cover
metrics if
From
Verificatio
n Plan
Verification
Complete
NO
Futurewiz
www.futurewiz.co.i
YES
SV Functional Coverage Support
Futurewiz
www.futurewiz.co.i
⚫ The System Verilog functional coverage constructs provides:
o Coverage of variables and expressions, as well as cross
coverage between them.
o Automatic as well as user-defined coverage bins.
o Associate bins with sets of values, transitions, or cross
products.
o Events and sequences to automatically trigger
coverage sampling.
o Procedural activation and query of coverage.
o Optional directives to control and regulate coverage.
covergroup
Futurewiz
www.futurewiz.co.i
⚫covergroup construct encapsulates the
specification of a coverage model.
⚫covergroup is a user defined type that allows you
to collectively sample all
variables/transitions/cross that are sampled at
the same clock (or sampling) edge.
⚫It can be defined inside a package, module,
interface, program block and class.
⚫Once defined, a covergroup instance can be
created
using new() - just like a class.
Example
Futurewiz
www.futurewiz.co.i
Syntax:
covergroup cg_name
[(port_list)] [coverage_event];
//coverage_specs;
//coverage_options;
endgroup [ : cg_name]
Example:
covergroup
cg;
……
endgrou
p
cg
⚫A coverage point (coverpoint) is a variable or
an expression that functionally covers design
parameters.
⚫Each coverage point includes a set of bins
associated with its sampled values or its value-
transitions.
⚫The bins can be automatically generated or
manually specified.
⚫A covergroup can contain one or more
coverpoints. Futurewiz
www.futurewiz.co.i
Coverpoint
Example
Futurewiz
www.futurewiz.co.i
Syntax:
[label : ] coverpoint expression [
iff (expression)]
[{
//bins specifications;
}] ;
Example:
covergroup
cg;
coverpoint a
iff (!reset);
endgroup
bins
Futurewiz
www.futurewiz.co.i
⚫ bins are buckets which are used to collect number of times a
particular value/transaction has occurred.
⚫ bins allows us to organize coverpoint sample values in different
ways.
o Single value bins.
o Values in a range, multiple ranges.
o Illegal values, etc.
⚫ If bins construct is not used inside coverpoint then automatic
bins are created based on the variable type and size.
⚫ For a n-bit variable, 2 ^ n automatic bins are created.
Example1
Futurewiz
www.futurewiz.co.i
bit [3:0] temp;
covergroup cg;
coverpoint
temp;
endgroup
//16 - Automatic bins
created
cg cg1;
initial cg1=new;
bin[0] to bin[15] are created where each bin stores
information of how many times that number has
occurred.
Example2
Futurewiz
www.futurewiz.co.i
bit [3:0] temp;
covergroup cg;
coverpoint
temp
{
bins a= { [0 :
15] };
//creates single bin for values 0-
15
bins b [ ]= { [0 : 15] }; //creates separate bin for
each
//value 0-15
}
endgroup
Example3
Futurewiz
www.futurewiz.co.i
bit [3:0] temp;
covergroup cg;
coverpoint
temp
{
bins a [ ]= { 0,
1, 2 };
bins b [ ]= { 0,
1, 2, [1:5] };
//creates three bins 0, 1,
2
//creates eight bins 0, 1,
2,
//1, 2, 3, 4,
5
}
endgroup
Example4
Futurewiz
www.futurewiz.co.i
bit [3:0] temp;
covergroup cg;
coverpoint
temp
{
bins a [4]=
{ [1:10], 1, 5,
7 };
//creates four
bins with
distribution <1,
2, 3>
<4, 5, 6>
<7, 8, 9>
}
endgrou
p
<10, 1, 5, 7>
Example5
Futurewiz
www.futurewiz.co.i
bit [9:0] temp;
covergroup cg;
coverpoint
temp
{
bins a =
{ [0:63], 65 };
// single
bin
bins b [ ]={ [127:150], [148:191] }; // overlapping multiple
bins // three bins
// multiple bins from
1000
bins c [ ]={ 200, 201, 202 };
bins d [ ]={ [1000:$] };
// to $(last
value:1023)
bins others [ ] = default;
}
endgroup
// bins for all other
value
Questa (How to obtain coverage)
Futurewiz
www.futurewiz.co.i
vlog +cover filename.sv
vsim –c modulename –do “run time; coverage report –
details;”
//Provides Function coverage, -details switch is used to
observe bins
vsim –c –cover modulename –do “run time; coverage report
–details; ” // -cover switch enables code coverage
vsim –c –cover modulename –do “run time; coverage report
–details –html;” //create html report for coverage
Covergroup Arguments
Futurewiz
www.futurewiz.co.i
⚫Parameterized Covergroups can be written
using arguments.
⚫Useful if similar covergroups are needed with
different parameters or covering different signals.
⚫Example: covergroup for all basic FIFO conditions.
⚫Actual values can be passed to formal arguments
while covergroup is instantiated.
⚫ref keyword is required if a variable is passed as an
argument.
Example
Futurewiz
www.futurewiz.co.i
bit [16:0] rdAddr, wrAddr;
covergroup addr_cov (input int low, int high, ref bit [16:0]
address)
@ (posedge clk);
addr_range : coverpoint
address { bins addrbin= { [low:
high] };
}
endgroup
addr_cov rdcov=new ( 0, 31, rdAddr );
addr_cov wrcov=new ( 64, 127, wrAddr
Covergroup inside a class
Futurewiz
www.futurewiz.co.i
⚫By embedding covergroup inside class, coverage
can be collected on class members.
⚫Very useful as it is a nice way to mix
constrained random stimulus generation
along with coverage.
⚫A class can have multiple covergroups.
⚫For embedded covergroups, instance must be
created be inside the new() of class.
Example
Futurewiz
www.futurewiz.co.i
class xyz;
bit [3:0]
m_x; int
m_y;
bit m_z;
covergroup cov1 @
(m_z); coverpoint m_x;
coverpoint m_y;
endgroup
//Embedded
Covergroup
//16 bins
//2^32 bins
function new(); cov1=new;
endfunction
endclass
Example
Futurewiz
www.futurewiz.co.i
class c1;
bit [7:0]
x;
covergroup cv (input int arg) @ (posedge
clk); option.at_least=arg;
coverpoint x;
endgroup
function new (int p1);
cv=new(p1); endfunction endclass
initial c1 obj=new(4);
Bins for Transition
Futurewiz
www.futurewiz.co.i
⚫In many cases, we are not only interested in
knowing if
certain values or value ranges happen.
⚫But, we are also interested in knowing if
transition between two values or two value
ranges happen.
⚫Transition coverage is often more interesting in
control scenarios, whereas value coverage is more
interesting in data path scenarios.
Specifying Transition
Futurewiz
www.futurewiz.co.i
⚫Single Value Transition
(value1=> value2)
⚫Sequence of Transitions
(value1=> value2 => value3=>
value4)
⚫Set of Transitions
(value1, value2 => value3, value4)
⚫Consecutive repetition of Transitions
value[*repeat_time]
Example1
Futurewiz
www.futurewiz.co.i
bit [4:1] a;
covergroup cg @ (posedge clk);
coverpoint a
{ bins sa [ ]= ( 4=>5=>6 ), ( [7:9],10=>11,12) ;
bins allother= default sequence;
}
endgroup
Sa will be associated with individual bins (4=>5=>6)
, (7=>11), (7=>12), (8=>11), (8=>12), (9=>11),
(9=>12),
(10=>11), (10=>12)
Example2
Futurewiz
www.futurewiz.co.i
⚫Consecutive
Repetition bins sb={
4 [*3] } ;
// (4=>4=>4)
bins sc [ ]={ 3 [*2:4] };
// (3=>3) , (3=>3=>3),
(3=>3=>3=>3)
⚫Non-Consecutive
Repetition bins sd [ ]={ 2
[->3] };
//2=>…. =>2 …. =>2
Automatic Bin creation
⚫ System Verilog creates implicit bins when coverpoint does not
explicitly specifies it.
⚫ The size of automatic bin creation is:
o In case of enum coverage point it is same as
number of elements in enum.
o In case of integral coverage point it is minimum of
2
• ^ no. of bits and value of auto_bin_max option.
o Automatic bins creation only considers two
state value.
o If auto_bin_max is less than 2 ^ no. of bits,
then values are equitably distributed among
the bins.
Futurewiz
www.futurewiz.co.i
Wildcard Bins
Futurewiz
www.futurewiz.co.i
⚫Wildcard bins are where X, Z or ? will be treated
as don’t care.
bit [2:0] num;
covergroup
cg; coverpoint
num
{ wildcard bins even={3’b??
0}; wildcard bins
odd={3’b??1};
}
endgroup
Wildcard Bins
Futurewiz
www.futurewiz.co.i
bit [3:0] count1;
bit [1:0] count2;
covergroup cg;
coverpoint count1
{ wildcard bins
n12_15={4’b11??};
//1100 || 1101 || 1110 || 1111
}
coverpoint count2
{ wildcard bins t
=(2’b0x=>2’b1x);
//(0, 1=>2, 3)
}
Excluding bins
Futurewiz
www.futurewiz.co.i
⚫In some cases all the bins may not be of
interest, or
design should never have a particular bin.
⚫These are two ways to exclude bins :
o ignore_bins
o illegal_bins
Ignore Bins
Futurewiz
www.futurewiz.co.i
⚫All values or transitions associated with
ignore_bins are excluded from coverage.
⚫Ignored values or transitions are excluded even if
they are also included in another bin.
bit [3:0] num;
covergroup cg;
coverpoint num
{ bins val
[ ]={ [1:15] };
ignore_bins bins
ignoreval={ 7, 8 };
//7 and 8 are
ignored
//ignore 7 and
8
ignore_bins bins ignoretran=(3=>4=>5);//ignore
transition
} endgroup
Ignore Bins
Futurewiz
www.futurewiz.co.i
bit [2:0] num;
covergroup cg;
coverpoint num
{ option.auto_bin_max
=4;
//<0:1> , <2:3>, <4:5>,
<6:7>
ignore_bins bins hi={6,
7};
// bins 6 and 7 are ignored
from coverage
}
Illegal Bins
Futurewiz
www.futurewiz.co.i
⚫ All values or transitions associated with illegal_bins are excluded
from coverage and run-time error is issued if they occur.
⚫ They will result in a run-time error even if they are also
included in another bin.
bit [3:0] num;
covergroup cg;
coverpoint num
{ //illegal bins 2 and
3
//4 to 5 is illegal
illegal_bins bins illegalval={ 2,
3 }; illegal_bins bins
illegaltran=(4=>5);
//transition
} endgroup
⚫Coverage points measures occurrences of individual
values.
⚫Cross coverage measures occurrences of combination
of values.
⚫Interesting because design complexity is in
combination of events and that is what we need to
make sure is exercised well.
⚫Examples:
o Was write enable 1 when address was 4’b1101.
o Have we provide all possible combination of inputs
to a Full
Adder. Futurewiz
www.futurewiz.co.i
Cross Coverage
Example1
Futurewiz
www.futurewiz.co.i
⚫Cross coverage is specified between two or
more coverpoints in a covergroup.
bit [3:0] a, b;
covergroup cg @ (posedge
clk); cross_cov: cross a , b;
endgroup
⚫16 bins for each a and b.
⚫16 X 16=256 bins for cross_cov
Example2
Futurewiz
www.futurewiz.co.i
⚫Cross coverage is allowed only between coverage
points defined within the same coverage group.
bit [3:0] a, b, c;
covergroup cg @ (posedge clk);
cov_add: coverpoint b+c;
cross_cov: cross a , cov_add;
endgroup
⚫16 Bins for each a, b and c. 32 bins for b +
c.
⚫16 X 32=512 bins for cross_cov.
Example3
Futurewiz
www.futurewiz.co.i
bit [31:0] a;
bit [3:0] b;
covergroup cg @ (posedge clk);
cova: coverpoint a { bins low
[ ]={ [0:9] }; } cross_cov: cross b, cova;
endgroup
⚫16 bins for b. 10 bins for cova.
⚫10 X 16=160 bins for cross_cov.
⚫Cross Manipulating or creating user-defined bins
for cross coverage can be achieved using bins
select- expressions.
⚫There are two types of bins select expression :
o binsof
o intersect
Futurewiz
www.futurewiz.co.i
Cross Coverage
binsof and intersect
Futurewiz
www.futurewiz.co.i
⚫The binsof construct yields the bins of expression
passed as an arguments. Example: binsof (X)
⚫The resulting bins can be further selected by including
or excluding only the bins whose associated values
intersect a desired set of values.
⚫Examples:
o binsof(X) intersect { Y } , denotes the bins of
coverage point X whose values intersect the range
given by Y.
o ! binsof(X) intersect { Y } , denotes the bins of
coverage point X whose values do not
intersect the range given by Y.
binsof and intersect
Futurewiz
www.futurewiz.co.i
⚫Selected bins can be combined with other selected
bins using the logical operators && and ||.
bit [7:0] a, b;
covergroup cg @ (posedge
clk); cova : coverpoint a
{
bins a1 = { [0:63] };
bins a2 = { [64:127] };
bins a3 = { [128:191] };
bins a4 = { [192:255] };
} endgroup
binsof and intersect
Futurewiz
www.futurewiz.co.i
covb : coverpoint b
{
bins b1 = { 0 };
bins b2 =
{ [1:84] };
bins b3 =
{ [85:169] };
bins b4 =
{ [170:255] };
}
binsof and intersect
Futurewiz
www.futurewiz.co.i
covc : cross cova, covb
{
bins c1= !binsof(cova) intersect {
[100:200] };
//a1*b1, a1*b2, a1*b3, a1*b4
bins c2= binsof(cova.a2) ||
binsof(covb.b2);
//a2*b1, a2*b2, a2*b3, a2*b4
//a1*b2, a2*b2, a3*b2, a4*b2
bins c3= binsof(cova.a1) &&
binsof(covb.b4);
//a1*b4
}
Excluding Cross products
Futurewiz
www.futurewiz.co.i
⚫A group of bins can be excluded from coverage by
specifying a select expression using ignore_bins.
covergroup
cg; cross a, b
{
ignore_bins
bins
ig=binsof(a)
intersect { 5,
[1:3] };
}
endgroup
⚫All cross products that satisfy the select expression
Illegal Cross products
Futurewiz
www.futurewiz.co.i
⚫A group of bins can be marked illegal by
specifying a select expression using illegal_bins.
covergroup cg (int
bad); cross a, b
{
illegal_bins bins
invalid=binsof(a)
intersect { bad
};
}
endgroup
Coverage Options
⚫ Options can be specified to control the behaviour of the covergroup,
coverpoint and cross.
⚫ There are two types of options:
o Specific to an instance of a covergroup.
o Specify for the covergroup.
⚫ Options placed in the cover group will apply to all cover points.
⚫ Options can also be put inside a single cover point for
• finer control.
Futurewiz
www.futurewiz.co.i
option.comment
Futurewiz
www.futurewiz.co.i
⚫Comments can be added to make coverage
reports easier to read.
covergroup cg;
option.comment=“Cover group for data and
address”; coverpoint data;
coverpoint address;
endgroup
per instance coverage
Futurewiz
www.futurewiz.co.i
⚫If your test bench instantiates a coverage group
multiple times, by default System Verilog groups
together all the coverage data from all the instances.
⚫Sometime you would that all coverpoints should be
hit on all instances of the covergroup and not
cumulatively.
covergroup cg;
option.per_instance=
1; coverpoint data;
endgroup
at_least coverage
Futurewiz
www.futurewiz.co.i
⚫By default a coverpoint is marked as hit (100%) if it is
hit at least one time.
⚫Some times you might want to change this to a
bigger value.
⚫Example: If you have a State machine that can
handle some kind of errors. Covering an error for
more number of times has more probability that
you might also test error happening in more than
one state.
option.at_least=10
Coverage goal
Futurewiz
www.futurewiz.co.i
⚫By default a covergroup or a coverpoint is
considered fully covered only if it hits 100% of
coverpoints or bins.
⚫This can be changed using option.goal if we want to
settle on a lesser goal.
bit [2:0] data;
covergroup cg;
coverpoint
data;
option.goal=90
; endgroup
//settle for partial
coverage
option.weight
Futurewiz
www.futurewiz.co.i
⚫If set at the covergroup level, it specifies the weight of
this covergroup instance for computing the overall
instance coverage.
⚫If set at the coverpoint (or cross) level, it specifies
the weight of a coverpoint (or cross) for
computing the instance coverage of the enclosing
covergroup.
⚫Usage: option.weight=2 (Default value=1)
⚫Usage: Useful when you want to prioritize
certain coverpoints /covergroups as must hit
versus less important.
Example
Futurewiz
www.futurewiz.co.i
covergroup cg;
a: coverpoint sig_a { bins a0= {0};
option.weight=0;
//will not compute to
//coverage
}
b: coverpoint sig_b { bins b1= {1};
option.weight=1;
}
ab: cross a , b
{ option.weight=3; } endgroup
option.auto_bin_max
Futurewiz
www.futurewiz.co.i
⚫Limiting autobins for coverpoints and crosses
⚫Usage: option.auto_bin_max = <number>
(default=64)
⚫Usage: option.cross_auto_bin_max =<number>
(default= unbounded)
Predefined Coverage Methods
Futurewiz
www.futurewiz.co.i
Example1
Futurewiz
www.futurewiz.co.i
covergroup packet_cg;
coverpoint dest_addr;
coverpoint
packet_type;
endgroup
packet_cg pkt;
initial pkt=new;
always @
(pkt_received)
pkt.sample();
Example2
Futurewiz
www.futurewiz.co.i
covergroup packet_cg;
coverpoint dest_addr;
coverpoint
packet_type;
endgroup
packet_cg
pkt; initial
pkt=new;
always @
(posedge clk)
if (port_disable)
pkt.stop(); else
Coverage system tasks and functions
Futurewiz
www.futurewiz.co.i
⚫$set_coverage_db_name ( name )
Sets the filename of the coverage database into
which coverage information is saved at the end of a
simulation run.
⚫$load_coverage_db ( name )
Load from the given filename the cumulative
coverage information for all coverage group types.
⚫$get_coverage ( )
Returns as a real number in the range 0 to 100 that
depicts the overall coverage of all coverage group
types.
Cover property
Futurewiz
www.futurewiz.co.i
⚫The property that is used an assertion can be used
for coverage using cover property keyword.
property ab;
@(posedge clk) a ##3
b; endproperty
cp_ab: cover property(ab)
$info(“coverage passed”);
Effect of coverage on performance
Futurewiz
www.futurewiz.co.i
⚫ Be aware that enabling Functional Coverage slows down the
simulation.
⚫ So know what really is important to cover :
o Do not use auto-bins for large variables.
o Use cross and intersect to weed out unwanted bins.
o Disable coverpoint/covergroup during reset.
o Do not blindly use clock events to sample coverpoint
variables, instead use selective sampling() methods.
o Use start() and stop() methods to decide when to
start/stop evaluating coverage.
o Do not duplicate coverage across covergroups and
properties.
System Verilog
ASSERTIONS
Assertions and Coverage
Futurewiz
www.futurewiz.co.i
⚫ Assertions
These are checks which used to verify that your design meets
the
given requirements.
Example: grant should be high two clock cycles after request.
⚫ Coverage
These are used to judge what percentage of your test
plan or functionality has been verified.
They are used to judge quality of stimulus.
They help us in finding what part of code remains
untested.
Assertions
Futurewiz
www.futurewiz.co.i
Design Rule : Grant should be asserted 2 clock cycles
after request
Clock
Reques
tGran
t
Gran
t
Assertion
Passed
Assertion
Failed
Assertions
Futurewiz
www.futurewiz.co.i
⚫Types of Assertions
Immediate
Assertions.
Concurrent
Assertions.
Immediate Assertions
Futurewiz
www.futurewiz.co.i
⚫ These are used to check condition at current time.
⚫ These checks are Non Temporal i.e. checks are not performed
across time or clock cycles.
⚫ These are used inside procedural blocks (initial/always
and tasks/functions).
⚫ Assertion fails if expression evaluates to 0, X or Z.
case an error is reported during
runtime.
[Label] : assert (expression) [pass
_statement];
⚫ In case fail_statement is not pro
[e
vi
l
d
s
e
e
d
f
a
a
n
i
d
l_
a
s
s
ta
se
te
rti
m
on
e
f
n
a
t
il
;
s
]
, then in
that
Example
stat
e
Futurewiz
www.futurewiz.co.i
IDL
E
RE
Q
RE
Q
RE
Q
IDL
E
IDL
E
Design Rule : State Machine should go to REQ state
only if req1 or
req2 is high.
clk
req1
req
2
Example
Futurewiz
www.futurewiz.co.i
always @ (posedge
clk) if (state==REQ)
REQ
assert ( req1 ||
req2) or
//if current state
is
//Check whether
req1
//req2 is
high
$info(“Correct
State”); else
$error(“Incorrect
State”);
Assertions Severity
Futurewiz
www.futurewiz.co.i
⚫$info indicates that the assertion failure carries no
specific severity. Useful for printing some messages.
⚫$warning indicates runtime warning. Can be
used to indicate non severe errors.
⚫$error indicates runtime error. Can be used to
indicate protocol errors.
⚫$fatal indicates fatal error that would stop
simulation.
Examples
Futurewiz
www.futurewiz.co.i
always @ (posedge clk)
assert(func(a, b)) ->myevent; else error=error + 1;
//Trigger myevent if function returns 1 else increase error
count.
always @ (negedge clk)
assert (y==0) error_flag=0; else error_flag=1;
//y should not be 1 at negedge of clk
always @ (state)
assert($onehot(state)) else $fatal(“state is not one hot”);
//In a one-hot encoded state machine all states should be
one-hot
Concurrent Assertions
Futurewiz
www.futurewiz.co.i
⚫ These assertions test for a sequence of events spread over
multiple clock cycles i.e. they are Temporal in nature.
⚫ property keyword is used to define concurrent assertions.
⚫ property is used to define a design specification that needs
to be verified
⚫ They are called concurrent because they occur in parallel with
other design blocks.
[Label] : assert property (property_name)
[pass_statement];
[else fail_statement;]
Assertions
Design Rule : Grant should be high 2 clock cycles
after request,
followed by low request and then grant in
consecutive cycles.
Clk
Req
Gn
t
Assertio
n Passed
Gn
t
Futurewiz
www.futurewiz.co.i
Assertio
n Passed
Example
Futurewiz
www.futurewiz.co.i
property req_gnt;
@ (posedge clk) req ##2 gnt ##1 !req ##1 !gnt;
endproperty
assert property(req_gnt) else $error(“req_gnt property violated”);
⚫ ## followed by a number is used to indicate no. of clock
cycles.
⚫ If gnt is not high 2 clock cycles after req goes high, violation
will be reported.
⚫ If req and gnt come at proper time but req is not low in next
clock
cycle, that will also lead to violations.
Assertion Region
Inactive
NBA
Observed
Re-Active
Re-Inactive
Postponed
$strobe, $monitor,
PLI Calls
Re-NBA
Preponed
Sample Data
before
entering
current time
slot (#1step)
Active
From Current Time
Slot
To Next Time
Slot
Values are sampled
in Preponed
Region
Evaluated in Observed
True / False
statements executed
in Re-Active
Futurewiz
www.futurewiz.co.i
Properties and Sequences
Futurewiz
www.futurewiz.co.i
⚫Assertions can directly include a property.
assert property (@ (posedge clk) a ##1
b);
⚫Assertions can be split into assertion and
property declared separately
property myproperty;
@ (posedge clk) a ##1 b ##1
c; endproperty
assert property (myproperty);
Properties and Sequences
Futurewiz
www.futurewiz.co.i
⚫A property can be disabled conditionally
property disable_property;
@ (posedge clk) disable iff
(reset) a ##1 b ##1 c;
endproperty
⚫property block contains definition of
sequence of events.
⚫Complex properties can be structured using
multiple sequence blocks.
Properties and Sequences
Futurewiz
www.futurewiz.co.i
sequence s1;
a ##1 b ##1
c;
endsequence
property p1;
@ (posedge clk) disable
iff (reset)
s1 ##1 s2;
endsequence
sequence
s2; a ##1 c;
endsequenc
e
assert
property(p1
);
Sequences
Futurewiz
www.futurewiz.co.i
⚫Sequence is series of true/false expression spread
over one or more clock cycles.
⚫It acts like basic building block for creating complex
property specifications.
⚫Sampling edge can be specified inside a
sequence. If not defined, it is inferred from
property block or assert block.
sequence s1;
@(posedge clk) a ##1 !b ##1 c ##0 !
d; endsequence
Linear Sequences
Futurewiz
www.futurewiz.co.i
⚫ Linear sequence is finite list of System Verilog Boolean
expression in a linear order of increasing time.
⚫ A sequence is set to match if all these conditions are true:
o The first boolean expression evaluates to true at the
first sampling edge.
o The second boolean expression evaluates to true after
the delay from first expression.
o and so forth, up to and including the last boolean
expression evaluating to true at the last sampling edge.
⚫ Sequence is evaluated on every sampling edge.
Example
• program
assert_test; initial
begin
• #4 a=1;
• #10 a=0; b=1;
• #10 b=0; c=1;
• #10 c=0;
• #10 a=1;
• #20 b=1;
• #10 c=1;
• #10;
• end
Futurewiz
www.futurewiz.co.i
module
test; bit clk;
logic a=0,
b=0, c=0;
always #5
clk=~clk; property
abc;
@ (posedge clk) a
##1 b ##1 c;
endproperty
assert
property(abc)
$info(“Sequence
Occurred”);
//program
Example
clk
a
b
c
Evaluation in
progress
Error
Reported
Sequence
Occurred
Futurewiz
www.futurewiz.co.i
⚫A sequence can be declared inside:
o Module
o Interface
o Program
o Clocking block
o Package
⚫Syntax:
sequence sequence_name [ (arguments)
]; boolean_expression;
endsequence [ : sequence_name]
Futurewiz
www.futurewiz.co.i
Declaring Sequences
⚫Sequences can have optional Formal Arguments.
⚫Actual arguments can be passed during
instantiation. sequence s1 (data, en)
( !a && (data==2’b11)) ##1
(b==en) endsequence
⚫Clock need not be specified in a
sequence.
⚫In this case clock will be inferred from the property
or
assert statement where this sequence is
Futurewiz
www.futurewiz.co.i
Sequence Arguments
⚫Evaluation of a sequence can be pre-conditioned
with an implication operator.
⚫Antecedent – LHS of implication operator
⚫Consequent – RHS of implication operator
⚫Consequent will be evaluated only if Antecedent is
true.
⚫There are two types of implication operators:
o Overlapping (Antecedent |-> Consequent )
o Non-Overlapping (Antecedent |=> Consequent )
Futurewiz
www.futurewiz.co.i
Implication Operator
⚫If antecedent is true then Consequent evaluation
starts immediately.
⚫If antecedent is false then consequent is not
evaluated and sequence evaluation is considered
as true this is called vacuous pass.
⚫$assertvacuousoff [ (levels[ , list]) ] can be used to
disable vacuous pass.
property p1;
@ (posedge clk) en |-> (req ##2 ack);
endproperty
Futurewiz
www.futurewiz.co.i
Overlapping Implication Operator
Example
• program
assert_test; initial
begin
• #4 en=1; req=1;
• #10 en=0; req=0;
• #10 gnt=1;
• #10 gnt=0;
• #20 en=1;
• #10 en=0; req=1;
• #10 req=0; gnt=1;
• #10;
• end
Futurewiz
www.futurewiz.co.i
module
test; bit clk;
logic en=0,
req=0,
gnt=0;
always #5
clk=~clk; property
abc;
@ (posedge clk)
en |-> req ##2
gnt;
endproperty
assert
property(abc)
$info(“Sequence
Example
clk
en
re
q
gn
t
Sequence Occurred
Evaluation in
progress Futurewiz
www.futurewiz.co.i
Error
Reported
Vacuous Pass
Example
Futurewiz
www.futurewiz.co.i
module
test; bit clk;
logic en=0,
req=0,
gnt=0;
always #5
clk=~clk; property
abc;
@ (posedge clk)
en ##0 req ##2
gnt;
endproperty
assert
program
assert_test; initial
begin
#4 en=1; req=1;
#10 en=0; req=0;
#10 gnt=1;
#10 gnt=0;
#20 en=1;
#10 en=0; req=1;
#10 req=0; gnt=1;
#10;
end
endprogram
Example
clk
en
re
q
gn
t
Evaluation
in
Reporte
d
progres
s
Futurewiz
www.futurewiz.co.i
Erro
r
Sequence
Occurred
⚫If antecedent is true then Consequent
evaluation starts in next clock cycle.
⚫If antecedent is false then consequent is not
evaluated and sequence evaluation is considered
as true this is called vacuous pass.
property p1;
@ (posedge clk) en |=> (req
##2 ack);
endproperty
Futurewiz
www.futurewiz.co.i
Non-Overlapping Implication Operator
Example
Futurewiz
www.futurewiz.co.i
module
test; bit clk;
logic en=0,
req=0,
gnt=0;
always #5
clk=~clk; property
abc;
@ (posedge clk)
en |=> req ##1
gnt;
endproperty
assert
program
assert_test; initial
begin
#4 en=1; req=1;
#10 en=0; req=0;
#10 gnt=1;
#10 gnt=0;
#20 en=1;
#10 en=0; req=1;
#10 req=0; gnt=1;
#10;
end
endprogram
Example
clk
en
re
q
gn
t
Vacuous Pass
Evaluation in
progress
Error
Reported
Sequence
Occurred Futurewiz
www.futurewiz.co.i
Example
Futurewiz
www.futurewiz.co.i
module
test; bit clk;
logic en=0,
req=0,
gnt=0;
always #5
clk=~clk; property
abc;
@ (posedge clk)
en ##1 req ##1
gnt;
endproperty
assert
program
assert_test; initial
begin
#4 en=1; req=1;
#10 en=0; req=0;
#10 gnt=1;
#10 gnt=0;
#20 en=1;
#10 en=0; req=1;
#10 req=0; gnt=1;
#10;
end
endprogram
Example
clk
en
re
q
gn
t
Evaluation
in
Erro
r
Sequenc
e
Reporte
d
progres
s
Occurre
d
Futurewiz
www.futurewiz.co.i
n
⚫## n represents n clock cycle delay (or
number of sampling edges).
⚫## 0 means same clock cycle (overlapping
signals).
⚫## [min : max] specifies a range of clock cycles
o min and max must be >=0.
sequence s1;
@ (posedge clk) a ## [1:3]
b; endsequence
Equivalent to: (a ##1 b) || (a
##2 b) || (a ##3 b)
Futurewiz
www.futurewiz.co.i
Sequence Operators
Example
clk
a
b
b
b
b
Assertio
n
Passed
Assertio
n
Passed
Assertio
n
Passed
Assertio
n
Failed
Futurewiz
www.futurewiz.co.i
⚫$ is used to specify infinite number of clock cycles
(till end of simulation).
sequence s2;
@ (posedge clk) a ## [2:$]
b; endsequence
b must be high after 2 or more clock cycle after
a is asserted.
Futurewiz
www.futurewiz.co.i
Sequence Operators
⚫Sequence of events can be repeated for a count using [*n].
sequence s3;
@ (posedge clk) a ##1 b
[*2]; endsequence
Equivalent to : a ##1 b ##1 b
b must be true for two consecutive clock cycles after a goes
high a ##1 (b ##1 c) [*2];
Equivalent to : a ##1 b ##1 c ##1 b ##1 c
Futurewiz
www.futurewiz.co.i
Sequence Operators
⚫Sequence of events can be repeated for a range
of count using [*m : n].
o n should be more than 0 and cannot be $
sequence s4;
@ (posedge clk) a ##1 b
[*2:5]; endsequence
Futurewiz
www.futurewiz.co.i
Equivalent to :
(a ##1 b ##1 b ) ||
(a ##1 b ##1 b ##1 b) ||
(a ##1 b ##1 b ##1 b ##1 b)
||
(a ##1 b ##1 b ##1 b ##1 b ##1
b) ||
Sequence Operators
b must be true for
minimum 2 and maximum
5 consecutive clock cycles
after a is asserted
Sequence Operators
Futurewiz
www.futurewiz.co.i
⚫[=m] operator can be used if an event repetition
of m non-consecutive cycles are to be detected.
o m should be more than 0 and cannot be $
sequence s5;
@ (posedge clk) a ##1 b [=2];
endsequence
b must be true for 2 clock cycles, that may not
be
consecutive.
Example
clk
a
b
b
Futurewiz
www.futurewiz.co.i
Assertio
n Passed
Assertio
n Passed
Sequence Operators
Futurewiz
www.futurewiz.co.i
⚫[=m : n] operator is used if an event repetition of m
(minimum) to n (maximum) non-consecutive cycles
are to be detected.
sequence s6;
@ (posedge clk) a ##1 b [=2: 3];
endsequence
cycles,
b must be true for minimum of 2 and maximum of 3
clock
Equivalent to : (a ##1 b [=2] ) || (a ##1 b
[=3] ) that may not be consecutive.
AND Operator
Futurewiz
www.futurewiz.co.i
⚫Use and operator if two sequences needs to match.
seq1 and seq2
⚫Following should be true for resultant
sequence to matches:
o seq1 and seq2 should start from same
point.
o Resultant sequence matches when both seq1
and seq2 matches.
o The end point of seq1 and seq2 can be
different.
o The end time of resulting sequence will be end
Example
c
d
e
Resultant
Sequence
Detecte
d
(a ##2 b) and (c ##1 d ##2
e)
clk
a
b
S
e
q
1
d
e
t
e
c
t
d
Seq detection
started
Seq2
detected Futurewiz
www.futurewiz.co.i
Example
clk
a
b
(a and
b)
Resultant
Sequence
Futurewiz
www.futurewiz.co.i
Detecte
d
Seq1
Detecte
d
Seq2
Detected
Example
(a ##[2:4] b) and (c ##1 d ##2
e)
clk
a
b
c
d
e Seq1 Seq2
Detected
Resultant
Sequence
Seq detection
started
Futurewiz
www.futurewiz.co.i
Detecte
d
Detecte
d
Intersect Operator
Futurewiz
www.futurewiz.co.i
seq1 intersect seq2
⚫Following should be true for resultant
sequence to matches:
o seq1 and seq2 should start from same
point.
o Resultant sequence matches when both seq1
and seq2 matches.
o The end point of seq1 and seq2 should be
same.
Example
(a ##[2:4] b) intersect (c ##1 d ##2
e)
clk
a
b
c
d
e Resultant
Sequence
Seq1 Seq2
Detected
Seq
detection
starte
d
Futurewiz
www.futurewiz.co.i
Detecte
d
Detecte
d
OR Operator
Futurewiz
www.futurewiz.co.i
⚫Use or operator when at least one of the
sequences needs to match.
seq1 or seq2
⚫Following should be true for resultant
sequence to matches:
o seq1 and seq2 should start from same
point.
o Resultant sequence matches when either seq1
or seq2 matches.
o The end point of seq1 and seq2 can be
different.
o The end time of resulting sequence will be end
time of last sequence.
Example
c
d
e
Resultant
Sequence
Detecte
d
(a ##2 b) or (c ##1 d ##2
e)
clk
a
b
S
e
q
1
d
e
t
e
c
t
d
Seq detection
started
Seq2
detected Futurewiz
www.futurewiz.co.i
Example
clk
a
b
(a or
b)
Resultant
Sequence
Futurewiz
www.futurewiz.co.i
Detecte
d
Seq1
Detecte
d
Seq2
Detected
Example
(a ##[2:4] b) or (c ##1 d ##2
e)
clk
a
b
c
d
e Resultant
Sequence Futurewiz
www.futurewiz.co.i
Detecte
d
Detecte
d
Seq1 Seq2
Detected
Seq detection
started
throughout Operator
Futurewiz
www.futurewiz.co.i
⚫Useful for testing a condition that an expression
has to be true throughout the sequence.
expr1 throughout seq1
⚫Left of throughout cannot be a sequence.
(!c) throughout a ##3 b
First_match Operator
Futurewiz
www.futurewiz.co.i
⚫first_match operator matches only first of
possible multiple matches for evaluation of
sequence.
a ##[2:5] b first_match(a
##[2:5] b)
Equivalent to:
(a ##2 b)
|| (a ##3 b)
||
(a ##4 b)
||
(a ##5 b)
Sequence will match only one
of the following options,
whichever occurs first
(a ##2 b)
(a ##3 b)
(a ##4 b)
(a ##5 b)
Example
first_match(a ##[2:4]
b)
clk
a
b
Seq
detection
Futurewiz
www.futurewiz.co.i
starte
d
Resultant sequence
detected
Example
(!c) throughout a
##3 b
clk
a
b
c Assertio
n
Failed Futurewiz
www.futurewiz.co.i
Assertion
Passed
Detection
Started
within Operator
Futurewiz
www.futurewiz.co.i
⚫Useful for testing a condition where a
sequence is overlapping in part length of
another sequence.
seq1 within seq2
⚫seq1 should happen between start and
completion of seq2.
sequence seq1; sequence seq2;
@(posedge clk) a ##2 b; @(posedge clk) c ##1 !d
##2 e; endsequence endsequence
property p1;
@(posedge clk) seq1 within
seq2; endproperty
not Operator
Futurewiz
www.futurewiz.co.i
⚫not operator is used to check that a particular
sequence should not occur.
sequence
abc; a ##1 b ##1 c;
endsequence
property
nomatch;
@(posedge clk) start
|-> not (abc); endproperty
not Operator
Futurewiz
www.futurewiz.co.i
⚫Example c ##1 d should not occur after a ##1 b.
property incorrect;
@(posedge clk) not (a ##1 b |=> c ##1
d); endproperty
⚫Will report even if a ##1 b does not occur
because of
vacuous pass.
property correct;
@(posedge clk) not(a ##1 b ##1 c ##1
d);
endproperty
If-else Expression
Futurewiz
www.futurewiz.co.i
⚫It is possible to select property expression based
on some condition using if-else expression.
property test;
@(posedge clk) (req1 || req2)
-> if(req1)
##1 ack1;
else
##1 ack2;
endpropert
y
Local Variables
Futurewiz
www.futurewiz.co.i
⚫Local variables can be declared and used
inside property and sequence.
⚫These are dynamically created inside sequence
instance and removed when end of sequence
occurs.
⚫Each instance of sequence has its own set of
variables.
⚫A local variable is assigned a value using a
comma separated list along with other
expressions.
Example
Futurewiz
www.futurewiz.co.i
sequence
s1; int i;
(data_valid, (i =
tag_in)) ##7 (tag_out
== i); endsequence
Local variable i is assigned a value
of tag_in when data_valid is high. This value is
then checked with the value of tag_out 7 clock
ticks later.
Sample Value Functions
Futurewiz
www.futurewiz.co.i
⚫Special System Functions are available for
accessing sampled values of an expression.
o Functions to access current sampled value.
o Functions to access sampled value in the past.
o Functions to detect changes in sample values.
⚫Can also be used in procedural code in
addition to assertions.
$rose, $fell
Futurewiz
www.futurewiz.co.i
⚫$rose(expression [, clocking event])
o Returns true if least significant bit changes to 1
with
respect to value (0, X, Z) at previous clock else
false.
⚫$fell(expression [, clocking event])
o Returns true if least significant bit changes to 0
with respect to value (1, X, Z) at previous clock
else false.
⚫Clocking event is optional usually derived from
$rose vs @(posedge)
Futurewiz
www.futurewiz.co.i
⚫@(posedge signal) returns 1 when signal changes
from (0, X, Z) to 1 or (0 to X) or (0 to Z).
⚫$rose(signal) is evaluated to true when signal
changes from (0, X, Z) to 1 across two clocking
event.
property p1;
@(posedge clk) a
##2 b;
endproperty
property p2;
@(posedge clk) a
##2
$rose(b);
endpropert
y
$rose
property p2;
@(posedge clk) a
##2
$rose(b);
endpropert
y
p
1 Futurewiz
www.futurewiz.co.i
asserte
p2
asserted
property p1;
@(posedge clk) a
##2 b;
endproperty
clk
a
b
$stable, $past
Futurewiz
www.futurewiz.co.i
⚫$stable(expression [, clocking event])
o Returns true if value of expression did not
change
from its sampled value in previous clock else
false.
⚫$past(expression [, no of cycles] [, gating
expression] [,clocking event])
o Used to access sampled value of an expression
any
number of clock cycles in past.
o no of cycles defaults to 1.
o gating expression for clocking event.
o clocking event inferred from assertion or
System Functions and Tasks
Futurewiz
www.futurewiz.co.i
⚫Following System Functions and Tasks are
available that can be used in assertions and
procedural blocks:
o $onehot (expression) Returns true if only one
bit of the expression is high.
o $onehot0 (expression) Returns true if at most one
bit of the expression is high.
o $isunknown (expression) Returns true if any bit of
the expression is X or Z.
o $countones (expression) Returns number of
one’s in the expression.
$asserton, $assertoff, $assertkill
Futurewiz
www.futurewiz.co.i
⚫disable iff can be locally disable assertions.
⚫$asserton, $assertoff and $assertkill are used to
control
assertions of a module or list of instance.
⚫$asserton, resume execution of assertions, enabled
by default.
⚫$assertoff, temporarily turns off execution of
assertions.
⚫$assertkill, kills all currently executing assertions.
$asserton(level [, list of modules or instances])
⚫A property is used to define behavior of a design.
⚫A property can be used for verification as an
assumption, a
checker, or a coverage specification.
o assert to specify the property as a checker to ensure that the property holds for the design.
o assume to specify the property as an assumption for the environment.
o cover to monitor the property evaluation for coverage.
⚫A property can be declared in a module, interface,
clocking
block, package or any compilation unit.
⚫Properties can have formal arguments like sequence
declarations.
Futurewiz
www.futurewiz.co.i
Properties
⚫Types of
Properties
o sequence
o negation
o disjunction
o conjunction
o if..else
o implication
o instantiation
Futurewiz
www.futurewiz.co.i
Types of Properties
⚫A property expression may be a simple
sequence expression.
⚫A sequence as a property expression is valid if
the sequence is not an empty match.
Futurewiz
www.futurewiz.co.i
Sequence
property p2;
a ##1 b ##1
c;
endproperty
property
p1; a;
endpropert
y
⚫A property is a negation if it has the form
not property_expr
⚫if property_expr evaluates to true, then
not property_expr evaluates to false,
and
⚫If property_expr evaluates to false, then
not property_expr evaluates to true.
property p3;
@ (posedge clk) not ( a ##1 b ##1 c );
endproperty Futurewiz
www.futurewiz.co.i
Negation
⚫A property is a disjunction if it has the
form property_expr1 or
property_expr2
⚫The property evaluates to true if and only if at least
one of property_expr1 and property_expr2 evaluates
to true.
property p4;
@ (posedge clk) ( (##[1:3] a) or (b |
=> c) ); endproperty Futurewiz
www.futurewiz.co.i
Disjunction (OR)
⚫A property is a conjunction if it has the
form property_expr1 and
property_expr2
⚫The property evaluates to true if and only if both
property_expr1 and property_expr2 evaluate to
true.
property p4;
@ (posedge clk) ( (##[1:3] b) and (c |
=> d) ); endproperty Futurewiz
www.futurewiz.co.i
Conjunction (AND)
if (expression) property_expr1
o Evaluates to true if expression evaluates false.
o Evaluates to true if expression evaluates true
and
property_expr1 also evaluates true.
o Others evaluate to False.
if (expression) property_expr1 else property_expr2
o Evaluates to true if expression evaluates true
and property_expr1 also evaluates true.
o Evaluates to true if expression evaluates false
and property_expr2 evaluates true.
o Others evaluate False. Futurewiz
www.futurewiz.co.i
If..else
⚫A property is an implication if it has either the
form
o sequence_expr |-> property_expr
(overlapping)
o sequence_expr |=> property_expr (non-
overlapping)
Futurewiz
www.futurewiz.co.i
Implication
property p5;
a |-> b ##1
c;
endproperty
property p6;
a |=> b ##1
c;
endproperty
⚫An instance of a property can be used inside
another property.
property p1(x,
y);
##1 x |->
y;
endpropert
y
property
p2;
@ (posedge
clk) a ##1 b |->
if(c) p1(d, e);
endpropert
y
Futurewiz
www.futurewiz.co.i
Instantiation
⚫A property is recursive if its declaration contains
an instance of itself.
property p7(a);
a and (1’b1 |=>
p7(a)); endproperty
⚫a should hold true in current and
next clock cycles.
assert property (@ (posedge clk) $fell(reset)
|-> p7(b) );
⚫Assert will make sure that after reset is de-
asserted the
signal b holds 1 all the time. Anytime b goes
asserted
.
Futurewiz
www.futurewiz.co.i
Recursive Properties
⚫What if we change above non-overlapping
operator to overlapping operator?
o Gets stuck in an infinite loop recursion in same
cycle resulting in a run-time error. So we need to
be careful while using recursive properties.
Futurewiz
www.futurewiz.co.i
Recursive Properties
Example
Design Rule : interrupt must hold until interrupt
ack is received.
clk
int
r
intr
a
intr
a
Futurewiz
www.futurewiz.co.i
Assertio
n Passed
Assertion
Failed
property cond( intr , intra);
intra or (intr and (1’b1 |=> cond( intr,
intra)));
endpropert
y
⚫The “and” between intr and the recursive call will
make sure that if intr goes low before intra - the
property/assertion fails.
⚫The “or” makes sure that property passes when
intra goes high.
Futurewiz
www.futurewiz.co.i
Example
⚫Operator “not” cannot be used in recursive
property instances.
property incorrect(p);
p and (1’b1 |=> not
incorrect(p)); endproperty
Futurewiz
www.futurewiz.co.i
Restriction on Recursive Property
⚫The operator “disable iff” cannot be used in
the declaration of a recursive property.
property
incorrect(p); disable
iff (a)
Futurewiz
www.futurewiz.co.i
⚫Rewrite as fpoallonwds(1a’bs1le|g=a>l is
not recursive.
Restriction on Recursive Property
incorrect(p))
;
endpropert
y
property correct(p);
p and (1’b1 |=>
correct(p));
endproperty
property legal(p);
disable iff (b)
correct(p));
endproperty
⚫If p is a recursive property, then, in the
declaration of p, every instance of p must occur
after a positive advance in time.
property rec(p);
p and (1’b1 |->
rec(p)); endproperty
⚫The overlapping operator will make this
recursion stuck in an infinite loop
Futurewiz
www.futurewiz.co.i
Restriction on Recursive Property
⚫Recursive properties can be mutually recursive.
property chk1;
a|-> b and (1’b1 |=>
chk2); endproperty
property chk2;
c |-> d and (1’b1 |=>
chk1); endproperty
⚫This is valid as there is time
advancement (non-
overlapping implication) and there
is an antecedent. Futurewiz
www.futurewiz.co.i
Mutual Recursion
⚫Labeling assertions is optional but highly useful for
debugging purpose, always label use meaningfully
label.
⚫Label gets printed during failure and also shows
up in waveform.
⚫Without label assertions from a module that are
instantiated multiple times will be a nightmare to
debug.
ERROR_q_did_not_follow_d:
assert property
( @(posedge clk) disable iff (!rst_n) (q==$past(d)) );
Futurewiz
www.futurewiz.co.i
Labeling Assertions

system verilog complete details with introduction

  • 1.
  • 2.
    ⚫ System Verilogis a hardware description and Verification language (HDVL). ⚫ It was developed by Accellera Systems Initiative and the IEEE Standards Association to address the growing complexity of modern digital systems. ⚫ System Verilog (IEEE Standard 1800-2005) is an extensive set of enhancements to IEEE 1364 Verilog- 2001 standards. ⚫ It inherits features from Verilog, VHDL, C and C++. ⚫ One of the key advantages of using SV is its ability to streamline the design and verification process. ⚫ Another significant advantage of System Verilog is its support for advanced verification techniques, such as the Universal Verification Methodology (UVM). What is SV?
  • 3.
  • 4.
    Regions in SV Inactive NBA Observed Re-Active Re-Inactive Postpone d $strobe, $monitor,PLI Calls Assertions are evaluated Execute statements with #0 delay Re-NBA Preponed Sample Data before entering current time slot (#1step) Continuous, Blocking and RHS of Non Blocking Assignment. $display, Non Blocking Assignments Pass/ Fail code of concurrent assertions #0 Statements in Program Block NBA inside Program Block Active From Current Time Slot To Next Time Slot
  • 5.
    ⚫System Verilog offersfollowing Data Types: o 4-State Type o 2-State Type o Real o Arrays o User Define Data Type o Structures o Unions o Strings o Enumerated Type o Class
  • 6.
    ⚫Allowed values are0, 1, X and Z. ⚫Following 4-State types are included from Verilog: o wire //Size: 1-bit Value: Z o reg //Size: 1-bit Value: X o integer // Size: 32-bit Value: X o time // Size: 64-bit Value: X ⚫User can define size for wire and reg. ⚫integer is signed, all others are unsigned. 4-State Type
  • 7.
    ⚫Addition to SystemVerilog o logic //Size: 1- bit ⚫User can define size for logic. Value: X ⚫Logic is improved reg data type. ⚫Logic can be driven by continuous as well as procedural assignments. ⚫Logic has a limitation that it cannot be driven by multiple drivers in such case use wire. 4-State Type
  • 8.
    Logic endmodul Example1: module and_gate (input logic a, b, output logic c); //driving logic using continuous assign c= a & b; assignment endmodule Example2: module flip_flop ( input logic din, clk, output logic dout); always @ (posedge clk) dout<=din; //driving logic using procedural assignment
  • 9.
    Logic driver . Example3: module example3 (input logic a, b, output logic c); assign c= a & b; //driving logic using continuous assignment always @ * c= a | b; assignmen t //driving logic using procedural eTnhdismcoodduelewill give compilation error because of multiple
  • 10.
    Logic Compilation error, usewire to achieve this functionality. Example4: module example4 ( input logic a, b, ctrl, output logic c); assign c= ctrl?a:1’bZ; //driving logic using continuous assignment assign c= !ctrl?b:1’bZ; //driving logic using continuous assignmen t endmodul e
  • 11.
    ⚫Allowed values are0 and 1. ⚫System Verilog offers following 2-State Data Types : ⚫ All are signed except bit which is unsigned. o shortint //Size: 16-bit Value: 0 o int //Size: 32-bit Value: 0 o longint //Size: 64-bit Value: 0 o byte //Size: 8-bit Value: 0 o bit //Size: 1-bit Value: 0 ⚫User can define size for bit. 2-State Type
  • 12.
    Example1 c=‘0; end endmodul e // locations withgiven number module example1; int a; int unsigned b; bit signed [7:0] c; initia l begi n a=-32’d127; b=‘1; //unsigned integer //same as byte //SV offers un-sized literal to fill all
  • 13.
    Example2 module example2; int a; logic[31:0] b=‘Z; initia l begi n a=b; b=32 ’h12 3x_5 678; //b=32’hzzzz_zzzz // a=32’h0000_0000 if($unknown(b)) $display(“b is unknown”); $display(“b is known”); else end end mo dul
  • 14.
    ⚫Included from Verilog oreal //Default Value : 0 ⚫real is same as double in C. ⚫Addition to System Verilog o shortreal //Default Value : 0 o realtime //Default Value : 0 ⚫shortreal is same as float in C. ⚫realtime and real can be used interchangeably. Real Type
  • 15.
    ⚫void data typerepresents non existing data. ⚫It can be used as return type of functions to indicate nothing is returned. Void Usage: display() ; Example : function void display; $display(“Hello”) ; endfunction
  • 16.
    ⚫Arrays are usedto group elements of same type. ⚫Arrays can be categorized as following: o Fixed Array o Dynamic Array o Packed Array o Unpacked Array o Queues o Associative Array Arrays
  • 17.
    ⚫Array whose sizeis fixed during compilation time is called as Fixed Array. ⚫Size of fixed array cannot be modified during run time. element Fixed Array Examples int array1 [15]; elements //array of int containing 15 //Equivalent to int array1 [0:14] int array2 [0:14]; logic array3 [7:0]; //array of logic containing 8
  • 18.
    ⚫Unpacked Arrays canbe declared by adding size after array name. ⚫Unpacked Arrays can be made of any data type. Example: ⚫System Verilog stores each element of an unpacked array in a longword (32-bit). Unpacked Array int array1 [16] [8]; bit array2 [3:0] [7:0]; bit [7:0] array3 [4]; //16 rows , 8 columns //4 rows , 8 columns //4 rows each containing 8 bits
  • 19.
    Unpacked Array bit [7:0]array1 [4]; array1 [2] array1 [3] Unus ed 7 6 5 4 3 2 1 0 Unu sed 7 6 5 4 3 2 1 0 array1 [0] Memory array1 [1] Memory Unu sed 7 6 5 4 3 2 1 0 Memory Unu sed 7 6 5 4 3 2 1 0 Memory
  • 20.
    Unpacked Array }; Initializing Array: intarray1 [2] [4] = ‘{ ‘{ 1, 2, 3, 4 } , ‘{ 5, 6, 7, 8 } }; int array2 [2] [3] = ‘{ ‘{ 1, 3, 6 } , ‘{ 3 {2} }; // same as ‘{ 1, 3, 6 } , ‘{ 2, 2, 2 } int array3 [0:5] = ‘{1:5, 3:1, default: 0}; // same as ‘{0, 5, 0, 1, 0, 0} int array4 [0:2] [1:4] = ‘{3 { ‘{ 2 {1, 2} } } }; // same as ‘{ ‘{1, 2, 1, 2} , ‘{1, 2, 1, 2} , ‘{1, 2, 1, 2} } int array5 [2] [2] [2] = ‘{ ‘{ ‘{4, 5}, ‘{3, 1} }, ‘{ ‘{1, 7}, ‘{2, 5} }
  • 21.
    Unpacked Array Accessing Array int array1[2] [4]; int array2 [0:5]; byte array3 [0:2] [1:4]; int a, b; byte c; a= array1[1] [3]; b= array2[4]; c= array3[1] [2];
  • 22.
    Basic Array Operation ⚫Arrayscan be manipulated using for and foreach loop bit [7:0] array1[10], array2[10] ; initia l begi n for ( int i=0; i <$siz e(arr ay1); //$size returns size of //k is defined implicitly
  • 23.
    Basic Array Operation Example: bit[7:0] array1[10] [20]; initia l begi n array 1=‘{1 0 { ‘{0: 2, 1 : 0 ,
  • 24.
    ⚫Packed Arrays canbe declared by adding size before array name. ⚫One dimensional packed arrays are also referred as vectors. ⚫Packed array is a mechanism of subdividing a vector into subfields which can be accessed as array elements. ⚫Packed array represents contiguous set of bits. ⚫Packed array can be made of single bit data (logic, bit, reg), enumerated type or other packed arrays. Packed Array
  • 25.
    Packed Array bit [3:0][7:0] array1; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 array1[3 ] bit [7:0] a, b; bit [15:0] c; bit d; bit [31:0] e; ] array1[1 array1[0] [4] array1[3:2 ] array 1 e=array1 ; a=array1[3]; b=array1[1]; c=array1[3:2]; d=array1[0] [4];
  • 26.
    Packed Array 7 65 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 Mixture of Packed and Unpacked Array bit [3:0] [7:0] b [4]; b[0] 7 6 5 4 3 2 1 0 7 6 5 [ 2 4] 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 b[1 ] b[2 ] b[3 ] b[0] [2] b[1 ] b[2] [2] b[3] [0] b[0] [1] [4:0]
  • 27.
    Packed vs. UnpackedArray ⚫ Packed arrays are handy if user wants to access array with different combination. ⚫ If user want to wait for change in array(i.e. @), in that case packed array will be preferred over unpacked array. ⚫ Only fixed size arrays can be packed. Therefore it is not possible to pack following arrays: o Dynamic Arrays o Queues o Associative Arrays
  • 28.
    Operation on Arrays intA [0:7] [15:0] , B [0:7] [15:0]; ⚫Following operation are possible for both packed and unpacked arrays. ⚫Both array A and B should be of same type and size. A=B; A[0:3]= B[0:3]; A[1+:4]= B[3+:4]; A[5]=B[5]; A==B A[2:4]! =B[2:4]; //Copy Operation //Slice and Copy //Comparison Operations
  • 29.
    Operation on Arrays bit[3:0] [7:0] A; ⚫Following operation are only allowed in packed arrays: A=0; A=A + 3; A=A * 2; A=‘1; A=A & 32’d255; A[3:1]=16’b1101_1110_0000_1010;
  • 30.
    ⚫Dynamic arrays areunpacked arrays whose size can be set and changed during simulation time. ⚫new constructor is used to set or change size of Dynamic Array. ⚫size() method returns current size of array. ⚫delete() method is used to delete all elements of the array. Dynamic Array
  • 31.
    Dynamic Array int dyn1[ ]; int dyn2 [4] [ ]; //Defining Dynamic Array (empty subscript) initial begin dyn1=new[10]; foreach (dyn1[ i ]) dyn1[ i ]=$random; dyn1=new[20] (dyn1); //Allocate 10 elements // Initializing Array // Resizing array and // Copying older values // Resizing to 50 elements Old Values are lost // Delete all elements dyn1=new[50 ]; dyn1.delete; end
  • 32.
    Dynamic Array int dyn1[ ]= ‘{5, 6, 7, 8} ; //Alternative way to define size initial begin repeat (2) if (dyn1.size != 0) begin foreach(dyn1 [ i ] ) $display(“dyn1 [%0d]=%0d”, i, dyn[ i ] ); dyn1.delete; en d else
  • 33.
    ⚫A Queue isa variable size, ordered collection of homogenous elements. ⚫Queues support constant time access to all its elements. ⚫User can Add and Remove elements from anywhere in a queue. ⚫Queue is analogous to 1-D array that grows and shrinks automatically. ⚫0 represents 1st element and $ represents last element. Queue
  • 34.
    Queue b > $returns q [a: $] // Unbounded Queue // Bounded Queue max size is 0 < a < b returns queue with b - a + 1 elements. a = b = n returns q[n] a > b returns empty queue a or b is either x or z returns empty queue a < 0 returns q [0: b] Declaration: int q1 [ $ ]; int q2 [ $ : 100 ]; 101 Operators : q [ a : b ];
  • 35.
    ⚫size() method returnsnumber of elements in a queue. x=A.size(); Queue Methods int A [$] = ‘{ 0, 1, 2, 3, 4, 5, 6 }; int x, y, z; 0 1 2 3 4 5 6 A 7 A.delete(5) ; x 0 1 2 7 3 4 5 6 0 1 2 7 3 5 6 ⚫insert(index, item) method is used to insert item at a given index. A.insert(3, 7); A ⚫delete(index) method is used to delete a queue if index is not specified else it is used to delete item at given index. A
  • 36.
    ⚫pop_front() method removesand returns 1st element of the queue. y=A.pop_front() ; ⚫pop_back() method removes and returns last element of the queue. z=A.pop_back(); ⚫push_front(item) method inserts item at the front of the queue. A.push_front(9) ; ⚫push_back(item) method inserts item at the back of the queue. A.push_back(8); Queue Methods 1 2 7 3 5 6 A 1 2 7 3 5 A 9 1 2 7 3 5 A 9 1 2 7 3 5 8 A y 0 6 z
  • 37.
    Queue int q [$]= ‘{ 5, 7, 9, 11, 2}; q = { q, 6 }; q = { 3, q }; q = q [1:$]; q = q[0:$- 1]; q = { q[0:3], 9, q[4:$] }; q = {}; // q.push_back(6) // q.push_front(3) // void'(q.pop_front()) // or q.delete(0) // void'(q.pop_back()) // or q.delete(q.size- 1) // q.insert(4, 9) // q.delete() q = q[2:$]; q = q[1:$- 1]; // a new queue lacking the first two items // a new queue lacking the first and last items
  • 38.
    Array Query Functions ⚫$leftreturns the left bound of the dimension. ⚫$right returns the right bound of the dimension. ⚫$increment returns 1 if $left is greater than or equal to $right and –1 if $left is less than $right. ⚫$low returns the same value as $left if $increment returns –1, and the same value as $right if $increment returns 1.
  • 39.
    Array Query Functions ⚫$highreturns the same value as $right if $increment returns – 1, and the same value as $left if $increment returns 1. ⚫$size returns the number of elements in the dimension. ⚫$dimensions returns total number of dimensions in the array. ⚫$unpacked_dimensions returns total number of unpacked dimensions for an array.
  • 40.
    Array Locator Methods ⚫Array locator methods works on unpacked arrays and returns queue. ⚫ with clause is mandatory for the following locator methods: ⚫ find() returns all the elements satisfying the given expression. ⚫ find_index() returns the indices of all the elements satisfying the given expression. ⚫ find_first() returns the first element satisfying the given expression.
  • 41.
    Array Locator Methods ⚫find_first_index()returns the index of the first element satisfying the given expression. ⚫find_last() returns the last element satisfying the given expression. ⚫find_last_index() returns the index of the last element satisfying the given expression.
  • 42.
    Array Locator Methods ⚫with clause is not mandatory for the following locator methods: ⚫ min() returns the element with the minimum value or whose expression evaluates to a minimum. ⚫ max() returns the element with the maximum value or whose expression evaluates to a maximum. ⚫ unique() returns all elements with unique values or whose expression evaluates to a unique value. ⚫ unique_index() returns the indices of all elements with unique values or whose expression evaluates.
  • 43.
    Array Locator Methods inta [6] = ‘{9, 1, 8, 3, 4, 4}; int b [$], c [$] = ‘{1, 3, 5, 7}; b = c.min; // {1} b = c.max; // {7} b = a.unique; // {1, 3, 4, 8, 9} b = a.find with (item > 3); // {9, 8, 4, 4} b = a.find_index with (item > 3); // {0, 2, 4, 5} b = a.find_first with (item > 3); // {9} b = a.find_first_index with (item==8); // {2} b = a.find_last with (item==4); // {4} b = a.find_last_index with (item==4); // {5}
  • 44.
    Array Ordering Methods ⚫reverse()reverses the order of elements in an array. ⚫sort() sort array in ascending order with optional with clause. ⚫rsort() sort array in descending order with optional with clause. ⚫shuffle() randomizes the order of elements in an array. 5 3 1 9 8 2 7 A A A int A [7] = ‘{ 5, 3, 1, 9, 8, 2, 7}; A.reverse(); A.sort(); A.rsort() ; 7 2 8 9 1 3 5 1 2 3 5 7 8 9 9 8 7 5 3 2 1 A
  • 45.
    Array Reduction Methods ⚫sum()returns sum of all elements in an array or specific elements if with clause is present. ⚫product() returns product of all elements in an array or specific elements if with clause is present. ⚫and() returns bitwise and of all array elements or specific elements if with clause is present. ⚫or() returns bitwise or of all array elements or specific elements if with clause is present. ⚫xor() returns bitwise xor of all array elements or specific elements if • with clause is present.
  • 46.
    ⚫ In casesize of data is not known or data space is sparse, Associative array is a better option. ⚫ System Verilog allocates memory for an associative element when they are assigned. ⚫ Index of associative can be of any type. ⚫ If index is specified as * , then the array can be indexed by any integral expression of arbitrary size. ⚫ real and shortreal are illegal index type. Associative Array
  • 47.
    int array1 [* ]; int array2 [ int ]; //Array can be indexed by any integral expression. int array3 [ string ]; //Indices can be strings or Associative Array
  • 48.
    int xyz [ *]; 0 xyz[0]=5; xyz[1]=7; xyz[2]=2; xyz[3]=1; xyz[7]=3; xyz[10]= 9; 3 7 10 //Memory allocated during assignment 5 7 2 1 3 9 Associative Array 1 2
  • 49.
    ⚫ num() andsize() method returns number of elements in associative array. ⚫ delete(index) deletes element at given index if index is specified else deletes entire array. ⚫ exists(index) checks whether an element exists at the specified index. ⚫ first(index) method assigns to the given index variable the value of the first (smallest) index. first (smallest) index. It returns 0 if the array is empty; otherwise, it returns 1. Associative Array Methods
  • 50.
    ⚫ last(index) methodassigns to the given index variable the value of the last (largest) index in the associative array. It returns 0 if the array is empty; otherwise, it returns 1. ⚫ next(index) method finds the smallest index whose value is greater than the given index argument. Returns 1 if new index is different as old index else 0. ⚫ prev(index) function finds the largest index whose value is smaller than the given index argument. Returns 1 if new index is different as old index else 0. Associative Array Methods
  • 51.
    int a [string]=‘{“Jan”: 1, “Feb”: 2, “Mar”: 3, “April”: 4, “May”: 5}; string index; initia l begi n a.firs t(ind ex); $display(a[index]); while(a.next(index // index=Jan //Go through all index Associative Array Methods
  • 52.
    ⚫System Verilog allowsuser to define new data types using typedef keyword. User Defined typedef byte unsigned uint8; typedef bit [15:0] word; //Defining uint8 //Defining word uint8 a, b; word c, d; a=8’d10; c=16’d25;
  • 53.
    ⚫Structure and Unionsare used to group non- homogenous data types. ⚫By default structure are unpacked. ⚫Unpacked structure can contain any data type. Declaration : Structures struct { bit [7:0] opcode; bit [15:0] addr; } IR; struct {bit [7:0] r, g, b;} pixel; struct {int a, b; real b;} mix;
  • 54.
    Structures IR=‘{opcode : 7’d8,addr : 15’d1}; pixel=‘{ 128, 255, 100}; pixel=‘{ r :128, g : 255, b :100}; pixel=‘{ int :0}; mix=‘{ 3, 5, 5.6}; mix=‘{ int : 1, real : 1.0}; mix=‘{ default : 0}; Initializing : int x; bit [7:0] y; pixel.r=200 ; mix.a=3; mix.c=4.5; x=mix.b; y=pixel.g; Accessing :
  • 55.
    Packed Structures ⚫Packed Structureis made up of bit fields which are packed together in memory without gaps. ⚫A packed structure can be used as a whole to perform arithmetic and logical operations. ⚫First member of packed array occupies MSB and subsequent members follow decreasing significance. ⚫Structures can be packed by writing packed keyword which can be followed by signed or unsigned keyword.
  • 56.
    Packed Structures Example : typedefstruct packed signed { shortint a; //16-bits [31:16] byte b; //8- bits [15:8 ] [7:0] bit [7:0] c; //8- bits } exam_st; exam_st pack1; bit [7:0] a, b, c; pack1=‘{a: ’1, b: -10, c: 8’b1001_0101}; a=pack1.b; b=pack1.c; c=pack1[9:2] ;
  • 57.
    Packed Structures ⚫Only packeddata type and integer data types are allowed inside packed structures struct packed { bit [3:0] a; bit [7:0] b; // default unsigned bit [15:0] c [7:0] ; } pack2; Compilation Error packed structure cannot have unpacked element
  • 58.
    Packed vs UnpackedStructures struct { bit [7:0] a; bit [15:0] b; int c; } str1; struct packed { bit [7:0] a; bit [15:0] b; int c; } str2; 31:24 23:16 15:8 7:0 Unused a Unused b c 55:48 47:32 31:0 a b c
  • 59.
    ⚫Union represents asingle piece of storage element that can be accessed by any of its member. ⚫Only one data types in union can be used at a time. Example : Unions union { real a; int b; bit [7:0] union packed { real a; int b; bit [7:0] c;
  • 60.
    Unions Example : typedef union { shortint a; intb; bit [7:0] c; } my_un; my_un un1; un1.a=16’hf0f0 ; 00 00 00 00 00 00 F0 F0 00 00 F0 AA
  • 61.
    Structures vs Unions StructureUnion Memory is allocated to each and every element. Common memory is allocated for all the members. Size of structure is sum of size of each member or more. Size of union is equal to size of largest member First member is at offset 0. All member have 0 offset. Modifying value of one member has no effect on other members Modifying value of one member modifies value of all members
  • 62.
    ⚫System Verilog stringtype is used to store variable length strings. ⚫Each character of string is of type byte. ⚫There is no null character at the end of string. ⚫String uses dynamic memory allocation, so size of string is no longer a concern. Example : string s=“hello”; String
  • 63.
    String Operators ⚫str1 ==str2 checks whether strings are equal or not. ⚫str1 != str2 checks for inequality of strings. ⚫Comparison using lexicographical ordering of strings. o str1 < str2 o str1 <= str2 o str1 > str2 o str1 >= str2 ⚫{str1, str2, str3, .. , strn} concatenation of strings.
  • 64.
    String Operators Example : strings1=“hello”, s2=“Hello”, s3=“xyz”; initial begin if(s1 != s2) $display(“strings are different”); if(s1 > s3) $display(“s1 is more than s3”); else $display(“s3 is more than s1”); $display({s1, s2, s3}); end
  • 65.
    String Methods ⚫len() methodreturns length of a string. ⚫putc(position, character) method replaces character at given position by character passed as an argument. ⚫getc(position) method returns ASCII value of character at given position. ⚫toupper() method returns a string with all characters in uppercase.
  • 66.
    String Methods ⚫tolower() methodreturns a string with all characters in lowercase. ⚫compare(string) compares given string with string passed as an argument. ⚫icompare(string) same as above but comparison is case insensitive. ⚫substr(i, j) returns a string formed between characters at position i and j.
  • 67.
    String Methods ⚫atoi() methodreturns integer corresponding to ASCII decimal representation. ⚫The conversion scans all leading digits and underscore characters ( _ ) and stops as soon as it encounters any other character or the end of the string. ⚫itoa(i) stores the ASCII decimal representation of i in sEtrxinagm.ple : string s1=“12_3xyz”, s2; int a, b=127; a=s1.atoi(); //a=123 s2.itoa(b); // s2=“127”
  • 68.
    String Methods //Display: 83(‘S’) // Display: SYSTEMVERILOG // "SystemVerilog3.1b" // change b-> a // Display: stem s2=$psprintf("%s %0d", s1, 5); $display(s2); // Display: SystemVerilog3.1a 5 end Example : string s1, s2; initial begin s1 = "SystemVeri log"; $display(s1. getc(0)); $display(s1.toupper() ); s1 = {s1, "3.1b"}; s1.putc(s1.len()-1, "a"); $display(s1.substr(2, 5));
  • 69.
    ⚫An enumeration createsa strong variable type that is limited to a set of specified names. Example : enum { RED, GREEN, BLUE } color; typedef enum { FETCH, DECODE, EXECUTE } operation_e; ⚫enum are stored as int unless specified. typedef enum bit [2:0] { RED, GREEN, BLUE } color_e; ⚫First member in enum gets value 0, second value 1 and so on. ⚫User can give different values to member if required. Enumerated Type
  • 70.
    Enumerated Type Example : enum{ RED, GREEN, BLUE } color; //RED=0, GREEN=1, BLUE=2 enum { GOLD, SILVER=3, BRONZE} medals; //GOLD=0, SILVER=3, BRONZE=4 enum {A=1, B=3, C, D=4} alphabet; //Compilation error C and D have same value enum logic [1:0] {A=0; B=‘Z, C=1, D} exam; //A=00, B=ZZ, C=01, D=10 Default value of exam is X
  • 71.
    ⚫first() method returnsfirst member of enumeration. ⚫last() method returns last member of enumeration. ⚫next(N) method returns the Nth next member (default is 1) starting from current position. ⚫previous(N) method returns Nth previous member (default is 1) starting from current position. Enumerated Type Methods
  • 72.
    ⚫Both next() andprev() wraps around to start and end of enumeration respectively. ⚫num() method returns number of elements in given enumeration. ⚫name() method returns the string representation of given enumeration value. Enumerated Type Methods
  • 73.
    Enumerated Type Methods Example typedefenum { RED, BLUE, GREEN} color_e; color_e mycolor; mycolor = mycolor.first; do begin $display("Color = %0d %0s", mycolor, mycolor.name); mycolor = mycolor.next; end while (mycolor != mycolor.first); // Done at wrap- around
  • 74.
    const ⚫const keyword isused to define constants in System Verilog. ⚫localparam constants are set during elaboration time. ⚫const constants are set during simulation time. Example: const byte colon= “:”; const real pi=3.14;
  • 75.
    Events • Events arestatic objects useful for synchronization between the process. • Events operations are of two staged processes in which one process will trigger the event, and the other processes will wait for an event to be triggered. • Events are triggered using -> operator or ->> operator. • wait for an event to be triggered using @ operator or wait() construct • System Verilog events act as handles to synchronization queues. thus, they can be passed as arguments to tasks, and they can be assigned to one another or compared. • Syntax: a) ->event_name; b) @(event_name.triggered);
  • 76.
    Casting ⚫Casting is usedconvert data from one type to other. ⚫There are two ways to perform casting : o Static Casting: destination = return_type’ (source). This type of casting always succeeds at run time and does not give any error. o Dynamic Casting: using $cast system task or function. Example : int a; initial a=int’(3.0 * 2.0);
  • 77.
    Casting ⚫System Verilog providesthe $cast system task to assign values to variables that might not ordinarily be valid because of differing data type. ⚫ $cast can be called as either a task or a function. $cast used as a function if ($cast(destination, source)) source // should be singular $cast used as a task $cast(destination, source); //destination and
  • 78.
    Casting int a; real b=3.0; if($cast(a,b)) //Returns 1 if casting succeeds else 0 $display(“casting success”); $cast(a, b); //If casting fails run time error occurs In both cases if casting fails then destination value remains unchanged.
  • 79.
  • 80.
    Casting typedef enum {red, green, blue, yellow, white, black } Colors; Colors col; int a, b; initial begin col=green; //col=3; a= blue * 2; b= col + green; end Runtime error
  • 81.
    Casting en d typedef enum {red, green, blue, yellow, white, black } Colors; Colors col; initial begin $cast( col, 2 + 3 ); // col=black if ( ! $cast( col, 2 + 8 ) ) $display( "Error in cast" ); //10: invalid cast col = Colors’(2 + 1); col = Colors’(4 + 3); //col=yellow //value is empty
  • 82.
  • 83.
    Operators ⚫Included from Verilog  Arithmetic Logical  Relational  Equality  Bitwise  Reduction  Shift  Concatenation  Replication  Conditional + - * / % ** ! && || > < >= <= == != === !== ~ & | ^ ~^ ^~ ~^ ^~ & >> ~& | ~| ^ << >>> <<< { op1, op2, op3, .. , opn } { no_of_times { a } } cond ? True_Stm : False_Stm
  • 84.
    Operators >>>= <<<= += -=*= /= %= ++ -- -> <-> &= | = ^= >>= <<= =?= !?= ⚫Additions to System Verilog  Arithmetic  Increment/Decrement  Logical  Bitwise  Shift  Wildcard Equality  Set Membership  Distribution  Stream insid e dist {<<{}} {>>{} }
  • 85.
    Example1 int a, b,c=2, d=6, e=10; initial begin a=d++; b=+ +d; c*=d; c>>=1; e%=3; e+=2; end Result : a = 6 b= 8 c= 8 d= 8 e= 3
  • 86.
    Example2 int a, b,c, d; initial begin b=3; if((a=b)) //brackets compulsor y $display(“a=%d b=%d”, a, b); (a=(b=(c=4))); end Result: a=3 b=3 c=4 b= 4 a=4 // Display if ((a=b)) is same as a=b; if (a)
  • 87.
    Example3 int a=1, b=2; initial beginif(a- >b) $display(“a implies b”); if (a<-> b) $display(“a is logically equivalent to b”); end a->b is same as !a || b a<-> b is same as (!a || b) && (!b || a) Result: a implies b a is logically equivalent to b
  • 88.
    Example4 int i=11, range=0; bit a=5’b10101; initialbegin if(a=?=5’b1XZ01) range+=1 ; end if(i inside { [1:5], [10:15], 17,18})// i is 1-5 or 10-15 or 17or 18 range+=1; Result: range= 2 //X and Z acts like don’t care
  • 89.
    Loops ⚫Included from Verilog •for • forever • repeat • while ⚫Additions to System Verilog o foreach o do while
  • 90.
    Loops inital begin int a [8][5]; foreach ( a [i, j] ) a[i] [j]=$rando m; end inital begin int i=10; do begin i -=1; //statements end while (i >5) end Statements executed first an then execution depends upon condition Used to access all elements in an array
  • 91.
    Break and Continue inital beginint i; repeat(10) begin if(i==7) break; i+=1; en d en inital begin int i; repeat(10) begin if(i==7) continue; i+=1; en d en
  • 92.
    package ⚫Packages provide waysto have common code to be shared across multiple modules. ⚫A package can contain any of the following: o Data Types o Subprograms (Tasks/Functions) o Sequence o property ⚫Elements of a package can be accessed by: o :: (Scope Resolution Operator) o import keyword
  • 93.
    `include vs import ⚫`includeis used to include the content of specified file to the given location. ⚫It is equivalent to copying the content and pasting at the given location. `include “xyz.v” ⚫Import is used to access elements defined inside the package without copying them to current location. import :: element_name; import :: *;
  • 94.
    Example “file1.sv” function int add(input int a, b ); add= a + b; endfunctio n “file2.sv” function int add (input int a, b, c ); add= a + b + c; endfunction `include “file1.sv” `include “file2.sv” module test; initial begin int x=add(1, 2, 3); int y=add(3, 4); end endmodule Compilation error add already exists
  • 95.
    Example “pack1.sv” package mypack1; int x; add=a + b; endfunctio n function int add (input int a, b ); function int add (input int a, b, c endpackag e “pack2.sv” package mypack2; int y; ); add= a + b + c; endfunction endpackag e
  • 96.
  • 97.
    unique and priority ⚫Improperlycoded case statements can frequently cause unintended synthesis optimizations or unintended latches. ⚫System Verilog unique and priority keywords are designed to address improperly coded case and if statements. ⚫unique and priority keywords can be placed before an if, case, casez, casex statement.
  • 98.
    unique ⚫A unique keywordperforms following checks: o Each choice of statement is unique or mutually exclusive. o All the possible choices are covered. ⚫A unique keyword causes simulator to perform run time checks and report warning if any of the following conditions are true: o More than one case item matches the case expression. o No case item matches the case expression, and there is no default case
  • 99.
    unique always @ * uniquecase (sel) 2’b00: y=a; 2’b01: y=b; 2’b01: y=c; 2’b10: y=d; 2’b11: y=e; endcase Result : Inputs 00 : 01 : issue d x1 : issue d 11 : Output s y=a; y=b; warnin g Latch; warning y=e;
  • 100.
    unique always @* casez (ip)4’b1??? : y=2’b11; 4’b?1?? : y=2’b10; 4’b??1? : y=2’b01; 4’b???1 : y=2’b00; default: y=2’b00; endcase Synthesis Result: Priority Encoder
  • 101.
    unique always @* unique casez(ip) 4’b1??? : y=2’b11; 4’b?1?? : y=2’b10; 4’b??1? : y=2’b01; 4’b???1 : y=2’b00; default: y=2’b00; endcase Synthesis Result: Encoder
  • 102.
    priority ⚫A priority instructtools that choices should be evaluated in order they occur. ⚫A priority case will cause simulation to report a warning if all possible choices are not covered and there is no default statement. ⚫A priority if will cause simulators to report a warning if all of the if…if else conditions are false, and there is no final else branch.
  • 103.
    priority always @ * prioritycase (sel) 2’b00: y=a; 2’b01: y=b; 2’b01: y=c; 2’b10: y=d; 2’b11: y=e; endcase Result : Inputs 00 : 01 : x1 : issue d 11 : Output s y=a; y=b; Latch; warnin g y=e;
  • 104.
    priority always @ * Result: InputsOutputs priority if (sel==2’b00) y=a; 00 : y=a; else if (sel==2’b01) y=b; 01 : y=b; else if (sel==2’b10) y=c; 10 : y=c; else if (sel==2’b10) y=d; 11 : y=e; else if (sel==2’b11) y=e; 1x : Latch; warning issue d z1 : issu ed Latch; warning
  • 105.
    Procedural Statements ⚫If thereis label on begin/fork then you can put same label on the matching end/join. ⚫User can also put label on other System Verilog end statements such as endmodule, endfunction, endtask, endpackage etc. module test; initial for (int i=0; i<15; i+ +) begin : loop ……………. end : loop endmodul e : test
  • 106.
    Scope and Lifetime ⚫SystemVerilog adds the concept of global scope. Any declaration and definitions which are declared outside module, interface, subprograms etc has a global scope. ⚫These declaration and definitions can be accessed by any scope that lies below the current scope including the current scope. ⚫All global variables have static lifetime i.e. they exist till end of simulation. Global members can be explicitly referred by $root.
  • 107.
    Example int i; //task increment module test; //task decrement initialbegin : label i=5; #6 $root.i=3; #3 increment; #4 decrement; end : label task increment; i+= 1; endtask task decrement; $root.i- =1; endtask
  • 108.
    Scope and Lifetime Futurewiz www.futurewiz.co.i ⚫Localdeclarations and definitions are accessible at scope where they are defined or scopes below it. ⚫By default all the variables are static in a local scope. ⚫These variables can be made automatic. ⚫Static variables can be accessed by hierarchal names.
  • 109.
    Scope and Lifetime ⚫automaticvariables cannot be accessed by hierarchical name. ⚫automatic variables declared in an task, function, or block are local in scope, default to the lifetime of the call or block, and are initialized on each entry to the call or block. ⚫Static variables are initialized only once during the simulation period at the time they are declared. ⚫Advantage of defining variables local to scope is that there is no side effect i.e the variable is getting modified by operations local to it.
  • 110.
    Example1 int i; module test; inti; initial begin int i; for (int i=0; i<5; i+ +) test.i=i ; i=6; end endm //Global Declaration //Local to module //Local to initial block //Local to for loop //Modifies i inside test //Modifies i inside initial
  • 111.
    Example2 int svar1 = 1;optional initial begin for (int i=0; i<3; i++) begin : l1 automatic int loop3 = 0; for (int k=0; k<3; k++) begin : l2 loop3++; $display(loop3); end : l2 // static keyword // executes every loop //loop3 destroyed here end : l1 end Result: 1 2 3 1 2 3 1 2 3
  • 112.
    Example3 initial begin for (inti=0; i<3; i++) begin : l1 static int loop3 = 0; for (int k=0; k<3; k++) begin : l2 loop3++; $display(loop3); end : l2 end : l1 end // executes once //loop3 stays till end of //simulation Result: 1 2 3 4 5 6 7 8 9
  • 113.
    Type Parameter ⚫A parameterconstant can also specify a data type. ⚫This allows modules, interfaces, or programs to have ports and data objects whose type can be set for each instance. module test #( parameter p1=1, parameter type p2= logic) ( input p2 [p1:0] in, output p2 [p1:0] op); p2 [p1:0] x; endmodul e
  • 114.
    Subprograms ⚫Following advancement hasbeen done to System Verilog Subprograms (Functions and Task) : o Default Port Direction : default port is input, unless specified. Following types of ports are allowed: o input : value captured during subprogram call. o output: value assigned at end of subprogram. o inout : value captured at start assigned at the end.
  • 115.
    Subprograms ⚫Following advancement hasbeen done to System Verilog Subprograms (Functions and Task) : o Default Data Type : Unless declared, data types of ports is logic type. o Default Value : Input ports can have default values. If few arguments are not passed, there default values are taken. o begin..end : begin end is no longer required. o Return : return keyword can be used to return value in case of functions and to exit subprogram in case of tasks. o Life Time : Variables can be defined as static or automatic.
  • 116.
    Function and Tasks ⚫BothFunctions and Tasks can have zero or more arguments of type input, output, inout or ref. ⚫Only Functions can return a value, tasks cannot return a value. ⚫A void return type can be specified for a function that is not suppose to return any value. ⚫Functions executes in zero simulation time, where as tasks may execute in non zero simulation time.
  • 117.
    Example1 function int add(int a=0, b=0, c=0); return a + b+ c; endfunction initial begin int y; y=add(3, 5); //3+5+0 #3 y=add(); //0+0+0 #3 y=add(1, 2, 3); //1+2+3 #3 y=add(, 2, 1); //0+2+1 end
  • 118.
    Example2 function void display(int a=0, b=0); $display(“a is %0d b=%0d”, a, b); endfunction //void function initial begin display(3, 5); //a=3 b=5 #3 display(); // a=0 b=0 #3 display(1); // a=1 b=0 #3 display( , 3); // a=0 b=3 end
  • 119.
    Example3 function int initialize(refint a [7:0]); foreach( a[ i ] ) a[ i ]=$rando m; return 1; endfunction int b[7:0], status; initial begin status=initialize(b); #3 void’(initialize(b)); end //same as pointer concept in c // ignore return value
  • 120.
    Example4 //If argument isconst then subprogram cannot modify it function void copy(const ref int a [7:0], ref b [7:0]); foreach( a[ i ] ) b[ i ]=a[ i ]; endfunctio n int a[7:0], b [7:0]; initial begin foreach (a [i] ) a [ i ]=$random; copy(a, b);
  • 121.
    Example5 task check (inta, output b); if (!a) begin b=1; $display(“error” ); return; end b=0; endtask initial begin #3 check(5, error); #3 check(0, error); end // error=0 // error=1
  • 122.
    Example6 task add (inta=0, b=0, output int z); //Variables are static by //default #2 z=a + b; endtask int x, y; initial fork add(3, 5, x); #1 add(2, 4, y); join Resul t : x=6 y=6
  • 123.
    Example6 task add (inta=0, b=0, output int z); //Variables are static by //default #2 z=a + b; endtask int x, y; initial begin add(3, 5, x); #1 add(2, 4, y); Resul t : x=8 y=6
  • 124.
    Example7 task automatic add(int a=0, b=0, output int z); #2 z=a + b; endtask int x, y; initial fork add(3, 5 , x); #1 y=add(2, 4 , y); join Resul t : x=8 y=6
  • 125.
  • 126.
    Introduction Futurewiz www.futurewiz.co.i ⚫System Verilog introducesan object-oriented class data type. ⚫Classes allow objects to be dynamically created, deleted, assigned, and accessed via object handles. ⚫A class is a type that includes data and subroutines (functions and tasks) that operate on that data. ⚫class’s data is referred to as class properties, and its subroutines are called methods.
  • 127.
    Example1 Futurewiz www.futurewiz.co.i class rectangle; int lenght, width; functionint area(); return lenght * width; endfunction function int perimeter(); return 2*(lenght + width); endfunction endclass //class properties //class method //class method
  • 128.
    Example2 Futurewiz www.futurewiz.co.i class person; string name, address; properties intnumber; // class function void set_name(string user); method name=user ; endfunctio n endclass // class
  • 129.
  • 130.
    Objects Futurewiz www.futurewiz.co.i ⚫A class definesa data type. An object is an instance of that class. ⚫An object is created by defining a handler of class type and then calling new function which allocates memory to the object. packet p; p=new(); //p is handler to class packet //Object is constructed ⚫If objects are not created then handler points to null.
  • 131.
    Default Constructor Futurewiz www.futurewiz.co.i ⚫new() isa default constructor which allocates memory and initializes class variables for an object. rectangle rec; initial begin rec=new; int a, p; rec.set_size(3, 5); a=rec.area; //memory allocated to length and width p=rec.perimeter; end
  • 132.
    Constructor endfunctio Futurewiz www.futurewiz.co.i ⚫User candefine customized constructers by writing there own new function inside a class. ⚫The new method is defined as a function with no return type. ⚫It is also possible to pass arguments to the constructor, which allows run-time customization of an object. function new (int x=0, y=0); length=x; width=y;
  • 133.
    Example Futurewiz www.futurewiz.co.i class rectangle; int lenght, width; function new(int x=1,y=1);..... functionint area(); ............. function int perimeter(); .......... rectangle r1, r2, r3; int a1, a3, p1; initial begin r1=new(3, 5); r2=new(4); a1=r1.area; p1=r2.perimete r; a3=r3.area; //error r3 is null end
  • 134.
    Parameterized Class • classpacket #(number=10, type dtype= bit); dtype data [number]; • function void randomize(); foreach(data[i]) data[i]=$random; endfunction • function void display(); • foreach(data[i]) $display(“data[%0d”]=%0d”, i, data[i]); endfunction • endclass Futurewiz www.futurewiz.co.i
  • 135.
    Parameterized Class Futurewiz www.futurewiz.co.i packet p1; packetp2#(20); packet p3#( , int); packet p4#(30, bit [3:0]); initial begin p1=new(); p2=new(); p4.display; p4.randomize; p4.display; //number=10, dtype=bit //number=20, dtype=bit //number=10, dtype=int //number=30, dtype=bit [3:0] p3=new() ; p4=new() ;
  • 136.
    This Futurewiz www.futurewiz.co.i ⚫The this keywordis used to unambiguously refer to class properties or methods of the current instance. int a; function new(int a); a=a; endfunction endclass ⚫The this keyword shall only be used within non- static class methods, otherwise an error shall be issued. class example; Now a is property of class as well as argument of function new. SV will look in local scope to resolve reference to a, which in this case is subroutine argument.
  • 137.
    This Futurewiz www.futurewiz.co.i class example; int a; function new(int a);this.a=a; endfunction endclass ⚫To solve this issue this keyword is used which now refers to property a in current class instance. example x, y; initial begin x=new(5); y=new(3); $display(x.a) ; $display(y.a) ; end
  • 138.
    Fundamental Principles ofOOP Futurewiz www.futurewiz.co.i ⚫Encapsulation o It’s a concept that binds together the data and functions that manipulate the data. o Encapsulation keeps both data and function safe from outside world i.e. data hiding. ⚫Abstraction o Abstraction is the concept of moving the focus from the details and concrete implementation of things, to the types of things, the operations available thus making the programming simpler, more general.
  • 139.
    Fundamental Principles ofOOP the function. Futurewiz www.futurewiz.co.i ⚫Inheritance o New classes are created by inheriting properties and method defined in an existing class. o Existing class is called the base class(parent class), and the new class is referred to as the derived class(child class). ⚫Polymorphism o polymorphism means having many forms. o A member function will cause a different function to be executed depending on the type of object that
  • 140.
    Inheritance Futurewiz www.futurewiz.co.i ⚫Inheritance allows userto create classes which are derived from other classes. ⚫The derived class (child class) inherits all the properties and methods defined in base class (parent class). ⚫Additional properties and methods can be defined in child class. ⚫properties and methods defined in base class can be overridden by redefining them in child class. This phenomenon is called as overriding.
  • 141.
    Example1 Futurewiz www.futurewiz.co.i class parent; int a,b; task display(); $display(“Paren t Class”); endtask endclas s class child extends parent; int c; task print(); $display(“Child Class”); endtask endclass
  • 142.
  • 143.
    Example2 Futurewiz www.futurewiz.co.i class parent; int a, b; task display(); $display(“Paren tClass”); endtask endclas s class child extends parent; int a; task display(); $display(“Child Class”); endtask endclas s Display method and property a is overridden in child class
  • 144.
  • 145.
    Example3 endclas s Futurewiz www.futurewiz.co.i class parent; int a; task display(); $display(“Paren t Class”); endtask endclas classchild extends parent; int a, b; task display(); $display(“Child Class”); super.display; $display(super.a); endtask ⚫A super keyword can be used to access properties and methods defined in parent class from a child class.
  • 146.
    Example3 parent p; child c; initial begin p=new; c=new; p.a=5; c.a=6; p.display ; c.display ;end parent p a=5 ; Futurewiz www.futurewiz.co.i child c a=6 ; b=0; Parent Class Child Class Parent Class 0
  • 147.
    Inheritance Futurewiz www.futurewiz.co.i ⚫Every time whenchild object is created, constructer of parent (super.new) is called first implicitly. ⚫If a new function has been defined in parent which accepts a set of arguments and arguments don’t have default values. In such a case super.new has to be explicitly specified with required arguments. ⚫It is because of this reason that child class is able to access properties and methods defined in parent class.
  • 148.
    Example4 Futurewiz www.futurewiz.co.i class parent; function new(); $display(“Paren t Class”); endfunctio nendclass initial begin child c; c=new ; end class child extends parent; function new(); $display(“Child Class”); endfunction endclass Parent Class Child Class
  • 149.
    Example5 Futurewiz www.futurewiz.co.i class parent; function new(string str); $display(str) ; endfunction endclass initial begin child c; c=new classchild extends parent; function new(); $display(“Child Class”); endfunction endclass Error super.new is not called
  • 150.
    Example6 Futurewiz www.futurewiz.co.i class parent; function new(string str=“ ”); $display(str) ; endfunction endclass initialbegin child c; c=new class child extends parent; function new(); $display(“Child Class”); endfunction endclass en d Child Class No error, parent constructor has default value
  • 151.
    Example7 Futurewiz www.futurewiz.co.i class parent; function new(string str); $display(str) ; endfunction endclass initial begin child c; c=new classchild extends parent; function new(); super.new(“Pare nt Class”); $display(“Child Class”); endfunctio n ePnadrcela
  • 152.
    Example8 •class rectangle; int length, width; •functionnew(int x, y); this.length=x; this.width=y; endfunction •function int area(int x, y);.... function int perimeter(int x, • y);... Futurewiz www.futurewiz.co.i class square extends rectangle; int size; function new(int size); this.size=size; super.new(size, size); endfunction endclas s square sq= new(5); sq.area; sq.perimete r;
  • 153.
    Encapsulation members can alsobe accessed by child class.Futurewiz www.futurewiz.co.in ⚫Till now classes have members which were accessible to rest of the program. However in many situation such functionality are not desired. ⚫Example: In cars we are not concerned by how engine works but we our focus is how to control it. ⚫System Verilog provides various ways of hiding class members: o local keyword will ensure that the members are available only to the method of the same class. o protected keyword is similar to local keyword but
  • 154.
    Example1 Futurewiz www.futurewiz.co.i class rectangle; int length, width; functionnew(int x, y); this.length=x; this.width=y; endfunction function int area; …. endclass rectangle rec; initial begin rec=new(2, 3); rec.area; rec.length=5; //length is modified rec.area; en d
  • 155.
    Example2 Futurewiz www.futurewiz.co.i class rectangle; local intlength, width; function new(int x, y); this.length=x; this.width=y; endfunction function int area; …. en d endclass rectangle rec; initial begin rec=new(2, 3); rec.area; rec.length=5; rec.area; // error
  • 156.
    Example3 Futurewiz www.futurewiz.co.i class rectangle; local intlength, width; function new(int x, y); this.length=x; this.width=y; endfunction function int area; …. endclas s class square extends rectangle; function new (int x); super.new(x, x); endfunction endclas s square sq; initial sq=new(3); Error length and width are local to class rectangle
  • 157.
    Example4 squar e Futurewiz www.futurewiz.co.i class rectangle; protected intlength, width; function new(int x, y); this.length=x; this.width=y; endfunction function int area; …. endclass class square extends rectangle; function new (int x); super.new(x, x); endfunctio n endclass square sq; initial sq=new(3); Now length and width are accessible to both rectangle and
  • 158.
    Lifetime in Class Futurewiz www.futurewiz.co.i ⚫Bydefault properties and methods defined inside a class have automatic lifetime. ⚫Memory to properties are allocated dynamically when a new instance of the class is created. ⚫User can define properties and methods as static. A static property is a class variable that is associated with the class, rather than an instance of the class.
  • 159.
    Lifetime in Class Futurewiz www.futurewiz.co.i ⚫Memoryto static properties and methods are allocated during elaboration time. ⚫Scope resolution operator ( :: ) can be used to access static property and methods defined inside a class. ⚫Static properties and methods can be accessed without creating any instance of a class.
  • 160.
    Example1 Futurewiz www.futurewiz.co.i packet p1, p2,p3; class packet; static int id; initial begin int val; //default: automatic p1=new; $display(p1.id, p1.val); function new(); id++; val++; endfunctio n endclas s p2=new; $display(p2.id, p2.val); p3=new; $display(p3.id, p3.val); p2.id=7; p2.val=3; $display(p1.id, p1.val); $display(p2.id, p2.val); $display(packet :: id); end
  • 161.
  • 162.
    Example2 Futurewiz www.futurewiz.co.i class packet; static intid; int val; //default: automatic function new(); id=id+1; val=val+1; endfunction endclas s initial begin packet:: id=3; $display(packet::id ); packet p1; p1=new; $display(packet::id ); end Resul t id=3; id=4 ;
  • 163.
    Functions and Tasks Futurewiz www.futurewiz.co.i ⚫Taskand Functions defined inside class have automatic lifetime for their arguments and variables. ⚫A static keyword can be added after Task/Function to make arguments and variables static in nature. ⚫A function prototype can be declared inside a class and body can be defined outside class with help of extern keyword.
  • 164.
    Example1 Futurewiz www.futurewiz.co.i class test; task increment; int i; i++; $display(“i=%d”, i); endtask endclass initialbegin test t1; t1=new; t1.incremen t; t1.incremen t; t1.incremen t; end Resul t : i=1 i=1 i= 1
  • 165.
    Example2 Futurewiz www.futurewiz.co.i class test; task increment; static int x; inty; x+ +; y++; $display(“x=%d y=%d”, x, y); endtask endclass initial begin test t1; t1=new; t1.incremen t; t1.incremen t; t1.incremen t; end Result: x=1 y=1 x=2 y=1 x=3 y=1
  • 166.
    Example3 endclas s Futurewiz www.futurewiz.co.i class test; task static increment;int x; int y; x+ +; y++; $display(“x=%d y=%d”, x, y); endtask initial begin test t1; t1=new; t1.incremen t; t1.incremen t; t1.incremen t; end Result: x=1 y=1 x=2 y=2 x=3 y=3
  • 167.
    Example4 Futurewiz www.futurewiz.co.i class test; task static increment; intx; automatic int y; x++; y++; $display(“x=%d y=%d”, x, y); endtask endclass initial begin test t1; t1=new; t1.incremen t; t1.incremen t; t1.incremen t; end Result: x=1 y=1 x=2 y=1 x=3 y=1
  • 168.
    Example5 Futurewiz www.futurewiz.co.i class rectangle; local intlength, width; extern function new(int x, y); extern function int area(); endclass function rectangle :: new(int x, y); this.length= x; this.widht=y; endfunction function int rectangle::area(); return length*width; endfunction
  • 169.
    Functions and Tasks Futurewiz www.futurewiz.co.i ⚫Functions and Tasks can be local as well as protected. ⚫ Functions and Tasks can also be declared as static. The lifetime of variables inside static methods are automatic by default. ⚫ Memory to static methods are allocated during elaboration time. ⚫ A static methods can only access static members of a class. ⚫ A static method can be called without creating instance of a class. They can be accessed by scope resolution operator(::).
  • 170.
    Example1 Futurewiz www.futurewiz.co.i class test; int i; localfunction void increment; i++; $display(“i= %0d”, i); endtask function void inc; increment; endfunction endclass initial begin test t1; t1=new; t1.inc; t1.inc; // t1.increme nt; will give //compilation error end Resul t : i=1 i=2
  • 171.
    Example2 endclas s Futurewiz www.futurewiz.co.i class test; staticfunction int add(int x, y); int i; i+ +; $di spl ay(“ i= %0 initial begin $display(test::add(3,2)) ; $display(test::add(1,1)) ; end Result: 5 i=1 2 i=1
  • 172.
    Example3 endclas s Futurewiz www.futurewiz.co.i class test; inti; static function int add(int x, y); i++; $display(“i=%0d”, i); return x + y; endfunctio n initial begin $display(test::add(3,2)) ; $display(test::add(1,1)) ; end Result : Error, Static function cannot access non-static class properties
  • 173.
    Example4 •class test; •static inti; • static function int add(int x, y); •i++; •$display(“i=%0d”, i); return x + y; •endfunction endclas s Futurewiz www.futurewiz.co.i initial begin $display(test::add(3,2)) ; $display(test::add(1,1)) ; end Result: 5 i=1 2 i=2
  • 174.
    Polymorphism Futurewiz www.futurewiz.co.i ⚫Polymorphism is anability to appear in many forms. ⚫In OOPS multiple routines sharing a common name is termed as Polymorphism. ⚫In SV, Polymorphism allows a parent class handler to hold sub class object and access the methods of those child classes from the parent class handler. ⚫To achieve this, functions/tasks in SV are declared as virtual functions/tasks which allow child classes to override the behaviour of the
  • 175.
    Example1 Futurewiz www.futurewiz.co.i class shape; protected x,y, z; virtual function void display(); $display(“I am shape”); endfunction //Main Class //Function call can be // overridden, will call //child function instead virtual function void perimeter(); $display(“I don’t know perimeter”); endfunction endclass
  • 176.
    Example1 Futurewiz www.futurewiz.co.i class rectangle extends shape;virtual function void display(); $display(“I am rectangle”); endfunction virtual function void perimeter(); $display(“perimeter=%0d”, 2*(x + y)); endfunction function new (int x, y); ..... endclass
  • 177.
    Example1 Futurewiz www.futurewiz.co.i class square extends rectangle;//This function call //cannot be overridden function void display(); $display(“I am square”); endfunction function void perimeter(); $display(“perimeter=%0d”, 4*x); endfunction function new (int x); ..... endclass
  • 178.
    Example1 Futurewiz www.futurewiz.co.i class triangle extends shape;function void display(); $display(“I am a triangle”); endfunction function void perimeter(); $display(“perimeter=%0d”, (x + y + z)); endfunction function new (int x, y, z); ..... endclass
  • 179.
    Example1 Futurewiz www.futurewiz.co.i shape s1, s2; rectangle r1,r2;square sq1; triangle t1; initial begin s1=new; r1=new(2, 3); sq1=new(4); t1=new(1, 2, 3); s1.display ; r1.display ; t1.display; s2=t1; s2.display ; r2=sq1; r2.display ; s2=r1; s2.display s1.perimete r; r1.perimeter ; t1.perimeter ; s2. perimeter; r2. perimeter; s2. perimeter;
  • 180.
    Example1 Futurewiz www.futurewiz.co.i Result : I don’t know Iam shape perimete r I am rectangle I am triangle I am triangle I am square I am Perimeter= 10 Perimeter= 6 Perimeter= 6 Perimeter= 16 Perimeter= 10
  • 181.
    Example2 •class parent; int a=3; •functionvoid d1(); •$display(“Parent d1”); endfunction •virtual function void d2(); •$display(“Parent d2”); endfunction •endclass • class child extends parent; • int b=8; • function void d1(); • $display(“Child d1”); • endfunction • function void d2(); • $display(“Child d2”); • endfunction endclas s Futurewiz www.futurewiz.co.i
  • 182.
    Example2 Futurewiz www.futurewiz.co.i initial begin parent p1;child c1; c1=new; $cast(p1, c1); //p1=c1; // checks run-time casting errors //checks compile time casting errors //properties and virtual methods in parent class //points to one defined in child class p1.d1; p1.d2; $display(“p1.a=%0d”, p1.a); c1.a=9; $display(“p1.a=%0d”,
  • 183.
    Example2 Result : Parent d1 Child d2 p1.a=5 p1.a=9 parent pchild c null a : inherited b : local; d1 : inherited; d2 : inherited; d1 : overridden; d2 : overridde n; parent p after p1=c1; parent points to child memory for inherited properties and virtual methods child c a : inherited b : local; d1 : inherited; d2 : inherited; d1 : overridden; d2 : overridde n; Futurewiz www.futurewiz.co.i
  • 184.
    Example3 •class parent; int a=3; •functionvoid d1(); •$display(“Parent d1”); endfunction •virtual function void d2(); •$display(“Parent d2”); endfunction •endclass • class child extends parent; • int a=5; b=8; • function void d1(); • $display(“Child d1”); • endfunction • function void d2(); • $display(“Child d2”); • endfunction endclas s Futurewiz www.futurewiz.co.i
  • 185.
    Example3 Futurewiz www.futurewiz.co.i initial begin parent p1;child c1; c1=new; p1=c1; //Polymorphism occurs //c1=p2; will give compilation error p1.d1; p1.d2; $display(“p1.a=%0d”, p1.a); c1.a=9; $display(“p1.a=%0d”, p1.a); end
  • 186.
    Example3 Result : Paren t d1 Child d2 p1.a=3 p1.a=3 Modifying parent’sa will not modify child’s a since it is overridden in parent p child c null a : inherited a : overridden b : local; d1 : inherited; d2 : inherited; d1 : overridden; d2 : overridde n; parent p after p1=c1; child c a : inherited a : overridden b : local; d1 : inherited; d2 : inherited; d1 : overridden; d2 : overridde n; child . Futurewiz www.futurewiz.co.i
  • 187.
    Abstraction Futurewiz www.futurewiz.co.i ⚫Sometimes, it isuseful to create a class without intending to create any objects of the class. ⚫The class exists simply as a base class from which other classes can be derived. ⚫In System Verilog this is called an abstract class and is declared by using the word virtual. ⚫A virtual class object can not be constructed but handle to the virtual class can be defined.
  • 188.
    Abstraction Futurewiz www.futurewiz.co.i ⚫Virtual methods canbe declared without any body. ⚫These methods can be overridden in a derived class. ⚫The method overriding virtual method should have same signature i.e. (return type, number and type of arguments) must be the same as that of the virtual method. ⚫If a virtual method is defined as pure then these methods must be defined in child classes. A pure virtual method forces child classes to implement standard set of methods.
  • 189.
    Example1 Futurewiz www.futurewiz.co.i virtual class abstract; //Abstract Class virtual task display(); //VirtualMethod //Body not defined function int increment(int x); return x + 1; endfunctio n endclass
  • 190.
    Example1 endclas s Futurewiz www.futurewiz.co.i class abc extends abstract; task display(); defined $display(“abc”) ;endtask // display may or may not be function int increment(int x); //Overriding return x + 2; endfunction
  • 191.
    Example1 Futurewiz www.futurewiz.co.i class xyz extends abstract; task display(); defined $display(“xyz”) ;endtask // display may or may not be //Increment function may not be defined endclass
  • 192.
    Example1 Futurewiz www.futurewiz.co.i abstract ab; abc a; xyzx; int p1, p2; initial begin //ab=new; not allowed //will give compilation error a=new;x=new; a.display; x.display; p1=a.increment(2); p2=x.increment(5); ab=x; ab.display; ab=a; ab.display; end Results: abc 4 xyz xyz 6 abc
  • 193.
    Example2 Futurewiz www.futurewiz.co.i virtual class abstract; //Abstract Class pure virtualtask display(); //Pure Virtual Method virtual function int increment(int x); //Virtual Function //Body may not be defined endclass
  • 194.
    Example2 Futurewiz www.futurewiz.co.i class abc extends abstract; taskdisplay(); $display(“abc”) ; endtask //display method needs to be defined //will give compilation error if not defined function int increment(int x); return x + 2; endfunctio n //Increment function may // or may not be defined endclas s
  • 195.
    Nested Class Futurewiz www.futurewiz.co.i ⚫A classcan contain instance of another class using handle to an object. Such classes are called as Nested Classes. ⚫Common reasons for using containment are reuse and controlling complexity. class Node; Node left, right; //properties and methods for Node endclass
  • 196.
  • 197.
    Example Futurewiz www.futurewiz.co.i class packet; int data[7:0]; timestat t; function new;t=new; endfunction extern task transmit; endclass task packet :: transmit(); t.start; //do some operation t.end; endtask
  • 198.
    Typedef Class Futurewiz www.futurewiz.co.i ⚫A forwarddeclaration is a declaration of a object which the programmer has not yet given a complete definition. ⚫System Verilog language supports the typedef class construct for forward referencing of a class declaration. ⚫This allows for the compiler to read a file from beginning to end without concern for the positioning of the class declaration.
  • 199.
  • 200.
    Example Futurewiz www.futurewiz.co.i module test; typedef class timestat; class packet; timestatt; // definitions endclass class timestat; // definitions enclass typedef allows compiler to process packet class before timestat class.
  • 201.
    Copy Futurewiz www.futurewiz.co.i ⚫User can makea copy of an object to keep a routine from modifying the original. ⚫There are two ways of copying an object: o Using built-in copy with new function (Shallow Copy) o Writing your own complex copy function (Deep Copy) ⚫Using new to copy an object is easy and reliable. A new object is constructed and all variables from the existing object are copied.
  • 202.
    Shallow Copy Futurewiz www.futurewiz.co.i class pkt; bitaddr [15:0]; bit [7:0] data; int status; function new(); addr=$randomiz e; data=$randomiz e; status=0; endfunction endclass pkt src, dst; initial begin src=new; dst=new src; end //create object //copy to dst src dst addr=5 ; addr=5 ; data=10; data=10; status=0; status=0;
  • 203.
    Shallow Copy Futurewiz www.futurewiz.co.i ⚫Shallow copyis similar to photocopy, blindly copying values from source to destination. ⚫If a class contains handle to another class then only top level objects are copied by new, not the lower one. ⚫When using new to copy objects, the user define new constructer is not called. New function just copies the value of variables and object handle.
  • 204.
    Example Futurewiz www.futurewiz.co.i class pkt; bit addr[15:0]; bit [7:0] data; int id; static int count; timestat t; function new(); id=count++; t=new; endfunction endclass class timestat; time start_time, end_time; endclass
  • 205.
    Example packet src, dst; initialbegin src=new; src.t.start_time=1 0; dst=new src; //handle of t is copied //id is not incremented dst.t.start_time=1 4; //modifies t since // handler is common end src id=1 ; dst id=1 ; t start_time=14 ; Futurewiz www.futurewiz.co.i
  • 206.
    Deep Copy Futurewiz www.futurewiz.co.i ⚫User canwrite his own deep copy function. ⚫This user defined copy function should copy the content of class handle, not handle itself.
  • 207.
    Example Futurewiz www.futurewiz.co.i class pkt; bit addr[15:0]; bit [7:0] data; int id; static int count; timestat t; function new(); id=count++; t=new; endfunction extern function pkt copy; endclass function pkt pkt :: copy; copy=new; copy.addr=this.addr; copy.data=this.data; copy.t.start_time=this.t.start_ ti me; copy.t.end_time=this.t.end_ti m e; endfunction
  • 208.
    Example initial begin pkt src, dst; src=new; src.t.start_time= 3;dst=src.copy; dst.t.start_time= 7; end src id=1 ; dst id=2 ; t start_time=3 ; t start_time=7 ; Futurewiz www.futurewiz.co.i
  • 209.
    Interface Class Futurewiz www.futurewiz.co.i ⚫ Aset of classes can be created that have a common set of behaviors. This set is called Interface class. ⚫ An interface class can only contain pure virtual functions, type declaration and Parameter declarations. ⚫ Pure functions are function that don’t have any implementation. ⚫ implements keyword is used to define a class that implements function defined in interface class. ⚫ When interface class is implemented then nothing is extended, implementation of pure virtual function is defined in class that implements interface class.
  • 210.
    Interface Class Futurewiz www.futurewiz.co.i interface classshape #(type id=int); int a; pure virtual function id area(id x=0, y=0); pure virtual function id perimeter(id x=0, y=0); endclass
  • 211.
    Interface Class Futurewiz www.futurewiz.co.i class int_rectangleimplements shape #(int); virtual function int area(int x=0, y=0); return x*y; endfunction //virtual keyword //compulsory virtual function int perimeter(int x=0, y=0); return 2*(x+y); endfunction //a defined in interface class cannot be accessed endclass
  • 212.
    Interface Class Futurewiz www.futurewiz.co.i class real_rectangleimplements shape #(real); virtual function real area(real x=0, y=0); return x*y; endfunction virtual function real perimeter(real x=0, y=0); return 2*(x+y); endfunction endclass
  • 213.
    Singleton Class Futurewiz www.futurewiz.co.i class singleton; int a; static singletonobj; local function new (int a); this.a=a; endfunction //static function endclass static function singleton create(int a); if (obj==null) obj=new(a); return obj; endfunctio n initial begin singleton s1; ⚫These are classes that restricts instantiation of class to just one object.
  • 214.
    Semaphore Futurewiz www.futurewiz.co.i ⚫ Semaphore isa built-in class which conceptually is a bucket. ⚫ When semaphore is allocated, then a bucket containing fixed number of keys is created. ⚫ Process using semaphore must first procure a key from bucket before they can continue to execute. ⚫ Once process is over, key should be returned back to the bucket. ⚫ Semaphore is basically used to control access to shared resources.
  • 215.
    Semaphore - Methods Futurewiz www.futurewiz.co.i ⚫new()method is used to create semaphore with specified number of keys. Default key count is 0. ⚫put() method is used to return specified number of keys to semaphore. Default value is 1. ⚫get() method is used to procure specified number of keys from semaphore. Default value is 1.
  • 216.
    Semaphore - Methods Futurewiz www.futurewiz.co.i ⚫Inget() method if the specified number of keys is not available, the process blocks until the keys become available. ⚫try_get() method is used to procure a specified number of keys from a semaphore, but without blocking. ⚫In try_get() method if the specified number of keys are not available, the method returns 0 else a positive value and continues.
  • 217.
    Example semaphore smp; int got=0; initialbegin smp=new(5); #5 smp.get(3); #6 smp.get(1); got=got +1; #2 if(smp.try_get(3)) got=got +1; end initia l begi n #8 smp. get(2 ); #7 smp. Futurewiz www.futurewiz.co.i
  • 218.
    Example Futurewiz www.futurewiz.co.i module test; semaphore smp; inta=0; smp=new(1); initial fork //statement1 // statement2 join begin : statement1 smp.get; a=7; #3 smp.put; end statement1 begin : statement2 smp.get; a=3;
  • 219.
    Mailbox Futurewiz www.futurewiz.co.i ⚫Mailbox is abuilt-in class that allows messages to be exchanged between processes. ⚫Data can be sent to mailbox by one process and retrieved by another. ⚫Mailbox can be bounded or unbounded queues. ⚫Mailbox can be parameterized or Non-parameterized. ⚫Non-Parameterized mailboxes are typeless , that is single mailbox can send and receive different type of data.
  • 220.
    Mailbox - Methods Futurewiz www.futurewiz.co.i ⚫new()method is used to create mailbox with size specified as an argument. ⚫If size is defined as 0 (default) then mailbox is unbound. ⚫num() method is returns the number of message currently present inside mailbox. ⚫put() method places a message in a mailbox in a FIFO order. ⚫If the mailbox is bounded, the process shall be suspended until there is enough room in the queue.
  • 221.
    Mailbox - Methods Futurewiz www.futurewiz.co.i ⚫try_put()method attempts to place a message in mailbox. This method is meaningful only for bounded mailboxes. ⚫If mailbox is full this method returns 0 and message is not placed else it returns 1 and message is placed. ⚫get() method retrieves a message from a mailbox. ⚫This method removes message from a mailbox and calling process is blocked if mailbox is empty. ⚫try_get() method attempts to retrieves a message from a mailbox without blocking.
  • 222.
    Mailbox - Methods Futurewiz www.futurewiz.co.i ⚫peek() method copies message from a mailbox without removing message from the queue. ⚫ If mailbox is empty then current process is blocked till a message is placed in the mailbox. ⚫ If the type of the message variable is not equivalent to the type of the message in the mailbox, a run-time error is generated. ⚫ try_peek() method attempts to copy a message from a mailbox without blocking. If the mailbox is empty, then the method returns 0 else if variable type is different it returns negative number else positive number is returned.
  • 223.
    Parameterized Mailboxes Futurewiz www.futurewiz.co.i ⚫By defaultmailboxes are typeless. They can send and receive different data types. This may lead to runtime errors. ⚫Mailbox type can be parameterized by passing type as a argument. mailbox #(string) mbox; ⚫In parameterized mailboxes, tools catches type mismatch errors at compilation time.
  • 224.
    Example Futurewiz www.futurewiz.co.i module test; mailbox mb; //typeless Mailbox string s; int i;initial begin mb=new(); //Unbound Mailbox $monitor(“s=%s and i=%0d at time=%0d”, s, i, $time); fork gen_data; rec_data; join end endmodul e
  • 225.
    Example Futurewiz www.futurewiz.co.i task gen_data; mb.put(“Hello” ); #3 mb.put(7); #4 mb.put(“Test”); #3mb.put(3); #3 mb.put(“Hi”); #2 mb.put(9); endtask task rec_data; #1 mb.peek(s); #2 mb.get(s); #2 mb.get(i); #1 mb.peek(s); #2 void’(mb.try_g et(s)); #1 void’(mb.try_g et(i));
  • 226.
    Example Futurewiz www.futurewiz.co.i Result: # s= andi=0 at time=0 # s=Hello and i=0 at time=1 # s=Hello and i=7 at time=5 # s=Test and i=7 at time=7 # s=Test and i=3 at time=16
  • 227.
    Example Futurewiz www.futurewiz.co.i module test; mailbox #(int) mb; inti; initial begin mb=new(3) ; //Parameterized Mailbox //bound mailbox $monitor(“i=%0d at %0d”, i , $time); fork gen_data; rec_data; join end endmodul e
  • 228.
    Example Futurewiz www.futurewiz.co.i task gen_data; mb.put(1); #1 mb.put(7); #1 mb.put(4); #2mb.put(3); #2 void’(mb.try _put(2)); #10 mb.put(5); #2 mb.put(6); task rec_data; #1 mb.peek(i); #5 mb.get(i); #2 mb.get(i); #2 void’(mb.try_ get(i)); #1 mb.get(i); #2 void’(mb.try_ get(i));
  • 229.
    Example Futurewiz www.futurewiz.co.i Result: # i=0 attime=0 # i=1 at time=1 # i=7 at time=8 # i=4 at time=10 # i=3 at time=11 # i=2 at time=13 # i=5 at time=18
  • 230.
  • 231.
    Why Randomize? Futurewiz www.futurewiz.co.i ⚫As designsgrow it becomes more difficult to verify their functionally through directed test cases. ⚫Directed test cases checks specific features of a design and can only detect anticipated bugs. ⚫Verifying your design using this approach is a time consuming process. ⚫Randomization helps us detecting bugs that we do not expect in our design.
  • 232.
    Comparison Directed o Verifies specific scenarios. o Time Consuming. oLinear progress. Futurewiz www.futurewiz.co.i Random o Broader Coverage. o TB’s are easy to write. o Tests are redundant. o Takes longer time to achieve functionality. Constrained Random o Broad and Deep o Tests are more productive o Finds corner cases o Constrained to achieve
  • 233.
    What to Randomize? Futurewiz www.futurewiz.co.i ⚫Deviceconfiguration ⚫Environment configuration ⚫Primary input data ⚫Encapsulated input data ⚫Protocol exceptions ⚫Errors and violations ⚫Delays ⚫Test order ⚫Seed for the random test
  • 234.
  • 235.
    Random in range Futurewiz www.futurewiz.co.i moduletest; integer a, b, c; initial repeat(20) begin a=$random % 10; b={$random} % 20; c=$unsigned($random) %15; range) //-9 to 9 (Random range) //0 to 19 (Random range) //0 to 14 (Random
  • 236.
    module test; integer a,b, c; initial repeat(20) begin a=10 + {$random} % 6; Futurewiz www.futurewiz.co.i //10 to 15 (positive range) b=-5 - {$random} % 6; //-5 to -10 (negative range) c =-5 + {$random} % 16; //-5 to 10 (mix range) #2; end endmodule Random in range
  • 237.
    Algorithms • Positive Range: •result= min + {$random} % (max – min + 1); • Negative Range: • result= -min - {$random} % (max – min + 1); • Mix Range: • result= -min + {$random} % (max + min + 1); • //min is the magnitude of minimum number • //max is the magnitude of maximum number Futurewiz www.futurewiz.co.i
  • 238.
    module test; integer a; initial repeat(20 ) if ({$rando m} %2) #2 a=10 + {$random} % 6; else Futurewiz www.futurewiz.co.i //10 to 15 // 3 to 7 Random between ranges
  • 239.
    module test; integer a, count=0; alwaysif(count< 10) #2 count=count+1; else #2 count=0; initial repeat(20) if (count<3) Futurewiz www.futurewiz.co.i //1 to 9 // 11 to 18 Higher weight #2 a=1 + {$random} % 9; else #2 a=11 + {$random} % 8; endmodule Weighted Random numbers
  • 240.
    module test; reg sign;reg [7:0] exp; reg [22:0] mantisa; real a; initial repeat(20) begin sign=$random; exp=$random; mantisa=$random; a=$bitstoshortreal({sign, exp, mantisa}); #2; end Futurewiz www.futurewiz.co.i Real random numbers
  • 241.
    while(index!=10) begin temp=$random; begin: loop for(i=0; i<index; i=i+1) if(rec[i]==temp) disableloop; rec[index]=temp; index=index + 1; num=temp; #2; end Futurewiz www.futurewiz.co.i Generate 10 unique random numbers integer rec [0:9]; integer i, temp, num, index=0; initial begin $monitor(“num=%0d”, num); Unique random numbers
  • 242.
    Result Futurewiz www.futurewiz.co.i # num=303379748 # num=- 1064739199# num=-2071669239 # num=- 1309649309 # num=112818957 # num=1189058957 # num=- 1295874971 # num=-1992863214 # num=15983361
  • 243.
    while(index!=10) begin temp={$random} % 100; begin:loop for(i=0; i<index; i=i+1) if(rec[i]==temp) disable loop; rec[index]=temp; index=index + 1; rand=temp; #2; end Futurewiz www.futurewiz.co.i Generate 10 unique random numbers between 0 to 99 integer rec [0:9]; integer i, temp, rand, index=0; Unique random numbers
  • 244.
  • 245.
    ⚫Verilog also offersfew more randomization system functions apart from $random. They can be categorized as following: o$dist_uniform (seed, start, end) o$dist_normal (seed, mean, standard_deviation) o$dist_exponential (seed, mean) o$dist_poisson (seed, mean) o$dist_chi_square (seed, degree_of_freedom) o$dist_t (seed, degree_of_freedom) o$dist_erlang (seed, k_stage, mean) Futurewiz www.futurewiz.co.i Other types
  • 246.
    module test; integer num1,num2, seed; initial repeat(20) begin num1=$dist_uniform (seed, 5, 15); num2=$dist_uniform (seed, -5, 10); 10 #2; end endmodul Futurewiz www.futurewiz.co.i //5 to 15 //-5 to $dist_uniform
  • 247.
  • 248.
    module test; integer num1,num2, seed; initial repeat(20) begin #2 num1=$urandom (seed); Futurewiz www.futurewiz.co.i //Unsigned 32- bit //Random Number num2=$urando m; end endmodule $urandom
  • 249.
    module test; integer num1,num2 , num3; Futurewiz www.futurewiz.co.i initial repeat(20) begin #2 num1=$urandom_range(35, 20); num2=$urandom_range(9); num3=$urandom_range(10,15); end endmodule //35:max to 20:min //9:max to 0:min //10:min to 15:max $urandom_range
  • 250.
    Result Futurewiz www.futurewiz.co.i # num1=27 num2=8 num3=10# num1=32 num2=0 num3=11 # num1=26 num2=0 num3=14 # num1=29 num2=0 num3=13 # num1=21 num2=6 num3=12 # num1=25 num2=4 num3=10 # num1=20 num2=7 num3=12 # num1=23 num2=2 num3=12 # num1=33 num2=2 num3=13 # num1=22 num2=1 num3=11 # num1=34 num2=8 num3=14 # num1=24 num2=2 num3=15
  • 251.
    ⚫SV provides scoperandomize function which is used to randomize variables present in current scope. ⚫randomize() function can accept any number of variables which have to be randomized as an arguments. ⚫This function returns true if randomization was successful else false. ⚫User can also provide inline constraints to control range of Futurewiz www.futurewiz.co.i Randomize function
  • 252.
    module test; integer num1,num2; initial repeat(20) begin if(randomize(num1, num2)) num2 endmodul e Futurewiz www.futurewiz.co.i //Randomize num1 and $display(“Randomization Successful”); else $display(“Randomization Failed”); #2 ; end Randomize function
  • 253.
  • 254.
  • 255.
    Randomize Object Properties Futurewiz www.futurewiz.co.i ⚫InSV properties (variables) inside a class can also be randomized. ⚫Variables declared with rand and randc are only considered for randomization. ⚫A class built-in randomize function is used to randomized rand and randc variables. ⚫User can also specify constraint blocks to constrain random value generation.
  • 256.
    rand vs randc Futurewiz www.futurewiz.co.i ⚫Variables defined with rand keyword, distribute values uniformly. rand bit [1:0] num1; num1: 3, 2 , 0, 3, 0, 1, 2, 1, 3 ⚫ Variables defined with randc keyword, distribute values in a cyclic fashion without any repetition within an iteration. randc bit [1:0] num2; num2 : 3, 2, 0, 1 0, 2, 1, 3 1, 3, 0, 2
  • 257.
    program test; sample sm; initial begin sm=new; repeat(20) assert(sm.ra ndomize()) Futurewiz www.futurewiz.co.i classsample; rand int num1; int num2; endclass //assert checks randomization status $display(“num1=%0d num2=%0d”, sm.num1, sm.num2); end endprogram num1 is randomized num2 remains untouched Example1
  • 258.
    Result Futurewiz www.futurewiz.co.i # num1=- 1884196597 num2= 0 # num1=-326718039num2= 0 # num1=1452745934 num2=0 # num1=- 2130312236 num2= 0 # num1=1572468983 num2=0 # num1=131041957 num2=0 # num1=1115460554 num2=0 # num1=-818992270 num2= 0 # num1=2000525113 num2=0 # num1=1547354947 num2=0
  • 259.
    program test; main m; initial begin m=new; repeat(20) assert(m.ran domize()) $display(m.sm.num );end endprogram Futurewiz www.futurewiz.co.i class sample; rand bit[1:0] num; endclass class main; rand sample sm; //rand is must to / / Example2
  • 260.
    program test; sample sm; initial begin sm=new; repeat(20) assert(sm.ra ndomize() ) $display(sm.st.a) ;end endprogramFuturewiz www.futurewiz.co.i class sample; typedef struct { randc int a; bit [3:0] b; } st_t; rand st_t st; //rand is must to randomize //int present inside structure endclass Example3
  • 261.
    program test; main m; initial begin m=new; repeat(20)begin assert(m.randomize()) ; $display(m.sm1.num); $display(m.sm2.num ); end end endprogram Futurewiz www.futurewiz.co.i class sample; rand bit[3:0] num; endclass class main; rand sample sm1; sample sm2; function new; sm1=new; sm2=new; endfunction endclass Example4
  • 262.
    Result Futurewiz www.futurewiz.co.i # 14 #0 # 4 # 0 # 9 # 0 # 6 # 0 # 5 # 0 # 15 # 0 # 4 # 0 # 13 # 0 # 1 # 0 # 8 # 0 # 9 # 0 # 14 # 0
  • 263.
    Specifying Constraints Futurewiz www.futurewiz.co.i class sample1; rand intnum; constraint c { num>10; nu m <1 00 ; } endclass class sample2; class sample3; randc int num; int Max, Min; constraint c1 { num>Min; } constraint c2 { num<Max; } endclass
  • 264.
    class packet; rand bit[7:0] data; int Max=50, Min=10; constraint c1 { data>Min; data<Max; } endclass program test; packet Futurewiz www.futurewiz.co.i Example1 repeat(10) assert(pkt.randomize( )) $display(pkt.data); pkt.Min=30; pkt.Max=100; repeat(10) assert(pkt.randomize( )) $display(pkt.data ); end endprogram
  • 265.
    Result Futurewiz www.futurewiz.co.i # 22 #72 # 22 # 53 # 29 # 66 # 27 # 79 # 46 # 68 # 43 # 69 # 33 # 78 # 43 # 95 # 46 # 65 # 36 # 34
  • 266.
    class packet; rand bit[7:0] data; constraint c2 { data>50; data<10; } endclass Futurewiz www.futurewiz.co.i endprogra Example2 program test; packet pkt; initial begin pkt=new; repeat(10) if(pkt.rando mize()) $display(“Randomizatio n Success”); else $display(“Randomization
  • 267.
    Result Futurewiz www.futurewiz.co.i # Randomization Fails # RandomizationFails # Randomization Fails # Randomization Fails # Randomization Fails # Randomization Fails # Randomization Fails # Randomization Fails # Randomization Fails # Randomization Fails
  • 268.
    ⚫ Every classcontains pre_randomize and post_randomize functions which are evoked every time randomize function is called. ⚫ When randomize function is called, it first evokes pre_randomize and then randomization is done. ⚫ post_randomize function is only called if randomization was successful. ⚫ pre_randomize and post_randomize functions can be written in a class to offer user defined functionality before and after randomization. Futurewiz www.futurewiz.co.i pre_randomize and post_randomize
  • 269.
    class packet; rand bit[7:0] data; function void pre_randomize; $display(“Pre- Randomize”); endfunction function void post_randomize; $display(“Post- Randomize”); endfunction endclass Futurewiz www.futurewiz.co.i Example1 program test; packet pkt; initial begin pkt=new; repeat(5) begin void'(pkt.rand omize); $display(pkt.data ); end
  • 270.
    Result Futurewiz www.futurewiz.co.i # Pre-Randomize # Post-Randomize# 33 # Pre-Randomize # Post-Randomize # 25 # Pre-Randomize # Post-Randomize # 202 # Pre-Randomize # Post-Randomize # 138 # Pre-Randomize # Post-Randomize # 15
  • 271.
    class A; function voidpre_randomize; $display(“A: Pre- Randomize”); endfunction function void post_randomize; $display(“A: Post- Randomize”); endfunction endclass Futurewiz www.futurewiz.co.i Example2 class B extends A; function void pre_randomize; $display(“B: Pre- Randomize”); endfunction function void post_randomize; $display(“B: Post- Randomize”); endfunction endclass
  • 272.
    Example2 overridde n Futurewiz www.futurewiz.co.i program test; B b1; initial begin b1=new; repeat(2) void'(b1.randomize );end endprogram Result # B: Pre- Randomiz e # B: Post- Randomiz e # B: Pre- Randomiz e # B: Post- Randomiz e Pre-Randomize and
  • 273.
    ⚫ Randomization natureof rand and randc variables can be turned on/off dynamically. ⚫ rand_mode method is used to change randomization status of rand and randc variable. ⚫ When used as a task, the argument determines the state of rand and randc variables. ⚫ When argument is 0 then randomization is disabled(turned-off), when argument is 1 then randomization is enabled(turned-on). Futurewiz www.futurewiz.co.i Controlling Randomization
  • 274.
    ⚫When used asa function, rand_mode returns the current status of rand and randc variables. ⚫It returns 1 if randomization is on else it returns 0. ⚫Hierarchal reference of variables in an object can also be given to disable/enable specific rand and randc variables. ⚫Randomization is enabled by default. Futurewiz www.futurewiz.co.i Controlling Randomization
  • 275.
    class packet; rand bit[7:0] data; endclass program test; packet pkt; initial begin Futurewiz www.futurewiz.co.i Example1 •repeat(4) begin void'(pkt.randomize) ; •$display(pkt.data); end pkt.rand_mode(0); •//Disabling Randomization repeat(3) begin void'(pkt.randomize) •$display(pkt.data) ; end end
  • 276.
  • 277.
    class packet; rand bit[7:0] data1; rand int data2; endclass Futurewiz www.futurewiz.co.i Example2 if(pkt.rand_mode()) //Check current Status $display(“Randomization on”); else $display(“Randomization off”); end pkt.rand_mode(0); void'(pkt.randomize ); if(pkt.rand_mode()) $display(“Randomiz ation on”); else $display(“Randomization off”); end endprogram program test; packet pkt; initial begin pkt=new; repeat(10) begin void'(pkt.rando mize);
  • 278.
    class packet; rand bit[7:0] data1; rand byte data2; endclass program test; packet pkt; initial begin pkt=new; Futurewiz www.futurewiz.co.i Example3 repeat(10) if(pkt.randomize) $display(pkt.data1, pkt.data2); pkt.data2.rand_mode(0); //turn off for data2 repeat(10) if(pkt.randomize) $display(pkt.data1, pkt.data2); pkt.data2.rand_mode(1); repeat(10) if(pkt.randomize) $display(pkt.data1, pkt.data2); end endprogram
  • 279.
    Result # 9 -34Futurewiz www.futurewiz.co.i # 238 94 # 85 48 # 202 -92 # 29 38 # 155 48 # 225 -91 # 81 -66 # 232 -82 # 85 -112 # 141 -34 # 244 -34 # 32 -34
  • 280.
    class packet; rand bit[7:0] data1; byte data2; endclass program test; packet pkt; initial begin Futurewiz www.futurewiz.co.i Example4 repeat(10) if(pkt.randomiz e) $display(pkt.data1, pkt.data2); repeat(10) if(pkt.randomize(data2)) //will only randomize data2 $display(pkt.data1, pkt.data2); end endprogram
  • 281.
    Result Futurewiz www.futurewiz.co.i # 238 0 #85 0 # 202 0 # 29 0 # 155 0 # 225 0 # 141 75 # 141 115 # 141 -24 # 141 111 # 141 -119
  • 282.
    class packet; rand int data;int Max, Min; constraint c1{ data> Min; data<Max; } constraint c2 { Max> Min; } task set(int Min, Max); this.Min=Min; this.Max=Max; endtask endclass Futurewiz www.futurewiz.co.i Example5
  • 283.
    initial begin packet p1=new; p1.set(5, 25); repeat(5) if(p1.randomiz e) $display(“Randomvalue=%0d”, p1.data); p1.set(35, 20); repeat(5) if(p1.randomize) $display(“Random value=%0d”, p1.data); else $display(“Randomization Failed”); end Futurewiz www.futurewiz.co.i Example5
  • 284.
    Result Futurewiz www.futurewiz.co.i # Random value=14 # Randomvalue=18 # Random value=15 # Random value=16 # Random value=16 # Randomization Failed # Randomization Failed # Randomization Failed # Randomization Failed # Randomization
  • 285.
    module test; class A; rand bit[3:0] data; endclass A a1, a2; Futurewiz www.futurewiz.co.i initial begin a1=new; //Random seed initialized a2=new; //Random seed initialized with next seed value Random Stability repeat(5) if(a1.randomiz e) $display("a1.data= %0d",a1.data); repeat(5) if(a2.randomize) $display("a2.data= %0d",a2.data); end endmodule
  • 286.
    Result Futurewiz www.futurewiz.co.i # a1.data=12 # a1.data=7 # a1.data=15 # a1.data=6 #a1.data=9 # a2.data=13 # a2.data=13 # a2.data=6 # a2.data=2
  • 287.
    Random Stability Futurewiz www.futurewiz.co.i module test; class A; randbit [3:0] data; endclass A a1, a2; initial begin a1=new; //Random seed initialized a2=new; //Random seed initialized with next seed value repeat(5) if(a2.randomiz e) $display("a2.da ta= %0d",a2.data ); repeat(5) if(a1.randomiz e) $display("a1.da ta= %0d",a1.data
  • 288.
  • 289.
    module test; class A; rand bit[3:0] data; function new(int seed); srandom(seed); //set a particular seed endfunction endclass A a1, a2; Futurewiz www.futurewiz.co.i Random Stability initial begin a1=new(3); a2=new(3); repeat(5) if(a1.randomize) $display("a1.data= %0d",a1.data); repeat(5) if(a2.randomize) $display("a2.data= %0d",a2.data); end endmodule
  • 290.
    Result Futurewiz www.futurewiz.co.i # a1.data=5 # a1.data=7 # a1.data=12 # a1.data=13 #a1.data=5 # a2.data=5 # a2.data=7 # a2.data=12 # a2.data=13
  • 291.
    Relation in Constraints Futurewiz www.futurewiz.co.i ⚫Each constraint expression should only contain 1 relation operator. < <= == > >= -> <-> || ! && ⚫ lo < med is evaluated. Results in 0 or 1 ⚫ hi > (0 or 1) is evaluated. class bad_cons; rand bit [7:0] low, med, hi; constraint bad {low < med < hi;} endclass low=20, med=224, hi=164 low=114, med=39, hi=189 low=186, med=148, hi=161 low=214, med=223, hi=201
  • 292.
    ⚫User can use== to constraint random value to a particular expression. Using = will give compilation error. class packet; rand int length, data, address; constraint len { length==address * 5}; endclass Futurewiz www.futurewiz.co.i constraint good{ low < med; med < hi; } low=20, med=40, hi=100 low=10, med=25, hi=90 Relation in Constraints
  • 293.
    Set Membership Futurewiz www.futurewiz.co.i ⚫User canuse inside operator to set membership in a constraint block. ⚫Example: To limit address in range from 1 to 5, 7 to 11 and to a set of values 15, 18, 25. class packet; rand int address; constraint limit {address inside { [1:5],
  • 294.
    Set Membership Futurewiz www.futurewiz.co.i ⚫ A! Operator can be used to exclude set of values class packet; rand int address; constraint limit { !(address inside { 6, [12:14]} ) ;} endclass ⚫ Using arrays to set membership. class packet; int arr [ ]= `{ 5, 7, 11, 13, 19}; rand int address; constraint limit { address inside { arr }; } endclass
  • 295.
    Set Membership • classpacket; rand int data; • constraint limit { ( (data==5) || (data==7) || (data==9) );} endclass • There is a better way of providing such • constraints: • class packet; • rand int data; • constraint limit { data inside { 5, 7, 9}; } endclass Futurewiz www.futurewiz.co.i
  • 296.
    Weighted Distribution Futurewiz www.futurewiz.co.i ⚫User canprovide weights for random numbers to obtain non-uniform distribution. ⚫:= operator is used to assign same weight to all the values. ⚫:/ operator is used to distribute weight among all the values. ⚫dist operator is used to specify distribution. ⚫Weighted distribution does not work on randc variables. ⚫Example : constraint con { src dist { 0:=40, [1:3] :=60 }; dst dist { 0:/40 , [1:3] :/60 }; }
  • 297.
    class packet; rand int data; constraintcon { data dist { 0:=40, [1:4] :=60, [6:7]:=20 }; } endclass //Total weight= 40 + 60 + 60 + 60 + 60 + 20 + 20=320 Futurewiz www.futurewiz.co.i Example1 data=3 weight=60/320=18.75% data=4 weight=60/320=18.75% data=6 weight=20/320=6.25% data=7 weight=20/320=6.25% data=0 weight=40/320=12.5% data=1 weight=60/320=18.75% data=2 weight=60/320=18.75%
  • 298.
    class packet; rand int data; constraintcon { data dist { 0:/20, [1:3] :/60, [6:7]:/20 }; } endclass //Total weight= 20 + 60 + 20=100 Futurewiz www.futurewiz.co.i Example2 data=3 weight=20/100=20% data=6 weight=10/100=10% data=7 weight=10/100=10% data=0 weight=20/100=20% data=1 weight=20/100=20% data=2 weight=20/100=20%
  • 299.
    typedef enum {Red,Green, Blue} color; class temp; rand color col; int redw=5, greenw=3, bluew=4; constraint weight { col dist { Red:=redw, Green:=green w, Blue:=bluew}; } endclass Futurewiz www.futurewiz.co.i Example3
  • 300.
    Bidirectional Constraints Futurewiz www.futurewiz.co.i ⚫Constraints arenot procedural but declarative. ⚫All constraints should be active at same time. rand bit [15:0] a, b, c; constraint cp { a < c; b == a; c < 10; b > 5; } ⚫Even though there is no direct constraint on lower value of c, constraint on b restricts choices. Solution a b c S1 6 6 7 S2 6 6 8 S3 6 6 9 S4 7 7 8 S5 7 7 9 S6 8 8 9
  • 301.
    Implication Constraints Futurewiz www.futurewiz.co.i constraint mode_c{ if (mode == small) len < 10; else if (mode == large) len > 100; } Is equivalent to constraint mode_c{ (mode == small) -> len < 10; (mode == large) -> len > 100; } ⚫ If mode is small that implies length should be less than 10. ⚫ If mode is large that implies length should be more than 100. ⚫ Implication helps in creating case like blocks.
  • 302.
    Efficient Constraints Futurewiz www.futurewiz.co.i rand bit[31:0] addr; constraint slow { addr % 4096 inside { [0:20], [4075:4095] }; } rand bit [31:0] addr; constraint fast { addr [11:0] inside { [0:20], [4075:4095] }; } ⚫In slow, first addr is evaluated and then % is performed and then constraints are applied. In fast, constraints are directly applied on selected bits hence faster and
  • 303.
    Solution Probabilities Futurewiz www.futurewiz.co.i Solution xy Probabilit y S1 0 0 1/8 S2 0 1 1/8 S3 0 2 1/8 S4 0 3 1/8 S5 1 0 1/8 S6 1 1 1/8 S7 1 2 1/8 S8 1 3 1/8 class Unconstrained; rand bit x; // 0 or 1 rand bit [1:0] y; // 0, 1, 2, or 3 endclass
  • 304.
    Solution Probabilities Futurewiz www.futurewiz.co.i Solution xy Probabilit y S1 0 0 1/2 S2 0 1 0 S3 0 2 0 S4 0 3 0 S5 1 0 1/8 S6 1 1 1/8 S7 1 2 1/8 S8 1 3 1/8 class Implication1; rand bit x; // 0 or 1 rand bit [1:0] y; // 0, 1, 2, or 3 constraint c { (x==0) -> (y==0); } endclass
  • 305.
    Solution Probabilities Futurewiz www.futurewiz.co.i Solution xy Probabilit y S1 0 0 0 S2 0 1 0 S3 0 2 0 S4 0 3 0 S5 1 0 0 S6 1 1 1/3 S7 1 2 1/3 S8 1 3 1/3 class Implication2; rand bit x; // 0 or 1 rand bit [1:0] y; // 0, 1, 2, or 3 constraint c { y>0; (x==0) -> (y==0); } endclass
  • 306.
    Solution x y Probabilit y S10 0 1/2 S2 0 1 0 S3 0 2 0 S4 0 3 0 S5 1 0 1/8 S6 1 1 1/8 S7 1 2 1/8 S8 1 3 1/8 Futurewiz Solve before www.futurewiz.co.i n ⚫A solve before keyword can be used to specify order in which random variables would be solved. class solvebefore; rand bit x; // 0 or 1 rand bit [1:0] y; // 0, 1, 2, or 3 constraint c { (x==0) -> (y==0); solve x before y; }
  • 307.
    Solve before Futurewiz www.futurewiz.co.i Solution xy Probabilit y S1 0 0 1/8 S2 0 1 0 S3 0 2 0 S4 0 3 0 S5 1 0 1/8 S6 1 1 1/4 S7 1 2 1/4 S8 1 3 1/4 class solvebefore; rand bit x; // 0 or 1 rand bit [1:0] y; // 0, 1, 2, or 3 constraint c { (x==0) -> (y==0); solve y before x; } endclass
  • 308.
    ⚫ Constraints canbe turned on/off during runtime. ⚫ constraint_mode() is used to achieve this capability. ⚫ When used with handle.constraint, this method controls a single constraint. ⚫ When used with just handle, it controls all constraints for an object. ⚫ To turn off constraint, 0 is passed as an argument to constraint_mode and to turn on, 1 is passed as an argument. Futurewiz www.futurewiz.co.i Controlling Constraints
  • 309.
    class Packet; rand int length; constraintc_short { length inside { [1:32] }; } constraint c_long { length inside { [1000:1023]}; } endclass Futurewiz www.futurewiz.co.i Example
  • 310.
    Example Futurewiz www.futurewiz.co.i Packet p; initial begin p= new; // Create a long packet by disabling short constraint p.c_short.constraint_mode(0); assert (p.randomize()); // Create a short packet by disabling all constraints // then enabling only the short constraint p.constraint_mode(0); p.c_short.constraint_mode(1); assert (p.randomize()); end
  • 311.
    Inline Constraints Futurewiz www.futurewiz.co.i ⚫New constraintscan be added to existing constraints while calling randomize function using randomize with. ⚫constraint_mode can be used disable any conflicting constraints. class Transaction; rand bit [31:0] addr, data; constraint c1 { addr inside { [0:100], [1000:2000] }; } endclass
  • 312.
    Inline Constraints Futurewiz www.futurewiz.co.i // addris 50-100, 1000-1500, data < 10 Transaction t; initial begin t = new(); repeat(5) assert(t.randomize() with { addr >= 50; addr <= 1500; data < 10;} ); repeat(5) // force addr to a specific value, data > 10 assert(t.randomize() with { addr == 2000; data > 10; } ); end
  • 313.
    Constraint in Inheritance Futurewiz www.futurewiz.co.i ⚫Additionalconstraints can be provided in a subclass class(child class). Child class object has to fulfill both the constraints (parent and child). class base; rand int data; constraint limit1 { data> 0; d a t class child extends base; constraint limit2 { data > 50; } endclass Child: 50 < data < 100
  • 314.
    Example2 Futurewiz www.futurewiz.co.i class base; rand intdata; constraint limit1 { data> 0; data< 100; } endclass class child extends base; constraint limit2 { data == 50; } endclass Parent: 0 < data < 100 Child: data=50
  • 315.
    Example3 Futurewiz www.futurewiz.co.i class base; rand intdata; constraint limit1 { data> 40; data< 50; } endclass class child extends base; constraint limit2 { data > 10; data< 30; } endclass Parent: 40 < data < 50 Child: 10 < data < 30 Randomization Fails because both constraints are not satisfied
  • 316.
    Example 4 Futurewiz www.futurewiz.co.i class base; randint data; constraint limit1 { data> 40; d a t a < 5 class child extends base; rand int data; constraint limit2 { data > 10; data< 30; } endclass Parent: 40 < data < 50 Child: 10 < data < 30 Parent data is different as compared to child data. Data Overridden
  • 317.
    Constraint in Inheritance Futurewiz www.futurewiz.co.i ⚫Constraintsare overridden in child class if they are defined with same name as that present in parent class. class base; rand int data; constraint limit { data> 20; data< 40; } endclass class child extends base; constraint limit { data > 50; data < 90; } endclass Parent: 20 < data < 40 Child: 50 < data < 90 Constraints are overridden
  • 318.
    randcase Futurewiz www.futurewiz.co.i ⚫A randcase keywordcan be used to make a weighted choice between several actions. initial begin int len; repeat(20) begin randcase // 10%: 0 to 2 // 80%: 3 to 5 // 10%: 6 to 7 1: len = $urandom_range(0, 2); 8: len = $urandom_range(3, 5); 1: len = $urandom_range(6, 7); endcase $display("len=%0d", len); end end
  • 319.
    randsequence Futurewiz www.futurewiz.co.i ⚫The random sequencegenerator is useful for randomly generating structured sequences of stimulus. ⚫randsequence is composed of one or more productions. ⚫Each production contains a name and one or more production list. ⚫Production list contains one or more production_item.
  • 320.
    Example1 Futurewiz www.futurewiz.co.i module rand_sequence1(); initial begin repeat(5) begin//main is production //main contains one production list //one two three are production items randsequence( main ) main : one two three ; one : {$write("one");}; two : {$write("two");}; three: {$display("three");}; endsequence en d en d en dm od
  • 321.
    Result Futurewiz www.futurewiz.co.i # one two three# one two three # one two three # one two three # one two three
  • 322.
    Example2 Futurewiz www.futurewiz.co.i //main contains threeproduction list //one two three are production list //one list will be chosen randomly module rand_sequence2(); initial begin repeat(7) begin randsequence( main ) main : one| two | three ; one : {$display("one"); }; two : {$display("two"); }; three: {$display("three"); }; endsequence en d en d endmodule : rand_sequence2
  • 323.
  • 324.
    Example3 endmodule : rand_sequence3 Futurewiz www.futurewiz.co.i module rand_sequence3(); initial begin repeat(50)begin randsequence( main ) main : one:=5 | two:=2 | three:=3 ; //production list with weights one : {$display("one");}; two : {$display("two");}; three: {$display("three");}; endsequenc e end end
  • 325.
    Example4 Futurewiz www.futurewiz.co.i module rand_sequence4(); int one_1,two_2, three_3; bit on; initial begin repeat(100) begin randsequence( main ) main : one three; one : if(on) incr_one else incr_two; incr_one : {one_1 ++; on=~on;}; incr_two : {two_2 ++; }; three: {three_3++;}; endsequence end end endmodule : rand_sequence4
  • 326.
    Example5 Futurewiz www.futurewiz.co.i module rand_sequence5(); initial for(int i = 0 ; i < 10 ; i+ +) randsequence( main ) main : case(i %3) 0 : zero; 1, 2 : non_zero; default : def; endcase zero : {$display("zero");}; non_zero : {$display("non_zero");}; def : {$display("default");}; endsequence endmodule : rand_sequence5
  • 327.
  • 328.
    Program Block Futurewiz www.futurewiz.co.i ⚫Verilog moduleworks well for design but when used for Test benches may lead to race-around condition between design and Test bench. ⚫System Verilog adds program block which is used meant for writing Test Bench. ⚫program and endprogram keywords are used to define a program block.
  • 329.
    Program Block Futurewiz www.futurewiz.co.i ⚫program blockhas following features: o They separate test benches from design unit. o Statements are executed in Reactive Region. o always blocks are not allowed in program block. o They can be instantiated inside other modules. o Instance of module or program block is not allowed inside program block. o They have access to variables present inside a module where they are instantiated but vice versa is not true. o Implicit system task $exit is called when program block terminates.
  • 330.
    Program Block Region Inactive NBA Observed Re-Active Re-Inactive PostponedRe-NBA Preponed Active From Current Time Slot To Next Time Slot Program Block Runs Here Futurewiz www.futurewiz.co.i Test Bench runs once all design related activities are over.
  • 331.
    Example1 Futurewiz www.futurewiz.co.i module tff (q,clk, t); input clk, t; output reg q=0; always @ (posedge clk) if(t) q<= ~ q; endmodule module tb; reg clk=0, t=1; wire q=0; always #5 clk=~clk; tff u0 (q, clk, t); always @ (posedge clk) $display($time, “q=%d”, q);
  • 332.
    Example1 Futurewiz www.futurewiz.co.i Result: 5 q= 0 15q= 1 25 q= 0 35 q= 1 45 q= 0 55 q= 1
  • 333.
    Example2 Futurewiz www.futurewiz.co.i module tff (q,clk, t); input clk, t; output reg q=0; always @ (posedge clk) if(t) q<= ~ q; endmodule initial allowe d begin program tb (input clk); //always not forever @ (posedge clk) $display($time, “q=%d”, q); end initial t=1; endprogra m
  • 334.
    Example2 Futurewiz www.futurewiz.co.i module top; reg clk=0, t; wireq; always #5 clk=~clk; tff u0 (q, clk, t); tb u1 (clk); q //program has access to t and endmodul e
  • 335.
    Example2 Futurewiz www.futurewiz.co.i Result: 5 q= 1 15q= 0 25 q= 1 35 q= 0 45 q= 1 55 q= 0
  • 336.
    Example3 Futurewiz www.futurewiz.co.i program tb; int a; initial$monitor(“result is %d”, a); initial begin #3 a= a + 2; #4 a= a + 3; end endprogram Result : result is 2 a=5 $monitor does not execute for a=5 because of implicit $exit
  • 337.
    Example4 Futurewiz www.futurewiz.co.i program tb; int a; initial $monitor(“ resultis %d”, a); initial begin #3 a= a + 2; #4 a= a + 3; #1 ; end endprogra m Result : result is 2 result is 5
  • 338.
    Interface Futurewiz www.futurewiz.co.i ⚫ Interface isused to encapsulate communication between design blocks, and between design and verification blocks. ⚫ Encapsulating communication between blocks facilitates design reuse. Interfaces can be accessed through ports as a single item. ⚫ Signals can be added to and remove easily from an interface without modifying any port list. ⚫ Interface can contain the connectivity, synchronization, and optionally, the functionality of the communication between two or more blocks.
  • 339.
    Design Futurewiz www.futurewiz.co.i module adder (inputbit clk, input logic [3:0] a, b, output logic [4:0] sum); always @ (posedge clk) sum= a + b; endmodule
  • 340.
    Test Bench Futurewiz www.futurewiz.co.i program tb(input bit clk, input logic [4:0] sum, output logic [3:0] a, b); initia l begi n $monitor (“a=%0d b=%0d sum=%0d”, a, b, sum); forever begin a=$random; b=$random; #10; end end endprogram
  • 341.
    Top Level Futurewiz www.futurewiz.co.i module top ();bit clk=0; logic [3:0] a, b; logic [4:0] sum; always #5 clk=~clk; adder a0 (.*); have tb t0 (.*); endmodule //connect variables to ports that // same name and same data type Now in case you have to add one more input c, you have to define c at three place adder, tb and top.
  • 342.
    Defining Interface Futurewiz www.futurewiz.co.i interface intf(input bit clk); logic [3:0] a, b; logic [4:0] sum; endinterface : inf
  • 343.
    Design Futurewiz www.futurewiz.co.i module adder (intf inf); always@ (posedge inf.clk) inf.sum= inf.a + inf.b; endmodule : adder
  • 344.
    Test Bench Futurewiz www.futurewiz.co.i program tb(inft inf); initial begin $monitor (“a=%0d b=%0d sum=%0d”, inf.a, inf.b, inf.sum); forever begin inf.a=$rando m; inf.b=$rando m; #10; end end endprogram :
  • 345.
    Top Level Futurewiz www.futurewiz.co.i module top ();bit clk=0; always #5 clk=~clk; intf inf(clk); adder a0 (inf); tb t0 (inf); //inf is interface instance endmodul e
  • 346.
    Modport Futurewiz www.futurewiz.co.i ⚫modport construct isto used to provide direction information for module ports. interface intf (input bit clk); logic [3:0] a, b; logic [4:0] sum; //incase of inout port use wire modport DUT (input clk, a, b, output sum); modport TB (input clk, sum,
  • 347.
    Design Futurewiz www.futurewiz.co.i module adder (intf.DUT inf); always@ (posedge inf.clk) inf.sum= inf.a + inf.b; endmodule : adder
  • 348.
    Test Bench Futurewiz www.futurewiz.co.i program tb(intf.TB inf); initial begin $monitor (“a=%0d b=%0d sum=%0d”, inf.a, inf.b, inf.sum); forever begin inf.a=$rando m; inf.b=$rando m; #10; end end endprogram :
  • 349.
    Top Level Futurewiz www.futurewiz.co.i module top ();bit clk=0; always #5 clk=~clk ; intf i0 (.*); adder a0 (.*); tb t0 (.*); endmodu
  • 350.
    Clocking Block Futurewiz www.futurewiz.co.i ⚫Clocking blockconstruct identifies clock signals and captures the timing and synchronization requirements of the blocks being modeled. ⚫Clocking block assembles signals that are synchronous to a particular clock and makes their timing explicit. ⚫Clocking block separates the timing and synchronization details from the structural, functional, and procedural elements of a test bench.
  • 351.
    Clocking Block Futurewiz www.futurewiz.co.i ⚫In caseof synchronous circuits, input should be sampled just before the clock and output should be driven just after the clock. ⚫So from test bench point of view, design outputs should be sampled just before the clock and design inputs should be driven just after the clock. ⚫By default design outputs are sampled at #1step (Prepone Region) and design inputs are driven at #0 (Inactive /Re- Inactive Region).
  • 352.
    Clocking Block endinterfac e Futurewiz www.futurewiz.co.i interfaceintf(input bit clk); ………… modport TB (input clk, clocking cb); clocking cb @ (posedge clk); edge input sum; output a, b; endclocking : cb ………… //specifying active clock //sampled in prepone region //driven in inactive region //Directions w.r.t Test Bench
  • 353.
    Clocking Block Output ofTest Bench Clk en DUT Futurewiz www.futurewiz.co.i en Output of Clocking Block / Input to
  • 354.
    Clocking Block Output ofDUT/ Input to Clocking Block Clk coun t coun t 1 Futurewiz www.futurewiz.co.i 2 3 4 5 6 7 6 0 1 2 3 4 Input to Test Bench 5
  • 355.
    Clocking Block Futurewiz www.futurewiz.co.i ……………………… clockingcb @ (posedge clk); default input #3ns output #2ns; //specifying active clock edge //Specifying user default for sampling and driving input sum, reset; output a, b; endclocking : cb //sampled 3ns before active clock edge //driven 2ns after active clock edge …………………………
  • 356.
    Clocking Block Futurewiz www.futurewiz.co.i ……………………… clockingcb @ (posedge clk); default input #3ns output #2ns; //specifying active clock edge //Specifying user default for sampling and driving input sum; output a, b; //sampled 3ns before active clock edge //driven 2ns after active clock edge input negedge reset; //Overriding default sampling for reset endclocking : cb …………………………
  • 357.
    Interface Futurewiz www.futurewiz.co.i interface intf(input bit clk);logic [3:0] count; logic en; modport DUT (input clk, en, output count); //DUT modport TB (input clk, clocking cb); //Test Bench clocking cb @ (posedge clk); input count; output en; endclockin g endinterfac e //Clocking Block
  • 358.
    Design Futurewiz www.futurewiz.co.i module counter (intf.DUT inf); always@ (posedge inf.clk) if(inf.en) inf.count+=1; endmodule : counter
  • 359.
    Test Bench Futurewiz www.futurewiz.co.i program tb(intf.TB inf); initial begin @inf.cb; #3 inf.cb.en<=1; ##8 inf.cb.en<=0; repeat(2) @inf.cb; inf.cb.en<=1; //continue on active edge in cb // use NBA for signals in cb //wait for 8 active edges in cb //wait for 2 active edges in cb wait (inf.cb.count==3) inf.cb.en<=0; //wait for count to become 3 end endprogram : tb
  • 360.
    Parameterized Interface Futurewiz www.futurewiz.co.i interface intf#(size=3, type typ=logic) (input bit clk); typ [size-1:0] count; typ en; modport DUT (input clk, en, output count); //DUT modport TB (input clk, count, output en); //Test Bench endinterface
  • 361.
    Virtual Interface Futurewiz www.futurewiz.co.i ⚫ Avirtual interface is a variable that represents an interface instance. This interface is not use to represent physical connections. ⚫ Virtual interface variables can be passed as arguments to tasks, and functions. ⚫ Tasks and functions can modify variables present in a virtual interface which has the same effect as accessing physical interface. ⚫ A virtual interface can be declared as class property, should be initialize before usage.
  • 362.
    Virtual Interface Futurewiz www.futurewiz.co.i interface intf(input bit clk); logic req, gnt; always @(posedge clk); interface if(req) begin repeat(2) @(posedge clk); gnt<=1; end else gnt<=0; endinterfac e //functionality inside
  • 363.
    Virtual Interface endtas k Futurewiz www.futurewiz.co.i module test; bit clk=0; always#5 clk=~clk; intf inf(clk); initia l fork gen_ req(i nf); task gen_req(virtual intf a); @(posedge a.clk) a.req<=1; @(posedge a.clk) a.req<=0; repeat (5) @(posedge a.clk); a.req<=1; @(posedge a.clk) a.req<=0; endtask task rec_gnt(virtual intf b); forever begin @(posedge b.gnt) $display($time, “
  • 364.
    Virtual Interface Futurewiz www.futurewiz.co.i class test; virtualintf t1 ; function new(virtual intf t2); t1=t2; //initializing virtual //interface endfunction //task gen_req; //task rec_gnt; endclas s module top; bit clk=0; always #5 clk=~clk; intf inf(clk); initial begin test c1= new(inf); fork c1.gen_req ; c1.rec_gnt;
  • 365.
  • 366.
    final block en d Futurewiz www.futurewiz.co.i ⚫final blockis a procedural statement that occurs at the end of simulation. ⚫Delays are not allowed inside final block. ⚫Final block can only occur once during simulation. ⚫$finish can be used to trigger final block. final begi n $dis play( “Sim
  • 367.
    Block Statements Futurewiz www.futurewiz.co.i ⚫Block statementsare used to group procedural statements together. ⚫There are two types of blocks : o Sequential blocks (begin - end) o Parallel blocks (fork - join) ⚫System Verilog introduces three types of Parallel blocks: o fork – join o fork – join_any o fork – join_none
  • 368.
    fork - join Futurewiz www.futurewiz.co.i ⚫Infork-join, the process executing the fork statement is blocked until the termination of all forked processes. module test; initial begin $display(“Before Fork”); fork begin #3 $display(“#3 occurs at %0d”, $time); end begin #6 $display(“#6 occurs at %0d”, $time); end begin #8 $display(“#8 occurs at %0d”, $time); end begin #5 $display(“#5 occurs at %0d”, $time); end join $display(“Out of Fork at %0d”, $time); end endmodule
  • 369.
    fork - join Futurewiz www.futurewiz.co.i Result: Before Fork #3 occurs at 3 #5 occurs at 5 #6 occurs at 6 #8 occurs at 8 Out of Fork at 8
  • 370.
    fork – join_any Futurewiz www.futurewiz.co.i ⚫Infork-join_any, the process executing the fork statement is blocked until any one of the processes spawned by fork completes . module test; initial begin $display(“Before Fork”); fork begin #3 $display(“#3 occurs at %0d”, $time); end begin #6 $display(“#6 occurs at %0d”, $time); end begin #8 $display(“#8 occurs at %0d”, $time); end begin #5 $display(“#5 occurs at %0d”, $time); end join _any $display(“Out of Fork at %0d”, $time); end endmodule
  • 371.
    fork – join_any Futurewiz www.futurewiz.co.i Result: Before Fork #3 occurs at 3 Out of Fork at 3 #5 occurs at 5 #6 occurs at 6 #8 occurs at 8
  • 372.
    fork – join_none Futurewiz www.futurewiz.co.i ⚫Infork-join_none, the process executing the fork statement continues to execute with all processes spawned by fork. module test; initial begin $display(“Before Fork”); fork begin #3 $display(“#3 occurs at %0d”, $time); end begin #6 $display(“#6 occurs at %0d”, $time); end begin #8 $display(“#8 occurs at %0d”, $time); end begin #5 $display(“#5 occurs at %0d”, $time); end join_none $display(“Out of Fork at %0d”, $time); end endmodule
  • 373.
    fork – join_none Futurewiz www.futurewiz.co.i Result: Before Fork Out of Fork at 0 #3 occurs at 3 #5 occurs at 5 #6 occurs at 6 #8 occurs at 8
  • 374.
    wait fork Futurewiz www.futurewiz.co.i program test; initialbegin $display(“Before Fork”); fork begin #3 $display(“#3 occurs at %0d”, $time); end begin #6 $display(“#6 occurs at %0d”, $time); end begin #8 $display(“#8 occurs at %0d”, $time); end begin #5 $display(“#5 occurs at %0d”, $time); end join_none $display(“Out of Fork at %0d”, $time); end endprogram program block exits simulation once it reaches end of initial block
  • 375.
  • 376.
    program test; initial begin$display(“Before Fork”); fork begin #3 $display(“#3 occurs at %0d”, $time); end begin #6 $display(“#6 occurs at %0d”, $time); end begin #8 $display(“#8 occurs at %0d”, $time); end begin #5 $display(“#5 occurs at %0d”, $time); end join_none $display(“Out of Fork at %0d”, $time); wait fork; end endprogram Waits till all forked processed are completed Futurewiz www.futurewiz.co.i n wait fork
  • 377.
    wait fork Futurewiz www.futurewiz.co.i Result : Before Fork Outof Fork at 0 #3 occurs at 3 #5 occurs at 5 #6 occurs at 6 #8 occurs at 8
  • 378.
    disable fork Futurewiz www.futurewiz.co.i module test; initialbegin $display(“Before Fork”); fork begin #3 $display(“#3 occurs at %0d”, $time); end begin #6 $display(“#6 occurs at %0d”, $time); end begin #8 $display(“#8 occurs at %0d”, $time); end begin #5 $display(“#5 occurs at %0d”, $time); end join_any $display(“Out of Fork at %0d”, $time); disable fork; end endmodule Disable fork kills all forked processes
  • 379.
  • 380.
    Conditional Event Control Futurewiz www.futurewiz.co.i ⚫@event control can have an iff qualifier. ⚫event expression only triggers if the expression after the iff is true. always @(a iff en==1) begin y<= a; end always @(posedge clk iff en) begin y<=din ; end Both the event expression (@a and (@posedge clk)) occurs only if en==1
  • 381.
    Sequence Event Control Futurewiz www.futurewiz.co.i ⚫Asequence instance can be used in event expressions to control the execution of procedural statements based on the successful match of the sequence. sequence abc; @ (posedge clk) a ##1 b ##1 c; endsequence always @(abc) $display(“event occurred on a, b and c in order”);
  • 382.
    Named Events Futurewiz www.futurewiz.co.i ⚫System Verilogallows used to define events and trigger them. ⚫There are two ways to trigger an event o Blocking (->) o Non-Blocking(->>) ⚫There are two ways to wait for an event o @ (event_name) o wait(even_name.triggered)
  • 383.
    Example1 Futurewiz www.futurewiz.co.i event myevent; int count=0; //User defined event initia l begi n ->myevent; #3 -> myevent; end //Triggering event always @(myevent) count+=1; //waiting for event Result : count= 2
  • 384.
    Example2 Futurewiz www.futurewiz.co.i event myevent; event int count=0; //User defined initia l begi n -> myevent; @(myevent )count+=1; //Triggering event //waiting for event end while using @, waiting should start before event is triggered Result : count= 0
  • 385.
  • 386.
    Example4 Futurewiz www.futurewiz.co.i event myevent; int count=0; //User defined event initia l begi n - >>myevent; @(myevent) count+=1; end //Triggeringevent in NBA region //waiting for event Result : count= 1 Event is scheduled to triggered in NBA region because of which waiting starts before triggering and count increments
  • 387.
    Example5 Futurewiz www.futurewiz.co.i event myevent; int count=0; //User defined event initia l fork ->myevent; @(myevent )count+=1; join //Triggering event //waiting for event count value depends upon which statement is executed first result varies from simulator to simulator.
  • 388.
    Example6 Futurewiz www.futurewiz.co.i event myevent; int count=0; //User defined event initia l begi n - >my even t; wait (myevent.triggered) count+=1; //Triggering event //waitingfor event When using .triggered, waiting should start before or at same time when event is triggered. Result : count= 1
  • 389.
  • 390.
    always_comb Futurewiz www.futurewiz.co.i ⚫ System Verilogprovides always_comb procedure for modeling combinational logic behavior. always_comb c= a & b; ⚫ There is an inferred sensitivity list. ⚫ The variables written on the left-hand side of assignments shall not be written to by any other process. ⚫ The procedure is automatically triggered once at time zero, after all initial and always procedures. ⚫ Software tools will perform additional check to warn if behavior within always_comb does not match a combinational logic.
  • 391.
    always_latch Futurewiz www.futurewiz.co.i ⚫System Verilog providesalways_latch procedure for modeling latched logic behavior. always_latc h if(en) b=a; ⚫This construct is identical to always_comb, except that the tools will perform additionsal check to warn if behavior does not match a latch logic.
  • 392.
    always_ff Futurewiz www.futurewiz.co.i ⚫ always_ff procedurecan be used to model synthesizable sequential logic behavior. always_ff @ (posedge clk iff !rst or posedge rst) if(rst) q<=0; else q<=d; ⚫ The always_ff procedure imposes the restriction that it contains one and only one event control and no blocking timing controls. ⚫ Tools should perform additional checks to warn if the behavior does not represent sequential logic.
  • 393.
    Fine Grain processcontrol Futurewiz www.futurewiz.co.i ⚫A process is a built-in class that allows one process to access and control another process once it has started. ⚫Users can declare variables of type process and safely pass them through tasks. ⚫Objects of type process are created internally when processes are spawned. An attempt to call new() would give error.
  • 394.
    Fine Grain processcontrol Futurewiz www.futurewiz.co.i ⚫self() function returns handle to current process. ⚫status() function returns process status which could be any of the following: o FINISHED : Terminated Normally o RUNNING : Currently Running o WAITING : Waiting in a blocking statement o SUSPENDED : Stopped, Waiting for resume o KILLED : Forcibly terminated
  • 395.
    Fine Grain processcontrol Futurewiz www.futurewiz.co.i ⚫kill() function terminates the current process and all its sub processes. ⚫await() task allows one process to wait for completion of another process. ⚫suspend() function allows a process to suspend either its own execution or that of another process. ⚫resume() function restarts previously suspended process.
  • 396.
    Example Futurewiz www.futurewiz.co.i task run1(); p1=process :: self();forever #2 count+=1; end endtas k module test; process p1, p2; int count, i=1; //task definitions //On next slide endmodule
  • 397.
    Example Futurewiz www.futurewiz.co.i task run2 (refprocess p2); p2=process :: self(); repeat (6) begin #4 i*=2; end endtas k initial begin $monitor($time, count, i); fork run1() ; run2( p2); join en d
  • 398.
    Example Futurewiz www.futurewiz.co.i initial begin #3 p1.suspend(); #10p2.suspend(); #5 p1.resume(); $display(“%s”,p1.status()) ; $display(“%s”,p2.status()) ; #2 p2.resume(); #1 p2.await(); #1 p1.kill(); end
  • 399.
  • 400.
    Coverage Futurewiz www.futurewiz.co.i ⚫ Coverage isthe metric of completeness of verification. ⚫ Why we need coverage? o Direct Testing is not possible for complex designs. o Solution is constrained random verification but : o How do we make sure what is getting verified? o Are all importance design states getting verified? ⚫ Types of Coverage's: o Code Coverage. o Functional Coverage.
  • 401.
    Code Coverage Futurewiz www.futurewiz.co.i ⚫ CodeCoverage is a measure used to describe how much part of code has been covered (executed). ⚫ Categories of Code Coverage o Statement coverage o Checks whether each statement in source is executed. o Branch coverage o Checks whether each branch of control statement (if, case) has been covered. o Example: choices in case statements.
  • 402.
    Code Coverage Futurewiz www.futurewiz.co.i o Conditioncoverage o Has Boolean expression in each condition evaluated to both true and false. o Toggle coverage o Checks that each bit of every signal has toggled from 0 to 1 and 1 to 0. o Transition coverage o Checks that all possible transitions in FSM has been covered. o State coverage o Checks that all states of FSM has been covered.
  • 403.
    Functional Coverage Futurewiz www.futurewiz.co.i ⚫ FunctionalCoverage is used to verify that DUT meets all the described functionality. ⚫ Functional Coverage is derived from design specifications. o DUT Inputs : Are all interested combinations of inputs injected. o DUT Outputs : Are all desired responses observed from every output port. o DUT internals : Are all interested design events verified. e.g. FIFO full/empty, bus arbitration.
  • 404.
    Examples ⚫ Have Iexercised all the protocol request types and combinations? o Burst reads, writes etc. ⚫ Have we accessed different memory alignments? o Byte aligned, word aligned, dword aligned, etc. ⚫ Did we verify sequence of transactions? o Reads followed by writes. ⚫ Did we verify queue full and empty conditions? • o input and output queues getting full and new requests getting back pressured. Futurewiz www.futurewiz.co.i
  • 405.
    Code vs. FunctionalCoverage Futurewiz www.futurewiz.co.i Needs more Functional Coverage points, Check for unused code Good Coverage Start of Project Code may be incomplete Code Coverage Functional Coverage Hig h Low Hig h Low
  • 406.
    Coverage Driven Verification Createinitial cover metrics Generate Random Tests Run Tests, Collect Coverage Identify Coverage Holes Coverage Met ? Add tests to target holes, Enhance stimulus generator, Enhance cover metrics if From Verificatio n Plan Verification Complete NO Futurewiz www.futurewiz.co.i YES
  • 407.
    SV Functional CoverageSupport Futurewiz www.futurewiz.co.i ⚫ The System Verilog functional coverage constructs provides: o Coverage of variables and expressions, as well as cross coverage between them. o Automatic as well as user-defined coverage bins. o Associate bins with sets of values, transitions, or cross products. o Events and sequences to automatically trigger coverage sampling. o Procedural activation and query of coverage. o Optional directives to control and regulate coverage.
  • 408.
    covergroup Futurewiz www.futurewiz.co.i ⚫covergroup construct encapsulatesthe specification of a coverage model. ⚫covergroup is a user defined type that allows you to collectively sample all variables/transitions/cross that are sampled at the same clock (or sampling) edge. ⚫It can be defined inside a package, module, interface, program block and class. ⚫Once defined, a covergroup instance can be created using new() - just like a class.
  • 409.
  • 410.
    ⚫A coverage point(coverpoint) is a variable or an expression that functionally covers design parameters. ⚫Each coverage point includes a set of bins associated with its sampled values or its value- transitions. ⚫The bins can be automatically generated or manually specified. ⚫A covergroup can contain one or more coverpoints. Futurewiz www.futurewiz.co.i Coverpoint
  • 411.
    Example Futurewiz www.futurewiz.co.i Syntax: [label : ]coverpoint expression [ iff (expression)] [{ //bins specifications; }] ; Example: covergroup cg; coverpoint a iff (!reset); endgroup
  • 412.
    bins Futurewiz www.futurewiz.co.i ⚫ bins arebuckets which are used to collect number of times a particular value/transaction has occurred. ⚫ bins allows us to organize coverpoint sample values in different ways. o Single value bins. o Values in a range, multiple ranges. o Illegal values, etc. ⚫ If bins construct is not used inside coverpoint then automatic bins are created based on the variable type and size. ⚫ For a n-bit variable, 2 ^ n automatic bins are created.
  • 413.
    Example1 Futurewiz www.futurewiz.co.i bit [3:0] temp; covergroupcg; coverpoint temp; endgroup //16 - Automatic bins created cg cg1; initial cg1=new; bin[0] to bin[15] are created where each bin stores information of how many times that number has occurred.
  • 414.
    Example2 Futurewiz www.futurewiz.co.i bit [3:0] temp; covergroupcg; coverpoint temp { bins a= { [0 : 15] }; //creates single bin for values 0- 15 bins b [ ]= { [0 : 15] }; //creates separate bin for each //value 0-15 } endgroup
  • 415.
    Example3 Futurewiz www.futurewiz.co.i bit [3:0] temp; covergroupcg; coverpoint temp { bins a [ ]= { 0, 1, 2 }; bins b [ ]= { 0, 1, 2, [1:5] }; //creates three bins 0, 1, 2 //creates eight bins 0, 1, 2, //1, 2, 3, 4, 5 } endgroup
  • 416.
    Example4 Futurewiz www.futurewiz.co.i bit [3:0] temp; covergroupcg; coverpoint temp { bins a [4]= { [1:10], 1, 5, 7 }; //creates four bins with distribution <1, 2, 3> <4, 5, 6> <7, 8, 9> } endgrou p <10, 1, 5, 7>
  • 417.
    Example5 Futurewiz www.futurewiz.co.i bit [9:0] temp; covergroupcg; coverpoint temp { bins a = { [0:63], 65 }; // single bin bins b [ ]={ [127:150], [148:191] }; // overlapping multiple bins // three bins // multiple bins from 1000 bins c [ ]={ 200, 201, 202 }; bins d [ ]={ [1000:$] }; // to $(last value:1023) bins others [ ] = default; } endgroup // bins for all other value
  • 418.
    Questa (How toobtain coverage) Futurewiz www.futurewiz.co.i vlog +cover filename.sv vsim –c modulename –do “run time; coverage report – details;” //Provides Function coverage, -details switch is used to observe bins vsim –c –cover modulename –do “run time; coverage report –details; ” // -cover switch enables code coverage vsim –c –cover modulename –do “run time; coverage report –details –html;” //create html report for coverage
  • 419.
    Covergroup Arguments Futurewiz www.futurewiz.co.i ⚫Parameterized Covergroupscan be written using arguments. ⚫Useful if similar covergroups are needed with different parameters or covering different signals. ⚫Example: covergroup for all basic FIFO conditions. ⚫Actual values can be passed to formal arguments while covergroup is instantiated. ⚫ref keyword is required if a variable is passed as an argument.
  • 420.
    Example Futurewiz www.futurewiz.co.i bit [16:0] rdAddr,wrAddr; covergroup addr_cov (input int low, int high, ref bit [16:0] address) @ (posedge clk); addr_range : coverpoint address { bins addrbin= { [low: high] }; } endgroup addr_cov rdcov=new ( 0, 31, rdAddr ); addr_cov wrcov=new ( 64, 127, wrAddr
  • 421.
    Covergroup inside aclass Futurewiz www.futurewiz.co.i ⚫By embedding covergroup inside class, coverage can be collected on class members. ⚫Very useful as it is a nice way to mix constrained random stimulus generation along with coverage. ⚫A class can have multiple covergroups. ⚫For embedded covergroups, instance must be created be inside the new() of class.
  • 422.
    Example Futurewiz www.futurewiz.co.i class xyz; bit [3:0] m_x;int m_y; bit m_z; covergroup cov1 @ (m_z); coverpoint m_x; coverpoint m_y; endgroup //Embedded Covergroup //16 bins //2^32 bins function new(); cov1=new; endfunction endclass
  • 423.
    Example Futurewiz www.futurewiz.co.i class c1; bit [7:0] x; covergroupcv (input int arg) @ (posedge clk); option.at_least=arg; coverpoint x; endgroup function new (int p1); cv=new(p1); endfunction endclass initial c1 obj=new(4);
  • 424.
    Bins for Transition Futurewiz www.futurewiz.co.i ⚫Inmany cases, we are not only interested in knowing if certain values or value ranges happen. ⚫But, we are also interested in knowing if transition between two values or two value ranges happen. ⚫Transition coverage is often more interesting in control scenarios, whereas value coverage is more interesting in data path scenarios.
  • 425.
    Specifying Transition Futurewiz www.futurewiz.co.i ⚫Single ValueTransition (value1=> value2) ⚫Sequence of Transitions (value1=> value2 => value3=> value4) ⚫Set of Transitions (value1, value2 => value3, value4) ⚫Consecutive repetition of Transitions value[*repeat_time]
  • 426.
    Example1 Futurewiz www.futurewiz.co.i bit [4:1] a; covergroupcg @ (posedge clk); coverpoint a { bins sa [ ]= ( 4=>5=>6 ), ( [7:9],10=>11,12) ; bins allother= default sequence; } endgroup Sa will be associated with individual bins (4=>5=>6) , (7=>11), (7=>12), (8=>11), (8=>12), (9=>11), (9=>12), (10=>11), (10=>12)
  • 427.
    Example2 Futurewiz www.futurewiz.co.i ⚫Consecutive Repetition bins sb={ 4[*3] } ; // (4=>4=>4) bins sc [ ]={ 3 [*2:4] }; // (3=>3) , (3=>3=>3), (3=>3=>3=>3) ⚫Non-Consecutive Repetition bins sd [ ]={ 2 [->3] }; //2=>…. =>2 …. =>2
  • 428.
    Automatic Bin creation ⚫System Verilog creates implicit bins when coverpoint does not explicitly specifies it. ⚫ The size of automatic bin creation is: o In case of enum coverage point it is same as number of elements in enum. o In case of integral coverage point it is minimum of 2 • ^ no. of bits and value of auto_bin_max option. o Automatic bins creation only considers two state value. o If auto_bin_max is less than 2 ^ no. of bits, then values are equitably distributed among the bins. Futurewiz www.futurewiz.co.i
  • 429.
    Wildcard Bins Futurewiz www.futurewiz.co.i ⚫Wildcard binsare where X, Z or ? will be treated as don’t care. bit [2:0] num; covergroup cg; coverpoint num { wildcard bins even={3’b?? 0}; wildcard bins odd={3’b??1}; } endgroup
  • 430.
    Wildcard Bins Futurewiz www.futurewiz.co.i bit [3:0]count1; bit [1:0] count2; covergroup cg; coverpoint count1 { wildcard bins n12_15={4’b11??}; //1100 || 1101 || 1110 || 1111 } coverpoint count2 { wildcard bins t =(2’b0x=>2’b1x); //(0, 1=>2, 3) }
  • 431.
    Excluding bins Futurewiz www.futurewiz.co.i ⚫In somecases all the bins may not be of interest, or design should never have a particular bin. ⚫These are two ways to exclude bins : o ignore_bins o illegal_bins
  • 432.
    Ignore Bins Futurewiz www.futurewiz.co.i ⚫All valuesor transitions associated with ignore_bins are excluded from coverage. ⚫Ignored values or transitions are excluded even if they are also included in another bin. bit [3:0] num; covergroup cg; coverpoint num { bins val [ ]={ [1:15] }; ignore_bins bins ignoreval={ 7, 8 }; //7 and 8 are ignored //ignore 7 and 8 ignore_bins bins ignoretran=(3=>4=>5);//ignore transition } endgroup
  • 433.
    Ignore Bins Futurewiz www.futurewiz.co.i bit [2:0]num; covergroup cg; coverpoint num { option.auto_bin_max =4; //<0:1> , <2:3>, <4:5>, <6:7> ignore_bins bins hi={6, 7}; // bins 6 and 7 are ignored from coverage }
  • 434.
    Illegal Bins Futurewiz www.futurewiz.co.i ⚫ Allvalues or transitions associated with illegal_bins are excluded from coverage and run-time error is issued if they occur. ⚫ They will result in a run-time error even if they are also included in another bin. bit [3:0] num; covergroup cg; coverpoint num { //illegal bins 2 and 3 //4 to 5 is illegal illegal_bins bins illegalval={ 2, 3 }; illegal_bins bins illegaltran=(4=>5); //transition } endgroup
  • 435.
    ⚫Coverage points measuresoccurrences of individual values. ⚫Cross coverage measures occurrences of combination of values. ⚫Interesting because design complexity is in combination of events and that is what we need to make sure is exercised well. ⚫Examples: o Was write enable 1 when address was 4’b1101. o Have we provide all possible combination of inputs to a Full Adder. Futurewiz www.futurewiz.co.i Cross Coverage
  • 436.
    Example1 Futurewiz www.futurewiz.co.i ⚫Cross coverage isspecified between two or more coverpoints in a covergroup. bit [3:0] a, b; covergroup cg @ (posedge clk); cross_cov: cross a , b; endgroup ⚫16 bins for each a and b. ⚫16 X 16=256 bins for cross_cov
  • 437.
    Example2 Futurewiz www.futurewiz.co.i ⚫Cross coverage isallowed only between coverage points defined within the same coverage group. bit [3:0] a, b, c; covergroup cg @ (posedge clk); cov_add: coverpoint b+c; cross_cov: cross a , cov_add; endgroup ⚫16 Bins for each a, b and c. 32 bins for b + c. ⚫16 X 32=512 bins for cross_cov.
  • 438.
    Example3 Futurewiz www.futurewiz.co.i bit [31:0] a; bit[3:0] b; covergroup cg @ (posedge clk); cova: coverpoint a { bins low [ ]={ [0:9] }; } cross_cov: cross b, cova; endgroup ⚫16 bins for b. 10 bins for cova. ⚫10 X 16=160 bins for cross_cov.
  • 439.
    ⚫Cross Manipulating orcreating user-defined bins for cross coverage can be achieved using bins select- expressions. ⚫There are two types of bins select expression : o binsof o intersect Futurewiz www.futurewiz.co.i Cross Coverage
  • 440.
    binsof and intersect Futurewiz www.futurewiz.co.i ⚫Thebinsof construct yields the bins of expression passed as an arguments. Example: binsof (X) ⚫The resulting bins can be further selected by including or excluding only the bins whose associated values intersect a desired set of values. ⚫Examples: o binsof(X) intersect { Y } , denotes the bins of coverage point X whose values intersect the range given by Y. o ! binsof(X) intersect { Y } , denotes the bins of coverage point X whose values do not intersect the range given by Y.
  • 441.
    binsof and intersect Futurewiz www.futurewiz.co.i ⚫Selectedbins can be combined with other selected bins using the logical operators && and ||. bit [7:0] a, b; covergroup cg @ (posedge clk); cova : coverpoint a { bins a1 = { [0:63] }; bins a2 = { [64:127] }; bins a3 = { [128:191] }; bins a4 = { [192:255] }; } endgroup
  • 442.
    binsof and intersect Futurewiz www.futurewiz.co.i covb: coverpoint b { bins b1 = { 0 }; bins b2 = { [1:84] }; bins b3 = { [85:169] }; bins b4 = { [170:255] }; }
  • 443.
    binsof and intersect Futurewiz www.futurewiz.co.i covc: cross cova, covb { bins c1= !binsof(cova) intersect { [100:200] }; //a1*b1, a1*b2, a1*b3, a1*b4 bins c2= binsof(cova.a2) || binsof(covb.b2); //a2*b1, a2*b2, a2*b3, a2*b4 //a1*b2, a2*b2, a3*b2, a4*b2 bins c3= binsof(cova.a1) && binsof(covb.b4); //a1*b4 }
  • 444.
    Excluding Cross products Futurewiz www.futurewiz.co.i ⚫Agroup of bins can be excluded from coverage by specifying a select expression using ignore_bins. covergroup cg; cross a, b { ignore_bins bins ig=binsof(a) intersect { 5, [1:3] }; } endgroup ⚫All cross products that satisfy the select expression
  • 445.
    Illegal Cross products Futurewiz www.futurewiz.co.i ⚫Agroup of bins can be marked illegal by specifying a select expression using illegal_bins. covergroup cg (int bad); cross a, b { illegal_bins bins invalid=binsof(a) intersect { bad }; } endgroup
  • 446.
    Coverage Options ⚫ Optionscan be specified to control the behaviour of the covergroup, coverpoint and cross. ⚫ There are two types of options: o Specific to an instance of a covergroup. o Specify for the covergroup. ⚫ Options placed in the cover group will apply to all cover points. ⚫ Options can also be put inside a single cover point for • finer control. Futurewiz www.futurewiz.co.i
  • 447.
    option.comment Futurewiz www.futurewiz.co.i ⚫Comments can beadded to make coverage reports easier to read. covergroup cg; option.comment=“Cover group for data and address”; coverpoint data; coverpoint address; endgroup
  • 448.
    per instance coverage Futurewiz www.futurewiz.co.i ⚫Ifyour test bench instantiates a coverage group multiple times, by default System Verilog groups together all the coverage data from all the instances. ⚫Sometime you would that all coverpoints should be hit on all instances of the covergroup and not cumulatively. covergroup cg; option.per_instance= 1; coverpoint data; endgroup
  • 449.
    at_least coverage Futurewiz www.futurewiz.co.i ⚫By defaulta coverpoint is marked as hit (100%) if it is hit at least one time. ⚫Some times you might want to change this to a bigger value. ⚫Example: If you have a State machine that can handle some kind of errors. Covering an error for more number of times has more probability that you might also test error happening in more than one state. option.at_least=10
  • 450.
    Coverage goal Futurewiz www.futurewiz.co.i ⚫By defaulta covergroup or a coverpoint is considered fully covered only if it hits 100% of coverpoints or bins. ⚫This can be changed using option.goal if we want to settle on a lesser goal. bit [2:0] data; covergroup cg; coverpoint data; option.goal=90 ; endgroup //settle for partial coverage
  • 451.
    option.weight Futurewiz www.futurewiz.co.i ⚫If set atthe covergroup level, it specifies the weight of this covergroup instance for computing the overall instance coverage. ⚫If set at the coverpoint (or cross) level, it specifies the weight of a coverpoint (or cross) for computing the instance coverage of the enclosing covergroup. ⚫Usage: option.weight=2 (Default value=1) ⚫Usage: Useful when you want to prioritize certain coverpoints /covergroups as must hit versus less important.
  • 452.
    Example Futurewiz www.futurewiz.co.i covergroup cg; a: coverpointsig_a { bins a0= {0}; option.weight=0; //will not compute to //coverage } b: coverpoint sig_b { bins b1= {1}; option.weight=1; } ab: cross a , b { option.weight=3; } endgroup
  • 453.
    option.auto_bin_max Futurewiz www.futurewiz.co.i ⚫Limiting autobins forcoverpoints and crosses ⚫Usage: option.auto_bin_max = <number> (default=64) ⚫Usage: option.cross_auto_bin_max =<number> (default= unbounded)
  • 454.
  • 455.
  • 456.
  • 457.
    Coverage system tasksand functions Futurewiz www.futurewiz.co.i ⚫$set_coverage_db_name ( name ) Sets the filename of the coverage database into which coverage information is saved at the end of a simulation run. ⚫$load_coverage_db ( name ) Load from the given filename the cumulative coverage information for all coverage group types. ⚫$get_coverage ( ) Returns as a real number in the range 0 to 100 that depicts the overall coverage of all coverage group types.
  • 458.
    Cover property Futurewiz www.futurewiz.co.i ⚫The propertythat is used an assertion can be used for coverage using cover property keyword. property ab; @(posedge clk) a ##3 b; endproperty cp_ab: cover property(ab) $info(“coverage passed”);
  • 459.
    Effect of coverageon performance Futurewiz www.futurewiz.co.i ⚫ Be aware that enabling Functional Coverage slows down the simulation. ⚫ So know what really is important to cover : o Do not use auto-bins for large variables. o Use cross and intersect to weed out unwanted bins. o Disable coverpoint/covergroup during reset. o Do not blindly use clock events to sample coverpoint variables, instead use selective sampling() methods. o Use start() and stop() methods to decide when to start/stop evaluating coverage. o Do not duplicate coverage across covergroups and properties.
  • 460.
  • 461.
    Assertions and Coverage Futurewiz www.futurewiz.co.i ⚫Assertions These are checks which used to verify that your design meets the given requirements. Example: grant should be high two clock cycles after request. ⚫ Coverage These are used to judge what percentage of your test plan or functionality has been verified. They are used to judge quality of stimulus. They help us in finding what part of code remains untested.
  • 462.
    Assertions Futurewiz www.futurewiz.co.i Design Rule :Grant should be asserted 2 clock cycles after request Clock Reques tGran t Gran t Assertion Passed Assertion Failed
  • 463.
  • 464.
    Immediate Assertions Futurewiz www.futurewiz.co.i ⚫ Theseare used to check condition at current time. ⚫ These checks are Non Temporal i.e. checks are not performed across time or clock cycles. ⚫ These are used inside procedural blocks (initial/always and tasks/functions). ⚫ Assertion fails if expression evaluates to 0, X or Z. case an error is reported during runtime. [Label] : assert (expression) [pass _statement]; ⚫ In case fail_statement is not pro [e vi l d s e e d f a a n i d l_ a s s ta se te rti m on e f n a t il ; s ] , then in that
  • 465.
    Example stat e Futurewiz www.futurewiz.co.i IDL E RE Q RE Q RE Q IDL E IDL E Design Rule :State Machine should go to REQ state only if req1 or req2 is high. clk req1 req 2
  • 466.
    Example Futurewiz www.futurewiz.co.i always @ (posedge clk)if (state==REQ) REQ assert ( req1 || req2) or //if current state is //Check whether req1 //req2 is high $info(“Correct State”); else $error(“Incorrect State”);
  • 467.
    Assertions Severity Futurewiz www.futurewiz.co.i ⚫$info indicatesthat the assertion failure carries no specific severity. Useful for printing some messages. ⚫$warning indicates runtime warning. Can be used to indicate non severe errors. ⚫$error indicates runtime error. Can be used to indicate protocol errors. ⚫$fatal indicates fatal error that would stop simulation.
  • 468.
    Examples Futurewiz www.futurewiz.co.i always @ (posedgeclk) assert(func(a, b)) ->myevent; else error=error + 1; //Trigger myevent if function returns 1 else increase error count. always @ (negedge clk) assert (y==0) error_flag=0; else error_flag=1; //y should not be 1 at negedge of clk always @ (state) assert($onehot(state)) else $fatal(“state is not one hot”); //In a one-hot encoded state machine all states should be one-hot
  • 469.
    Concurrent Assertions Futurewiz www.futurewiz.co.i ⚫ Theseassertions test for a sequence of events spread over multiple clock cycles i.e. they are Temporal in nature. ⚫ property keyword is used to define concurrent assertions. ⚫ property is used to define a design specification that needs to be verified ⚫ They are called concurrent because they occur in parallel with other design blocks. [Label] : assert property (property_name) [pass_statement]; [else fail_statement;]
  • 470.
    Assertions Design Rule :Grant should be high 2 clock cycles after request, followed by low request and then grant in consecutive cycles. Clk Req Gn t Assertio n Passed Gn t Futurewiz www.futurewiz.co.i Assertio n Passed
  • 471.
    Example Futurewiz www.futurewiz.co.i property req_gnt; @ (posedgeclk) req ##2 gnt ##1 !req ##1 !gnt; endproperty assert property(req_gnt) else $error(“req_gnt property violated”); ⚫ ## followed by a number is used to indicate no. of clock cycles. ⚫ If gnt is not high 2 clock cycles after req goes high, violation will be reported. ⚫ If req and gnt come at proper time but req is not low in next clock cycle, that will also lead to violations.
  • 472.
    Assertion Region Inactive NBA Observed Re-Active Re-Inactive Postponed $strobe, $monitor, PLICalls Re-NBA Preponed Sample Data before entering current time slot (#1step) Active From Current Time Slot To Next Time Slot Values are sampled in Preponed Region Evaluated in Observed True / False statements executed in Re-Active Futurewiz www.futurewiz.co.i
  • 473.
    Properties and Sequences Futurewiz www.futurewiz.co.i ⚫Assertionscan directly include a property. assert property (@ (posedge clk) a ##1 b); ⚫Assertions can be split into assertion and property declared separately property myproperty; @ (posedge clk) a ##1 b ##1 c; endproperty assert property (myproperty);
  • 474.
    Properties and Sequences Futurewiz www.futurewiz.co.i ⚫Aproperty can be disabled conditionally property disable_property; @ (posedge clk) disable iff (reset) a ##1 b ##1 c; endproperty ⚫property block contains definition of sequence of events. ⚫Complex properties can be structured using multiple sequence blocks.
  • 475.
    Properties and Sequences Futurewiz www.futurewiz.co.i sequences1; a ##1 b ##1 c; endsequence property p1; @ (posedge clk) disable iff (reset) s1 ##1 s2; endsequence sequence s2; a ##1 c; endsequenc e assert property(p1 );
  • 476.
    Sequences Futurewiz www.futurewiz.co.i ⚫Sequence is seriesof true/false expression spread over one or more clock cycles. ⚫It acts like basic building block for creating complex property specifications. ⚫Sampling edge can be specified inside a sequence. If not defined, it is inferred from property block or assert block. sequence s1; @(posedge clk) a ##1 !b ##1 c ##0 ! d; endsequence
  • 477.
    Linear Sequences Futurewiz www.futurewiz.co.i ⚫ Linearsequence is finite list of System Verilog Boolean expression in a linear order of increasing time. ⚫ A sequence is set to match if all these conditions are true: o The first boolean expression evaluates to true at the first sampling edge. o The second boolean expression evaluates to true after the delay from first expression. o and so forth, up to and including the last boolean expression evaluating to true at the last sampling edge. ⚫ Sequence is evaluated on every sampling edge.
  • 478.
    Example • program assert_test; initial begin •#4 a=1; • #10 a=0; b=1; • #10 b=0; c=1; • #10 c=0; • #10 a=1; • #20 b=1; • #10 c=1; • #10; • end Futurewiz www.futurewiz.co.i module test; bit clk; logic a=0, b=0, c=0; always #5 clk=~clk; property abc; @ (posedge clk) a ##1 b ##1 c; endproperty assert property(abc) $info(“Sequence Occurred”); //program
  • 479.
  • 480.
    ⚫A sequence canbe declared inside: o Module o Interface o Program o Clocking block o Package ⚫Syntax: sequence sequence_name [ (arguments) ]; boolean_expression; endsequence [ : sequence_name] Futurewiz www.futurewiz.co.i Declaring Sequences
  • 481.
    ⚫Sequences can haveoptional Formal Arguments. ⚫Actual arguments can be passed during instantiation. sequence s1 (data, en) ( !a && (data==2’b11)) ##1 (b==en) endsequence ⚫Clock need not be specified in a sequence. ⚫In this case clock will be inferred from the property or assert statement where this sequence is Futurewiz www.futurewiz.co.i Sequence Arguments
  • 482.
    ⚫Evaluation of asequence can be pre-conditioned with an implication operator. ⚫Antecedent – LHS of implication operator ⚫Consequent – RHS of implication operator ⚫Consequent will be evaluated only if Antecedent is true. ⚫There are two types of implication operators: o Overlapping (Antecedent |-> Consequent ) o Non-Overlapping (Antecedent |=> Consequent ) Futurewiz www.futurewiz.co.i Implication Operator
  • 483.
    ⚫If antecedent istrue then Consequent evaluation starts immediately. ⚫If antecedent is false then consequent is not evaluated and sequence evaluation is considered as true this is called vacuous pass. ⚫$assertvacuousoff [ (levels[ , list]) ] can be used to disable vacuous pass. property p1; @ (posedge clk) en |-> (req ##2 ack); endproperty Futurewiz www.futurewiz.co.i Overlapping Implication Operator
  • 484.
    Example • program assert_test; initial begin •#4 en=1; req=1; • #10 en=0; req=0; • #10 gnt=1; • #10 gnt=0; • #20 en=1; • #10 en=0; req=1; • #10 req=0; gnt=1; • #10; • end Futurewiz www.futurewiz.co.i module test; bit clk; logic en=0, req=0, gnt=0; always #5 clk=~clk; property abc; @ (posedge clk) en |-> req ##2 gnt; endproperty assert property(abc) $info(“Sequence
  • 485.
    Example clk en re q gn t Sequence Occurred Evaluation in progressFuturewiz www.futurewiz.co.i Error Reported Vacuous Pass
  • 486.
    Example Futurewiz www.futurewiz.co.i module test; bit clk; logicen=0, req=0, gnt=0; always #5 clk=~clk; property abc; @ (posedge clk) en ##0 req ##2 gnt; endproperty assert program assert_test; initial begin #4 en=1; req=1; #10 en=0; req=0; #10 gnt=1; #10 gnt=0; #20 en=1; #10 en=0; req=1; #10 req=0; gnt=1; #10; end endprogram
  • 487.
  • 488.
    ⚫If antecedent istrue then Consequent evaluation starts in next clock cycle. ⚫If antecedent is false then consequent is not evaluated and sequence evaluation is considered as true this is called vacuous pass. property p1; @ (posedge clk) en |=> (req ##2 ack); endproperty Futurewiz www.futurewiz.co.i Non-Overlapping Implication Operator
  • 489.
    Example Futurewiz www.futurewiz.co.i module test; bit clk; logicen=0, req=0, gnt=0; always #5 clk=~clk; property abc; @ (posedge clk) en |=> req ##1 gnt; endproperty assert program assert_test; initial begin #4 en=1; req=1; #10 en=0; req=0; #10 gnt=1; #10 gnt=0; #20 en=1; #10 en=0; req=1; #10 req=0; gnt=1; #10; end endprogram
  • 490.
  • 491.
    Example Futurewiz www.futurewiz.co.i module test; bit clk; logicen=0, req=0, gnt=0; always #5 clk=~clk; property abc; @ (posedge clk) en ##1 req ##1 gnt; endproperty assert program assert_test; initial begin #4 en=1; req=1; #10 en=0; req=0; #10 gnt=1; #10 gnt=0; #20 en=1; #10 en=0; req=1; #10 req=0; gnt=1; #10; end endprogram
  • 492.
  • 493.
    ⚫## n representsn clock cycle delay (or number of sampling edges). ⚫## 0 means same clock cycle (overlapping signals). ⚫## [min : max] specifies a range of clock cycles o min and max must be >=0. sequence s1; @ (posedge clk) a ## [1:3] b; endsequence Equivalent to: (a ##1 b) || (a ##2 b) || (a ##3 b) Futurewiz www.futurewiz.co.i Sequence Operators
  • 494.
  • 495.
    ⚫$ is usedto specify infinite number of clock cycles (till end of simulation). sequence s2; @ (posedge clk) a ## [2:$] b; endsequence b must be high after 2 or more clock cycle after a is asserted. Futurewiz www.futurewiz.co.i Sequence Operators
  • 496.
    ⚫Sequence of eventscan be repeated for a count using [*n]. sequence s3; @ (posedge clk) a ##1 b [*2]; endsequence Equivalent to : a ##1 b ##1 b b must be true for two consecutive clock cycles after a goes high a ##1 (b ##1 c) [*2]; Equivalent to : a ##1 b ##1 c ##1 b ##1 c Futurewiz www.futurewiz.co.i Sequence Operators
  • 497.
    ⚫Sequence of eventscan be repeated for a range of count using [*m : n]. o n should be more than 0 and cannot be $ sequence s4; @ (posedge clk) a ##1 b [*2:5]; endsequence Futurewiz www.futurewiz.co.i Equivalent to : (a ##1 b ##1 b ) || (a ##1 b ##1 b ##1 b) || (a ##1 b ##1 b ##1 b ##1 b) || (a ##1 b ##1 b ##1 b ##1 b ##1 b) || Sequence Operators b must be true for minimum 2 and maximum 5 consecutive clock cycles after a is asserted
  • 498.
    Sequence Operators Futurewiz www.futurewiz.co.i ⚫[=m] operatorcan be used if an event repetition of m non-consecutive cycles are to be detected. o m should be more than 0 and cannot be $ sequence s5; @ (posedge clk) a ##1 b [=2]; endsequence b must be true for 2 clock cycles, that may not be consecutive.
  • 499.
  • 500.
    Sequence Operators Futurewiz www.futurewiz.co.i ⚫[=m :n] operator is used if an event repetition of m (minimum) to n (maximum) non-consecutive cycles are to be detected. sequence s6; @ (posedge clk) a ##1 b [=2: 3]; endsequence cycles, b must be true for minimum of 2 and maximum of 3 clock Equivalent to : (a ##1 b [=2] ) || (a ##1 b [=3] ) that may not be consecutive.
  • 501.
    AND Operator Futurewiz www.futurewiz.co.i ⚫Use andoperator if two sequences needs to match. seq1 and seq2 ⚫Following should be true for resultant sequence to matches: o seq1 and seq2 should start from same point. o Resultant sequence matches when both seq1 and seq2 matches. o The end point of seq1 and seq2 can be different. o The end time of resulting sequence will be end
  • 502.
    Example c d e Resultant Sequence Detecte d (a ##2 b)and (c ##1 d ##2 e) clk a b S e q 1 d e t e c t d Seq detection started Seq2 detected Futurewiz www.futurewiz.co.i
  • 503.
  • 504.
    Example (a ##[2:4] b)and (c ##1 d ##2 e) clk a b c d e Seq1 Seq2 Detected Resultant Sequence Seq detection started Futurewiz www.futurewiz.co.i Detecte d Detecte d
  • 505.
    Intersect Operator Futurewiz www.futurewiz.co.i seq1 intersectseq2 ⚫Following should be true for resultant sequence to matches: o seq1 and seq2 should start from same point. o Resultant sequence matches when both seq1 and seq2 matches. o The end point of seq1 and seq2 should be same.
  • 506.
    Example (a ##[2:4] b)intersect (c ##1 d ##2 e) clk a b c d e Resultant Sequence Seq1 Seq2 Detected Seq detection starte d Futurewiz www.futurewiz.co.i Detecte d Detecte d
  • 507.
    OR Operator Futurewiz www.futurewiz.co.i ⚫Use oroperator when at least one of the sequences needs to match. seq1 or seq2 ⚫Following should be true for resultant sequence to matches: o seq1 and seq2 should start from same point. o Resultant sequence matches when either seq1 or seq2 matches. o The end point of seq1 and seq2 can be different. o The end time of resulting sequence will be end time of last sequence.
  • 508.
    Example c d e Resultant Sequence Detecte d (a ##2 b)or (c ##1 d ##2 e) clk a b S e q 1 d e t e c t d Seq detection started Seq2 detected Futurewiz www.futurewiz.co.i
  • 509.
  • 510.
    Example (a ##[2:4] b)or (c ##1 d ##2 e) clk a b c d e Resultant Sequence Futurewiz www.futurewiz.co.i Detecte d Detecte d Seq1 Seq2 Detected Seq detection started
  • 511.
    throughout Operator Futurewiz www.futurewiz.co.i ⚫Useful fortesting a condition that an expression has to be true throughout the sequence. expr1 throughout seq1 ⚫Left of throughout cannot be a sequence. (!c) throughout a ##3 b
  • 512.
    First_match Operator Futurewiz www.futurewiz.co.i ⚫first_match operatormatches only first of possible multiple matches for evaluation of sequence. a ##[2:5] b first_match(a ##[2:5] b) Equivalent to: (a ##2 b) || (a ##3 b) || (a ##4 b) || (a ##5 b) Sequence will match only one of the following options, whichever occurs first (a ##2 b) (a ##3 b) (a ##4 b) (a ##5 b)
  • 513.
  • 514.
    Example (!c) throughout a ##3b clk a b c Assertio n Failed Futurewiz www.futurewiz.co.i Assertion Passed Detection Started
  • 515.
    within Operator Futurewiz www.futurewiz.co.i ⚫Useful fortesting a condition where a sequence is overlapping in part length of another sequence. seq1 within seq2 ⚫seq1 should happen between start and completion of seq2. sequence seq1; sequence seq2; @(posedge clk) a ##2 b; @(posedge clk) c ##1 !d ##2 e; endsequence endsequence property p1; @(posedge clk) seq1 within seq2; endproperty
  • 516.
    not Operator Futurewiz www.futurewiz.co.i ⚫not operatoris used to check that a particular sequence should not occur. sequence abc; a ##1 b ##1 c; endsequence property nomatch; @(posedge clk) start |-> not (abc); endproperty
  • 517.
    not Operator Futurewiz www.futurewiz.co.i ⚫Example c##1 d should not occur after a ##1 b. property incorrect; @(posedge clk) not (a ##1 b |=> c ##1 d); endproperty ⚫Will report even if a ##1 b does not occur because of vacuous pass. property correct; @(posedge clk) not(a ##1 b ##1 c ##1 d); endproperty
  • 518.
    If-else Expression Futurewiz www.futurewiz.co.i ⚫It ispossible to select property expression based on some condition using if-else expression. property test; @(posedge clk) (req1 || req2) -> if(req1) ##1 ack1; else ##1 ack2; endpropert y
  • 519.
    Local Variables Futurewiz www.futurewiz.co.i ⚫Local variablescan be declared and used inside property and sequence. ⚫These are dynamically created inside sequence instance and removed when end of sequence occurs. ⚫Each instance of sequence has its own set of variables. ⚫A local variable is assigned a value using a comma separated list along with other expressions.
  • 520.
    Example Futurewiz www.futurewiz.co.i sequence s1; int i; (data_valid,(i = tag_in)) ##7 (tag_out == i); endsequence Local variable i is assigned a value of tag_in when data_valid is high. This value is then checked with the value of tag_out 7 clock ticks later.
  • 521.
    Sample Value Functions Futurewiz www.futurewiz.co.i ⚫SpecialSystem Functions are available for accessing sampled values of an expression. o Functions to access current sampled value. o Functions to access sampled value in the past. o Functions to detect changes in sample values. ⚫Can also be used in procedural code in addition to assertions.
  • 522.
    $rose, $fell Futurewiz www.futurewiz.co.i ⚫$rose(expression [,clocking event]) o Returns true if least significant bit changes to 1 with respect to value (0, X, Z) at previous clock else false. ⚫$fell(expression [, clocking event]) o Returns true if least significant bit changes to 0 with respect to value (1, X, Z) at previous clock else false. ⚫Clocking event is optional usually derived from
  • 523.
    $rose vs @(posedge) Futurewiz www.futurewiz.co.i ⚫@(posedgesignal) returns 1 when signal changes from (0, X, Z) to 1 or (0 to X) or (0 to Z). ⚫$rose(signal) is evaluated to true when signal changes from (0, X, Z) to 1 across two clocking event. property p1; @(posedge clk) a ##2 b; endproperty property p2; @(posedge clk) a ##2 $rose(b); endpropert y
  • 524.
    $rose property p2; @(posedge clk)a ##2 $rose(b); endpropert y p 1 Futurewiz www.futurewiz.co.i asserte p2 asserted property p1; @(posedge clk) a ##2 b; endproperty clk a b
  • 525.
    $stable, $past Futurewiz www.futurewiz.co.i ⚫$stable(expression [,clocking event]) o Returns true if value of expression did not change from its sampled value in previous clock else false. ⚫$past(expression [, no of cycles] [, gating expression] [,clocking event]) o Used to access sampled value of an expression any number of clock cycles in past. o no of cycles defaults to 1. o gating expression for clocking event. o clocking event inferred from assertion or
  • 526.
    System Functions andTasks Futurewiz www.futurewiz.co.i ⚫Following System Functions and Tasks are available that can be used in assertions and procedural blocks: o $onehot (expression) Returns true if only one bit of the expression is high. o $onehot0 (expression) Returns true if at most one bit of the expression is high. o $isunknown (expression) Returns true if any bit of the expression is X or Z. o $countones (expression) Returns number of one’s in the expression.
  • 527.
    $asserton, $assertoff, $assertkill Futurewiz www.futurewiz.co.i ⚫disableiff can be locally disable assertions. ⚫$asserton, $assertoff and $assertkill are used to control assertions of a module or list of instance. ⚫$asserton, resume execution of assertions, enabled by default. ⚫$assertoff, temporarily turns off execution of assertions. ⚫$assertkill, kills all currently executing assertions. $asserton(level [, list of modules or instances])
  • 528.
    ⚫A property isused to define behavior of a design. ⚫A property can be used for verification as an assumption, a checker, or a coverage specification. o assert to specify the property as a checker to ensure that the property holds for the design. o assume to specify the property as an assumption for the environment. o cover to monitor the property evaluation for coverage. ⚫A property can be declared in a module, interface, clocking block, package or any compilation unit. ⚫Properties can have formal arguments like sequence declarations. Futurewiz www.futurewiz.co.i Properties
  • 529.
    ⚫Types of Properties o sequence onegation o disjunction o conjunction o if..else o implication o instantiation Futurewiz www.futurewiz.co.i Types of Properties
  • 530.
    ⚫A property expressionmay be a simple sequence expression. ⚫A sequence as a property expression is valid if the sequence is not an empty match. Futurewiz www.futurewiz.co.i Sequence property p2; a ##1 b ##1 c; endproperty property p1; a; endpropert y
  • 531.
    ⚫A property isa negation if it has the form not property_expr ⚫if property_expr evaluates to true, then not property_expr evaluates to false, and ⚫If property_expr evaluates to false, then not property_expr evaluates to true. property p3; @ (posedge clk) not ( a ##1 b ##1 c ); endproperty Futurewiz www.futurewiz.co.i Negation
  • 532.
    ⚫A property isa disjunction if it has the form property_expr1 or property_expr2 ⚫The property evaluates to true if and only if at least one of property_expr1 and property_expr2 evaluates to true. property p4; @ (posedge clk) ( (##[1:3] a) or (b | => c) ); endproperty Futurewiz www.futurewiz.co.i Disjunction (OR)
  • 533.
    ⚫A property isa conjunction if it has the form property_expr1 and property_expr2 ⚫The property evaluates to true if and only if both property_expr1 and property_expr2 evaluate to true. property p4; @ (posedge clk) ( (##[1:3] b) and (c | => d) ); endproperty Futurewiz www.futurewiz.co.i Conjunction (AND)
  • 534.
    if (expression) property_expr1 oEvaluates to true if expression evaluates false. o Evaluates to true if expression evaluates true and property_expr1 also evaluates true. o Others evaluate to False. if (expression) property_expr1 else property_expr2 o Evaluates to true if expression evaluates true and property_expr1 also evaluates true. o Evaluates to true if expression evaluates false and property_expr2 evaluates true. o Others evaluate False. Futurewiz www.futurewiz.co.i If..else
  • 535.
    ⚫A property isan implication if it has either the form o sequence_expr |-> property_expr (overlapping) o sequence_expr |=> property_expr (non- overlapping) Futurewiz www.futurewiz.co.i Implication property p5; a |-> b ##1 c; endproperty property p6; a |=> b ##1 c; endproperty
  • 536.
    ⚫An instance ofa property can be used inside another property. property p1(x, y); ##1 x |-> y; endpropert y property p2; @ (posedge clk) a ##1 b |-> if(c) p1(d, e); endpropert y Futurewiz www.futurewiz.co.i Instantiation
  • 537.
    ⚫A property isrecursive if its declaration contains an instance of itself. property p7(a); a and (1’b1 |=> p7(a)); endproperty ⚫a should hold true in current and next clock cycles. assert property (@ (posedge clk) $fell(reset) |-> p7(b) ); ⚫Assert will make sure that after reset is de- asserted the signal b holds 1 all the time. Anytime b goes asserted . Futurewiz www.futurewiz.co.i Recursive Properties
  • 538.
    ⚫What if wechange above non-overlapping operator to overlapping operator? o Gets stuck in an infinite loop recursion in same cycle resulting in a run-time error. So we need to be careful while using recursive properties. Futurewiz www.futurewiz.co.i Recursive Properties
  • 539.
    Example Design Rule :interrupt must hold until interrupt ack is received. clk int r intr a intr a Futurewiz www.futurewiz.co.i Assertio n Passed Assertion Failed
  • 540.
    property cond( intr, intra); intra or (intr and (1’b1 |=> cond( intr, intra))); endpropert y ⚫The “and” between intr and the recursive call will make sure that if intr goes low before intra - the property/assertion fails. ⚫The “or” makes sure that property passes when intra goes high. Futurewiz www.futurewiz.co.i Example
  • 541.
    ⚫Operator “not” cannotbe used in recursive property instances. property incorrect(p); p and (1’b1 |=> not incorrect(p)); endproperty Futurewiz www.futurewiz.co.i Restriction on Recursive Property
  • 542.
    ⚫The operator “disableiff” cannot be used in the declaration of a recursive property. property incorrect(p); disable iff (a) Futurewiz www.futurewiz.co.i ⚫Rewrite as fpoallonwds(1a’bs1le|g=a>l is not recursive. Restriction on Recursive Property incorrect(p)) ; endpropert y property correct(p); p and (1’b1 |=> correct(p)); endproperty property legal(p); disable iff (b) correct(p)); endproperty
  • 543.
    ⚫If p isa recursive property, then, in the declaration of p, every instance of p must occur after a positive advance in time. property rec(p); p and (1’b1 |-> rec(p)); endproperty ⚫The overlapping operator will make this recursion stuck in an infinite loop Futurewiz www.futurewiz.co.i Restriction on Recursive Property
  • 544.
    ⚫Recursive properties canbe mutually recursive. property chk1; a|-> b and (1’b1 |=> chk2); endproperty property chk2; c |-> d and (1’b1 |=> chk1); endproperty ⚫This is valid as there is time advancement (non- overlapping implication) and there is an antecedent. Futurewiz www.futurewiz.co.i Mutual Recursion
  • 545.
    ⚫Labeling assertions isoptional but highly useful for debugging purpose, always label use meaningfully label. ⚫Label gets printed during failure and also shows up in waveform. ⚫Without label assertions from a module that are instantiated multiple times will be a nightmare to debug. ERROR_q_did_not_follow_d: assert property ( @(posedge clk) disable iff (!rst_n) (q==$past(d)) ); Futurewiz www.futurewiz.co.i Labeling Assertions