⚫ 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?
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
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
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
⚫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
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
⚫ 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;
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”
⚫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.
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
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
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
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;
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.
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
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.
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;
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.
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.
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.
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
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
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.
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
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
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
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
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.
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
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.
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
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
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.
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
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
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.
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
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
⚫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
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
⚫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
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
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
⚫ 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
⚫ 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
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
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
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 }; }
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
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.
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
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
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.
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.
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.
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 :
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,
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 :
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
…………………………
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
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.
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
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
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
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
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
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
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)
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.
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.
⚫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
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.
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.
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)
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
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
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
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.
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.
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.
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
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.
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.
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
⚫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
⚫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
⚫## 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
⚫$ 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.
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
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.
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
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)
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.
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