You are on page 1of 123

SYSTEM VERILOG www.cranesvarsity.

com

System verilog for verification

It is advised that the participants revise the Verilog


Prerequisite that they have studied during their engineering.

© Cranes Varsity V1-2020-21 1/ 123


SYSTEM VERILOG www.cranesvarsity.com

INDEX

No. of
Sl # Topics / Subtopics Session Lab - Y/N Page #

1 Introduction of System Verilog 1 N 4

Definition of system verilog

Environment of Verification

2 Datatype 2 Y 17

2satete

4 state

enum , string , structure, union, class

3 Array 3 24

Array- Fixed array- packed and unpackled array

Dynamic Array, Associative array


Queues

4 Process creation 4 30

Fork-join, Fork-join any, Fork-join none,

wait-fork,Disable fork

5 OOPS concept 5 53

Inheritance,Polymorphism,

Data hiding,
Encapsulation

class

Deepcopy , shalow copy,Overriding class Y

use of Super,this keyword , constructor with


example

6 Interface 6

modport Y

interface

© Cranes Varsity V1-2020-21 2/ 123


SYSTEM VERILOG www.cranesvarsity.com

clocking block

Randomization Method

use of randomization method

pre randomization , post randomization

randomization mode

7 Constraints 7 77

common constarint Y

inline constraint

inside constarint

solve before constarint Y

soft constraint

8 coverage 8 99

functional coverage

coverpoints

covergroup

coverbins

9 Assertion 9 123

passing matrix tofunctions

Introduction of assertion , need of assertion


verification Y

use of $rose,$fell,$stable

Verification of HA , full adder

Verification of mux and demux

Verification of Dff,Tff,counter,register

© Cranes Varsity V1-2020-21 3/ 123


SYSTEM VERILOG www.cranesvarsity.com

CHAPTER - 1

Introduction of System Verilog

What is System verilog?

It is
 HDVL(Hardware Description and verification Language)

(with contrast to verilog)

 So verification is additional part.

 Unified design,modeling ,verification.

 It is Latest IEEEstandard 1800-2012


Evalution of System verilog

there are 4 different languages which donated the stuff that makes the system verilog.

 Verilog hardware design language (Synthesize SV)

i. Verilog was adapted for having design concept say synthesize-able system verilog.

 Object oriented Programming

i. This oops concept adapted so we will be dealing with classes through out the sv
session.

 Randomization

i. This Domain speicific HVL vera and e was adopted for having randomization
process

 Assertion language

Assertion was adapted from open vera assertion language.

What is verification?
Complete validation of design functionality.

Make sure design is bug free by verifying it in all aspects;all possible scenarios.

module half_adder(a,b,s,cout);

output s,cout;

input a,b;

© Cranes Varsity V1-2020-21 4/ 123


SYSTEM VERILOG www.cranesvarsity.com

xor1 u1(s,a,b);

nand1 u2(cout,a,b);

endmodule

Without performing verification questions are as followed

1) Will this work?

2) Will it be bug free?

Stimulating DUT (design under test) with all possible scenarios and comparing its
output with golden results..

How to verify?

From the above block we describe how to perform verification:

 We have taken one example of half adder that is DUT

 and go for next task

 Writting the code for stimulus generator like input generation such as input
a,b to the design.

 Next task is development of reference model.

 Why we need reference model

 Stimulus generator will provide same test cases like a,b to reference model
same like how it provided a and b for DUT.

 Reference model will provide sum carru out

 Last task is

Comparison of logic that actually does comparison between actual output and expected
output.

© Cranes Varsity V1-2020-21 5/ 123


SYSTEM VERILOG www.cranesvarsity.com

Why system verilog for verification?

Verilog was initially used for for writting test bench .But writting complex test bench
is much more of a programming task than describing hardware. No need to synthesize
test bench. So no need to constraint our self to write code into verilog.So we have come
up new language for verification that is system verilog.

The fact is :UVM is replacing SV based verification in industry.

Then why we are not jumping directly to the UVM ?

What is the use of learning first SV.

The reason is -

UVM is nothing but structured SV.So Knowing SV based verification helps under
standingUVM based verification also , or else UVM feels like set of magic macros
which are doing best of themself then we never come to know actual function of
UVM verification.

UVM = Universal verification methodology.

Why is Verilog not preferred for verification?

 Back in the 1990’s Verilog was the primary language to verify functionality of
design that were small , not very complex and had less features.

 As design complexity increases, so does the requirement of better tool to design


verify it.

 Sysytem verilog is far superior to verilog because of its ability to perform


constrained random stimulus, use oops features in test bench construction,
functional coverage, assertion among many others.

Now let me describe what is verification language:

Hard description language like verilog and VHDL are used to describe hardware
behavior which is called design module so that it can be converted to digital block made
up of combinatioanl gates and sequential elements.

After designing the module We need to verify the design to make sure that the design
is an accurate representation of the specification without any bugs. So there is need for
a language with more features in oop that will support complicated testing procedure
and is often called as hardware verification language.Verification is carried out to
ensure the correctness of design, to avoid surprises at a later time, to avoid a re-spin of
the chip and to enter the market on time with good quality.

© Cranes Varsity V1-2020-21 6/ 123


SYSTEM VERILOG www.cranesvarsity.com

In verification, the use the Testbench/Verification environment to determine the


correctness of the design under test (DUT).

Below is the functionality of the Testbench/Verification environment,


 Generate stimulus
 Apply stimulus to the DUT
 Capture the response
 Check for the correctness
 Measure progress against the overall verification goals
Verification plan contains the following

 Overview

 Resources, Budget and Schedule

 Verification Environmen

 System Verilog Verification Flow

 Feature Extraction

 Stimulus Generation Pla

 Checker Plan

 Coverage Plan

 Details of reusable components

Asic Verification

System verilog is extension of verilog with many such verification features that allow
engineers to verify the design using complex testbench structure and random stimuli in
simulation.

© Cranes Varsity V1-2020-21 7/ 123


SYSTEM VERILOG www.cranesvarsity.com

It combines the features of Hardware Description Languages such as Verilog and


VHDL with features from specialised Hardware Verification Languages, together with
features from C and C++.SystemVerilog is finding practical application in the areas of
concise and productive RTL coding, Assertion Based Verification, and building
coverage-driven verification environments using constrained random techniques.

Issues Facing by RTL and verification engineer:

 Designs are getting bigger

 Need to code for reuse and higher abstraction

 Need for more efficient constructs

 Test benches are growing exponentially

 Generate more tests faster

 More advanced techniques needed over traditional simulation.

 Need ways to measures verification progress

 What user want

 An incremental change to their existing environment.

 Re-use of existing code

 Minimal learning curve

Linear test bench:

Linear Test Bench is the simplest, fastest and easiest way of writing test benches.It is
also slowest way to execute stimulus.In this Test Bench, simple linear sequence of test
vectors is mentioned.The code snippet shows some input combination only. This is also
bad for simulator performance as the simulator must evaluate and schedule a very large
number of events. This reduces simulation performance in proportion to the size of the
stimulus process.

Linear test benches perform the following tasks:

 Instantiate the design under test (DUT)

 Stimulate the DUT by applying test vectors.

 Output results waveform window or to a terminal for visual inspection manually.

Example Linear test Bench:

Module addr(a,b,c); //dut code start

© Cranes Varsity V1-2020-21 8/ 123


SYSTEM VERILOG www.cranesvarsity.com

Input [3:0] a,b;

Output [16:0] y;

Assign y=a+b;

Endmodule

Module top(); //test bench code start

Reg a,b;

Wire c;

Adder dut(.a(a),.b(b),.c(c));

Initial begin

a=4’b1001;

b=4’1100;

#10 $display(“a=%d,b=%b,c=%b”, a,b,c);

End

endmodule

 To test all possible scenarios which are known to us, it is not an easy task.

 Development time increases exponentially as the number of scenarios increases


and maintain them is very difficult.

 Instead of listing out all the possible scenarios, pickup some randomly and check
the DUT.

Now let us take the example of a linear random test bench:

Linear Test bench:

Random Test Bench don't use Hardcoded values like linear testbenchs. Input stimulus
is generated using random values. In Verilog, system function $random provides a
mechanism for generating random numbers. The function returns a new 32-bit random
number each time it is called. These test cases are not easily readable and are also not
reusable. New tests have to be created when the specification or design changes, to
accommodate the changes. The main disadvantage of this testing is that we never know
what random values are generated and it may waste simulation cycles by generating
same values again and again.

module top(); //test bench code start

© Cranes Varsity V1-2020-21 9/ 123


SYSTEM VERILOG www.cranesvarsity.com

reg a,b;

wire c;

Adder dut(.a(a),.b(b),.c(c));

Initial begin

repeat(20) begin

a=$random;

b=$random;

#10 $display(“a=%d,b=%b,c=%b”, a,b,c);

end

End

endmodule

How does a Verification engineer check whether the results obtained from the
simulation match the original specification of the design?

 For simple test benches like the above, output is displayed in waveform window or
messages are sent to terminal for visual checking. Visually checking is the oldest
and most labor intensive technique.

 The quality of the verification depends on the determination and dedication of the
individual who is doing the checking. It is not practical to verify a complex model
merely by examining the waveform or text file. Whenever a change is made to the
DUT to add a new feature or to fix a bug, same amount of effort needs to be
deployed to check the simulation results.

Self checking test bench:

A self-checking Test Bench checks expected results against actual results obtained from
the simulation. Although Self-checking testbenchs require considerably more effort
during the initial test bench creation phase, this technique can dramatically Reduce the
amount of effort needed to re-check a design after a change has been made to the DUT.
Debugging time is significantly shortened by useful error-tracking information that can
be built into the Test Bench to show where a design fails.

© Cranes Varsity V1-2020-21 10/ 123


SYSTEM VERILOG www.cranesvarsity.com

A self-checking TestBench has two major parts, the input blocks and output blocks.
Input block consist of stimulus and driver to drive the stimulus to DUT. The output
block consists of monitor to collect the DUT outputs and verify them.

All the above approaches require the test writer to create an explicit test for each feature
of the design.

Verification approach in which each feature is written in a separate test case file is
called directed verification.

Example:

Adder example:

module tb();

Reg [3:0] a;

Reg[3:0] b;

Wire [3:0] c;

Adder dut(.a(a),.b(b),.c(c)); //dut instantiation

Initial

Repeat(20) begin

A=$random; //apply random stimulus

B=$random;

$display(“a=%b,b=%b,c=%b”,a,b,c);

If(a+b=!c) // monitor logic

$display(“error”);

end

endmodule

© Cranes Varsity V1-2020-21 11/ 123


SYSTEM VERILOG www.cranesvarsity.com

In Directed verification, the Verification Environment has mechanism to send the


Stimulus to DUT and collect the responses and check the responses.

The Stimulus is generated in Tests case. Directed testbenchs may also use a limited
amount of randomization, often by creating random data values rather than simply
filling in each data element with a predetermined value.

Each test case verifies specific feature of the design. This becomes tedious when the
design complexity increases. As circuit

complexity increases, it becomes more difficult to create patterns that fully exercise the
design.

Test case maintenance become harder and time consuming.

In direct verification, test writer has to list out each feature.

Test writer cannot think of all possible potential bugs scenarios and there are chances
that Bugs will escape.

With these approaches, the bugs which are not still hidden in these corners of the code
until later in the development cycle, or aren't found at all until product is taped out.

Solution to the above problems is Constraint random verification.

 Using constraint random verification, the stimulus required to verify test features
are generated automatically.

 Test writer specifies set of specification, and the Test Bench automatically creates
solution space and picks up scenarios from the solution space.

 Constraint random verification also reduces manual effort and code for individual
tests.

© Cranes Varsity V1-2020-21 12/ 123


SYSTEM VERILOG www.cranesvarsity.com

 As the scenarios are generated automatically by the TestBench, the number of test
case files gets reduced.

In Directed verification, some of the tests share similar logic, if the engineer has to
change the logic which is common to certain group of tests, then he has to edit all the
test case files and it is time consuming. But in Constraint random verification, the
number of tests case files will be very less, so changes will be mostly in environment
and minimal.

SystemVerilog Test Bench:

Test Bench or Verification environment is a group of classes or components. where


each component is performing a specific operation. i.e, generating stimulus, driving,
monitoring, etc. and those classes will be named based on the operation.

Discuss about each component of verification environment

NAME TYPE DESCRIPTION

Transaction CLASS Defines the pin level activity generated by agent


(to drive to DUT through the driver) or the
activity has to be observed by agent
(Placeholder for the activity monitored by the
monitor on DUT signals).

GENERATOR CLASS Generates the stimulus (create and randomize


the transaction class) and send it to Driver.

DRIVER CLASS Receives the stimulus (transaction) from the


generator and drives the packet level data inside

© Cranes Varsity V1-2020-21 13/ 123


SYSTEM VERILOG www.cranesvarsity.com

a transaction into pin level (to DUT).

MONITOR CLASS Observes pin level activity on interface signals


and converts into packet level which is sent to
the components such as scoreboard.

SCOREBOARD CLASS Receives data items from monitors and


compares them with expected values.
Expected values can be either golden reference
values or generated from the reference model.

ENVIRONMENT CLASS The environment is a container class for


grouping higher level components like agent's
and scoreboard.

TEST PROGRA The test is responsible for,


M
 Configuring the testbench.
 Initiate the testbench components
construction process.
 Initiate the stimulus driving.

TEST_BENCH TOP MODULE this the top most file,which connect the dut and
UP test bench. it consist of dut and test bench. it
consist of dut, test bench and interface
instance,the interface connect the dut and test
bench.

In the process of verification, we are going to verify modules by driving the input to
check the design behavior. we should check the behavior of the design by driving
correct and an error input, in both cases need to observe the design as it is behaving as
expected, if not then there will be a bug.

In verification, we use the Testbench/Verification environment to determine the


correctness of the design under test (DUT).
below is the functionality of the Testbench/Verification environment,
 Generate stimulus
 Apply stimulus to the DUT
 Capture the response
 Check for the correctness
 Measure progress against the overall verification goals
Chapter-3
So now having basic knowledge of data types.

© Cranes Varsity V1-2020-21 14/ 123


SYSTEM VERILOG www.cranesvarsity.com

 Agenda of this lecture is-


 Logic
 Data types classification
 Group of data object
 Net

In verilog we have used data types reg , wire etc but here logic replaces reg.
Why?
reg kyeword was getting to much confused with word flipflop.
User was not able to understand whethere reg keyword will be directly mapped with
the ff and latch. Or any other things.
By using logic - User no need to bother about that.
Logic can be reg or net depending on the usage.

Logic - state data types

4 state values representation Equivalent 2state velues

0 False condition 0

1 True condition 1

x Unknown logic value 0

z High impedence 0
state(open connection)

Each 4 states values is equivalent is some 2state values.


0 and 1 are equivalent to 0 and 1.
But x and z states are equivalent is 0 for 2 state.
The advantage of this datatype is no need to port list rules.
Group of data object:
Differ in the way in which they are assigned and hold values.
Net Variable
Written one or more continious Written by one or more procedural
assignment. statement
Cannot be procedurally assignment Written by one continuous assignment
Shall not store a value Store and hold values:last written value
determines the actual value.

System verilog data types:


 Two state data types

© Cranes Varsity V1-2020-21 15/ 123


SYSTEM VERILOG www.cranesvarsity.com

 Integer, Void, String, Event data Types


 User-defined Data Type
 Enumerations
 Class data type

Two State data types:


Two state data types improves the performance and memory usage over four data types.
two-state data types are bit, byte, int, shortint, longint, byte.

bit – Unsigned
byte, shortint, int, longint –Signed

unsigned two-state types:

bit single_bit ; // unsigned single bit


bit [31:0] 32_bit ; // 32-bit unsigned integer

signed two-state types:

int integer ; // 32-bit signed integer


byte 8_bit ; // 8-bit signed integer
shortint 16_bit ; // 16-bit signed integer
longint 64_bit ; // 64-bit signed integer

String:

A string is data types is variable size, it is dynamically allocated array of bytes.

String declaratrion example:

String s1 = “hello world”

String s2 ={“hi, s1”};

Below is the example of string:

Program main1;

Initial begin

String s1= “helllo world”;

String s2= “hi”;

$display(“String s1=%s”, s1);

$display(“|string s2=%s”,s2);

End

© Cranes Varsity V1-2020-21 16/ 123


SYSTEM VERILOG www.cranesvarsity.com

Endprogram

Output:

String 1 s1 = hello world

String 2 s2 = h

Enumeration / enum Data Type:

An enumerated type defines a set of named values. The simplest enumerated type
declaration contains a list of constant names and one or more variables.

Below is the example for enum data types:

enum{red,green,blue}colors

Default variable will get default values 0,1,2 respectively from red.

Enumerated types methods:

first() -- > returns the value of the first member of the enumeration.

last() -- > returns the value of the last member of the enumeration.

next() -- > returns the value of next member of the enumeration.


next(N) -- > returns the value of next Nth member of the enumeration.

prev() -- > returns the value of previous member of the enumeration.

prev(N)-->returns the value of previous Nth member of the enumeration.

num() -- > returns the number of elements in the given enumeration.

name()-- > returns the string representation of the given enumeration value.

Example of enum :

enum{red=0, green,blue=4,yellow,white=10,black}colors

Green,yellow and black aytomatically assigned to the increment value of


1,5,11respectively.

Another example:

enum { red=0, green=0, blue=4, yellow, white=5, black=6 } Colors

From the above example yellow will get the increment value of 5 , the value of white
is set with 5. This will cause the syntax error.

Example of enum datatypes:

© Cranes Varsity V1-2020-21 17/ 123


SYSTEM VERILOG www.cranesvarsity.com

module enum_data;

//declaration

enum{red,green,yellow,white,black}colors;

Integer i;

Initial begin

Colors=colors.first;

for(i=0; i<6; i=i +1)

begin

$display(“colors::value of colors name is =%d”,colors.name,colors);

Colors=colors.next;

end

end

endmodule

Below exapmle shows an error in case of automatic increment value , is same as the
value assigned to another enum member.

module enum_datatypes;

enum{red=0,green=1, blue=4, white,yellow=5,black=6}colors;

Initial begin

Colors=colors.first;

For(i=0;i<6; i=i+1)

$display(“colors :: value of colors is =%d”, colors.name(),colors);

end

endmodule

module enum_data;

typedef enum {red,green,yellow,blue}colors;

Initial begin

Colors colors;

© Cranes Varsity V1-2020-21 18/ 123


SYSTEM VERILOG www.cranesvarsity.com

Colors=yellow;

$display(“colors.first=%d”, colors.first);

$display(“colors.last=%d”, colors.last);

$display(“colors.next=%d”,colors.next);

$display(“colors.prev=%d”,colors.prev);

$display(“colors.num=%d”,colors.num);

$display(“colors.name=%d”, colors.name);

end

endmodule

Output:

Colors.first=0;

Colors.last=3

Colors.next=3;

Colors.prev=1;

Colors.num=4;

Colors.name=yellow;

Structures: The disadvantages of array is that all the elements stored in then are to be
of the same data types. If we need to use collection of different data types, it is not
possible using array. When we require using a collection of different data items of
different data types we can use a structure.

A structure represents a collection of data types that are stored together.

So structure is convenient method of handling a group of related data items of different


data types.

Declaration:

Struct{

int a;

byte b;

© Cranes Varsity V1-2020-21 19/ 123


SYSTEM VERILOG www.cranesvarsity.com

Bit[7:0]c;

Packed Structure:A packed structure is a mechanism for subdividing a vector into sub
fields that can be conveniently accessed as members.

A packed structure consists of bit fields, which are packed together in memory without
gaps.

A packed struct must be declared explicitly using keyword "packed".

Struct packed{

int a;

bit[7:0] b;

byte c;

Union:

Unions like structure contain members whose individual data types may differ from
one another.

The members that compose a union all share the same storage area.

A union allows us to treat the same space in memory as a number of different variables.

Example:

union{

int a;

bit[7:0] b;

byte c;

© Cranes Varsity V1-2020-21 20/ 123


SYSTEM VERILOG www.cranesvarsity.com

String: A typedef declaration lets you define your own identifiers that can be used in
place of type specifiers such as int, byte, real.

Let us see an example of creating data type "nibble".

typedef bit [7:0] nibble; //defining nibble data type.

Advantages of using typedef:

 Shorter names are easier to type and reduce typing errors.

 Improves readability by shortening complex declarations.

 Improves understanding by clarifying the meaning of data.

 Changing a data type in one place is easier than changing all of its uses throughout
the code.

 Allows defining new data types using structs, unions and Enumerations also.

 Increases re usability.

Array:

An array is a collection of variables, all of the same type, and accessed using the same
name plus one or more indices.

declaration of array: int marks[5];

Initialization of Array:

marks[0]=80;//initialization of array

marks[1]=60;

marks[2]=70;

marks[3]=85;

marks[4]=75;

© Cranes Varsity V1-2020-21 21/ 123


SYSTEM VERILOG www.cranesvarsity.com

Fixed size array:


Single Dimension array

int marks[5]={20,30,40,50,60};

Two Dimension Array:

data_type array_name[rows][columns]

int two dimen[4][3];

Initialization of 2D Array:

int arr [4][3]= {{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

TYPES OF ARRAY:

Fixed size array

Packed array

unpacked array

Dynamic array

Associative array

Queues

Fixed size array:


In fixed size array, array size will be constant throughout the simulation, Once the
array is declared no need to create it. By default, the array will be initialized with value
‘0’.

Packed Array:
The term packed array is used to refer to the dimensions declared before the data
identifier name.

Bit[7:0] array1;

Bit[2:0][7:0]arary5;

© Cranes Varsity V1-2020-21 22/ 123


SYSTEM VERILOG www.cranesvarsity.com

Unpacked array:
The term unpacked array is used to refer to the dimensions declared after the data
identifier name.

Bit [7:0]array1[2:0];

An unpacked array may or may not be so represented as a contiguous set of bits.

Dynamic Array:
A dynamic array is one dimension of an unpacked array whose size can be set or
changed at run-time.

Dynamic array is Declared using an empty word subscript [ ].

The space for a dynamic array doesn’t exist until the array is explicitly created at run-
time, space is allocated when new[number] is called.

//Declaration:

Bit[7:0]d_array1;

//memory allocation

D_array1=new[6];

D_array2=new[4];

//array initialization

D_array1={0,1,2,3};

Resize the dynamic array:

© Cranes Varsity V1-2020-21 23/ 123


SYSTEM VERILOG www.cranesvarsity.com

D_array1=new[10](d_array1);

//dynamic array declaration

Bit[7:0]d_array[];

//memory allocation

D_array=new[4];

//array initialization

D_array={0,1,2,3};

resize the dynamic array:

D_array1=new[10]D_array

Delete dynamic array:

//delete array:

D_array1.delete.

Array_name .delete() method will delete the array.

Example of dynamic array:

module dynamic_array;

Bit[7:0] d_array1;

int d_array2;

Integer i;

Initial begin

d_array1=new[2];

© Cranes Varsity V1-2020-21 24/ 123


SYSTEM VERILOG www.cranesvarsity.com

d_array2=new[3];

//array initialization

d_array1={1,2};

d_array2={11,1,4};

Foreach (d_array[i]);

$display(“d_array2=%d”,I,d_array2[i]);

d_array1.delete;

D_array2.delete;

$display(“d_array1=%d”,d_array1.size());

$display(“d_array2=%d”,d_array2.size());

End

Endmodule

Output:

d_array2=x 0

d_array1=0

d_array2=0

Associative array:

Associative arrays allocate the storage only when it is used, unless like in the dynamic
array we need to allocate memory before using it.

When the size of the collection is unknown or the data space is sparse, an associative
array is a better option.

In Associative arrays Elements Not Allocated until Used.

Associative Array Methods:


num() --> returns the number of entries in the associative array.

delete(index)-->removes the entry at the specified index.exa_array.delete(index).

exists(index)--> returns 1 if an element exists at the specified index else returns 0.

first(var) --> assigns the value of first index to the variable var.

last(var) --> assigns the value of last index to the variable var.

© Cranes Varsity V1-2020-21 25/ 123


SYSTEM VERILOG www.cranesvarsity.com

next(var) --> assigns the value of next index to the variable var.

prev(var) --> assigns the value of previous index to the variable var.

//Array declaration

int a_array1[*];

Bit[31:0]a_array2[string];

Queue:

A queue is a variable-size, ordered collection of homogeneous elements.

 like a dynamic array, queues can grow and shrink


 queue supports adding and removing elements anywhere.
 Queues are declared using the same syntax as unpacked arrays, but specifying $
as the array size.

 In queue 0 represents the first, and $ representing the last entries.

Queue Declaration:
bit queue_1[$];

int queue_2[$];

byte queue_3[$:255];

string queue_4[$];

//queue initialization

queue_1={1,2,3,4};

queue_4={ “red” , “green”, “blue”};

Queue Methods:
size() --> returns the number of items in the queue.

insert() --> inserts the given item at the specified index position.

delete() --> deletes the item at the specified index position.

push_front() -->inserts the given element at the front of the queue.

push_back() -->inserts the given element at the end of the queue.

pop_front() -->removes and returns the first element of the queue.

pop_back() -->removes and returns the last element of the queue

© Cranes Varsity V1-2020-21 26/ 123


SYSTEM VERILOG www.cranesvarsity.com

Example:

module queues_array;

Bit[31:0] queue_1[$];

Int var1;

Initial begin

queue_1={1,2,3,4,5,6};

$display(“queue_1 of the size is %d”, queue_1.size());

queue_1.push_front(45);

$display(“queue_1 push_front value is %d”,queue_1.size());

queue_1.push_back(55);

Var1=queue_1.pop_front():

$display(“queue_1 pop_front value is %d”,var1);

Var1=queue_1.pop_back();

$display(“queue_1 pop_back value is %d”,var1);

End

Endmodule

Output:Queue_1 of the size is 6;

Queue_1 push_front value is 7;

© Cranes Varsity V1-2020-21 27/ 123


SYSTEM VERILOG www.cranesvarsity.com

Queue_1pop_front value is 45;

Queue_1 pop_back value is 55;

Process:

Fork join:

Fork-Join will start all the processes inside it parallel and wait for the completion of all
the processes.

Statement1

Statement2

Fork

Process-1

Process-2

Process-3

Join

Statement-3

Statement-4

On start of simulation, statements get executed sequentially.Process inside the fork will
get executed parallel.statement-3 and ststement-4 will get executed after the completion
of process inside the fork.

Fork join example:

module fork_join;

Initial begin

$display(“a”);

#5 $dispaly(“b”);

Fork

Begin

$display(“c”);

$display(“d”);

End

© Cranes Varsity V1-2020-21 28/ 123


SYSTEM VERILOG www.cranesvarsity.com

begin

$display(“e”);

$display(“f”);

end

Join

$display(“g”);

$dispaly(“h”);

End

Endmodule

Output:

a,b,c,d,e,f,g,h

fork join_any:
Fork-Join_any will be unblocked after the completion of any of the Processes.

Statement1

Statement2

Fork

Process-1

Process-2

Process-3

end

Join_any

Statement-3

Statement-4

Any one of the process under fork is getting executed then statement-3 or statement-4
will be executed.

Example:

module fork_join1;

© Cranes Varsity V1-2020-21 29/ 123


SYSTEM VERILOG www.cranesvarsity.com

initial begin

Fork

//process-1

Begin

$display(“process-1 started”);

#5

$dispaly(“process-1 finished”);

End

//process-2

Begin

$display(“process-2 started”);

#20

$display(“process-2 finished”);

End

Join_any

$display(“out side of the fork”);

End

Endmodule

Output:

Process-1 started

Process-2 started

Process-1 finished

Outside fork_join

Process-2 finished

Fork join_none:

As in the case of Fork-Join and Fork-Join_any fork block is blocking, but in case of
Fork-Join_none fork block will be non-blocking.

© Cranes Varsity V1-2020-21 30/ 123


SYSTEM VERILOG www.cranesvarsity.com

Processes inside the fork-join_none block will be started at the same time, fork block
will not wait for the completion of the Process inside the fork-join_none.

module fork_join1;

initial begin

Fork

//process-1

Begin

$display(“process-1 started”);

#5

$dispaly(“process-1 finished”);

End

//process-2

Begin

$display(“process-2 started”);

#20

$display(“process-2 finished”);

End

Join_any

$display(“out side of the fork”);

End

Endmodule

Output:

Outside fork_join

Process-1 started

Process-2 started

Process-1finished

Process-2 finished

© Cranes Varsity V1-2020-21 31/ 123


SYSTEM VERILOG www.cranesvarsity.com

wait fork:
wait fork; causes the process to block until the completion of all processes started
from fork blocks.

Module wait_fork;

Initial begin

Fork

Begin

$display(“a”);

#5

$display(“b”);

End

Begin

$display(“c”);

#20

$display(“d”);

End

Join_any

//Wait fork;

$finish;

End

Endmoduloe

Without waitfork output is a,c,b

Module wait_fork;

Initial begin

Fork

//process-1

Begin

© Cranes Varsity V1-2020-21 32/ 123


SYSTEM VERILOG www.cranesvarsity.com

$display(“a”);

#5

$display(“b”);

End

//process-2

Begin

$display(“c”);

#20

$display(“d”);

End

Join_any

Wait fork;

$finish;

End

Endmoduloe

Output :

a,c,b,d.

From the above result we can say that wait fork will wait for the completion of the
second thread in the fork-join_any.

disable fork:
disable fork; causes the process to kill/terminate all the active processes started from
fork blocks.

Tasks:
Tasks and Functions provide a means of splitting code into small parts.

A Task can contain a declaration of parameters, input arguments, output arguments, in-
out arguments, registers, events, and zero or more behavioral statements.

Below is list of rules for task:

 Task can have multiple no. Of inputs and outputs.

© Cranes Varsity V1-2020-21 33/ 123


SYSTEM VERILOG www.cranesvarsity.com

 Task can have time delay.

 Task can call other task or function.

 Task can use blocking and non blocking assignment.

task example:

Module sv_task;

int x;

Task sum(input a,b, output int c);

c=a+b;

Endtask

Initial begin

Sum(10,5,x);

$display(“value of x=%d”, x);

End

Endmodule

Fuinction:

A Function can contain declarations of range, returned type, parameters, input


arguments, registers, and events.

Below is list of rules for function:

 Function can not enable task.

 Function definition must contain at least one input arguments.

 A function definition can not contain a inout declaration or output declaration.

Function example:

Module sv_function;

int x;

Function int sum( input int a,b);

Sum=a+b;

Endfunction

© Cranes Varsity V1-2020-21 34/ 123


SYSTEM VERILOG www.cranesvarsity.com

Initial begin

X=sum(10,5);

$display(“the value of x=%d”,x);

End

Endmodule

Output: x=15

Function with return value and return keyword:

Module sv_function;

int x;

Function int sum;

Input int a,b;

return a+b;

endfunction

Initial begin

X=sum(10,5);

$display(value of x=%d”,x);

End

endmodule

argument pass by value example:


In argument pass by value,

The argument passing mechanism works by copying each argument into the subroutine
area.

If any changes to arguments within the subroutine, those changes will not be visible
outside the subroutine.

Module argument_passing;

int x,y,z;

© Cranes Varsity V1-2020-21 35/ 123


SYSTEM VERILOG www.cranesvarsity.com

Function int sum (int x,y);

x=x+y;

Return x+y;

Endfunction

Initial begin

X=20;

Y=30;

$display(“the value of x=%d”,x);

$dipslay(“the value of y=%d”,y);

$display(“the value of z=%d”, z);

End

Endmodule

Output:

Value of x=20

Value of y=30

Value of z=80;

argument pass by reference:


 In pass by reference, a reference to the original argument is passed to the
subroutine.

 As the argument within a subroutine is pointing to an original argument, any


changes to the argument within subroutine will be visible outside.

 To indicate argument pass by reference, the argument declaration is preceded by


keyword ref.

Module argument_resference;

Function int sum (ref int x,y);

x=x+y;

Return x+y;

Endfunction

© Cranes Varsity V1-2020-21 36/ 123


SYSTEM VERILOG www.cranesvarsity.com

Initial begin

x=20;

y=30;

$dispaly(“the value of x=%d”,x);

$display(“the valye of y=%d”,y);

$display(“the value of z=%d”,z);

end

endmodule

Value of x=50;

Value of y=30;

Value of z=80;

Chapter-3
1. Basic

A. Datatype

B. Properties

© Cranes Varsity V1-2020-21 37/ 123


SYSTEM VERILOG www.cranesvarsity.com

C. Method

D. Constructor

2. Inheritance

A. class declarations extended from other class

3. Polymorphism

A. Concept and casting

4. Virtual Method and classes

A. Making polymorphism class method

5. Randomization

A. Randomization of class properties

6. Constarint

A. Declaration constraint for class randomization.

SystemVerilog Class:

A class is a user-defined data type that includes data (class properties), functions and
tasks that operate on data.

Class object dynamically created and deleted during simulation.

functions and tasks are called as methods, both are members of the class.

System verilog supports standards object oriented programming features such as

 Inheritance

 Data hiding and encapsulation

 Polymorphis

Now discuss about variable of the class type:

Class Declaration
example:

Class sv_class;

// class property;

Int x; // a variable declaration

© Cranes Varsity V1-2020-21 38/ 123


SYSTEM VERILOG www.cranesvarsity.com

// method1;

Task set (int i);

X=I;

Endtask

//method2;

Function int get();

Return x;

Endfunction

Endclass

How to create an array of classes ?

An array of classes can be created in a similar way to how you can create an int type:

module tb;

mypacket pkt [3];

Initial begin

For (i=0; i<10; i =i+1;)

Pkt[i]=new();

Pkt[i].diaplay();

End

End

Endmodule

What is class handle?

A class variable such as pkt below is only a name by which that object is known. It can
hold the handle to an object of class packet, but until assigned with something it is
always null. At this point, the class object does not exist.

Class packet;

© Cranes Varsity V1-2020-21 39/ 123


SYSTEM VERILOG www.cranesvarsity.com

int count;

Endclass

module tb;

// create a “handle” for the class packet that can point to an object of the class type
packet.

//now this handle is pointing to null

Packet pkt;

Initial begin

If(pkt==null)

// display the class member using “handle”

//expecting run time error because pkt is not an object

// yet and still pointing to null. Pkt is not aware that it should hold the number.

$display(“count=%d”,pkt.count);

End

Endmodule

What is class object?

Class properties and methods can be accessed only after creating the object.

Class_1=new();

Accessing class properties and methods :

Class properties and methods

Class packet;

Bit[31:0] addr;

function new();

addr=32’h 23;

Module tb();

© Cranes Varsity V1-2020-21 40/ 123


SYSTEM VERILOG www.cranesvarsity.com

Initial begin

Packet pkt=new();

$dipslay(“”addr=%d”, adddr);

end

end

Module can be accessed by using object names followed by property or method name.

System verilog constructor:

A constructor is simply method to create a new object of a particular clas data type.

By calling new method it allocates the memory and returns the address to the class
handle.

Example of class constructor

//class declaration

Class packet;

//class properties

Bit [7:0] a;

Bit [7:0] b;

Endclass

//declare the handle

Packet pkt;

//construct the object

Pkt=new();

Calling new() allocates memory, returns the address and initialize the variables to
default values.

 The new operation is defined as a function with no return type

© Cranes Varsity V1-2020-21 41/ 123


SYSTEM VERILOG www.cranesvarsity.com

 every class has a built-in new method, calling the constructor of class without
the explicit definition of the new method will invoke the default built-in new method
 specifying return type to the constructor shall give a compilation error (even
specifying void shall give a compilation error)
 The constructor can be used for initializing the class properties. In case of any
initialization required, those can be placed in the constructor and It is also possible to
pass arguments to the constructor, which allows run-time customization of an object.

 Variable’s initialization by constructor|:

//class declaration

Class packet;

//classa properties

Bit[3:0] addr;

Bit [3:0]data;

//constructor

Function new(bit[3:0]a,b);

Addr=a;

Data=b;

Endfunction

Endclass

//declare the handle

Packet pkt;

//construct the object

Pkt=new(10,20);

Now we will see one example of the constructor:

Class constructor example:

Class packet;

© Cranes Varsity V1-2020-21 42/ 123


SYSTEM VERILOG www.cranesvarsity.com

//class properties

Bit[3:0]addr;

Bit[3:0] data;

Bit write ;

//constructor

Function new();

Addr=4’d3;

Data=4’d7;

Write=1;

endfunction

Function void display();

$display(“addr=%d,data=%d”,addr,data);

endfunction

endclass

Module constructor_method;

Packet pkt;

Initial begin

Pkt=new();

Pkt.display();

End

Endmodule

Output :

Addr=3

Data=7

Write=1

 SystemVerilog Class Assignment


Class Assignment:

© Cranes Varsity V1-2020-21 43/ 123


SYSTEM VERILOG www.cranesvarsity.com

Object will be created only after doing new to an class handle,

packet pkt_1;
pkt_1 = new();
packet pkt_2;
pkt_2 = pkt_1;

In the above piece of code explanation:

 an object is created only for pkt_1, pkt_2 is just a handle to the


packet
 pkt_1 is assigned to the pkt_2. so only one object has been created,
pkt_1 and pkt_2 are two handles both are pointing to the same object
 As both the handles are pointing to the same object any changes made with
respect to pkt_1 will reflect on pkt_2

© Cranes Varsity V1-2020-21 44/ 123


System verilog www.cranesvarsity.com

Example of class assignment:

Class packet;

//class properties

Bit[3:0]addr;

Bit[3:0] data;

Bit write ;

//constructor

Function new();

Addr=4’d4;

Data=4’d7;

Write=1;

Endfunction

Function void display();

$display(“addr=%d,data=%d”,addr,data);

endfunction

endclass

Module assignment;

Packet pkt1;

Packet pkt2;

Initial begin

Pkt1=new();

Pkt1.display();

//assign pkt1 to pkt2

Pkt2=pkt1;

Pkt2.display();

//changing the value with pkt2 handle

Pkt2=4’d9;
© Cranes Varsity V1-2020-21 45/ 123
System verilog www.cranesvarsity.com

$display(“.. calling pkt1 display”);

Pkt1.display();

End

Endmodule

Output:

Calling pkt1 display

Addr=13

Data=15

Calling pkt2 display

Addr=13

Data=15

Shallow copy:

Content in pkt will be copied into pkt2 when pkt is used along with the new() constructor for
the new object.

Declaration of shallow copy:

Packet pkt1,pkt2;

Pkt1=new();

Pkt2=new pkt1;

This method is known as shallow copy.because all of the variable are copied across integers ,
string,instance handle etc but nested nested object are not copied entirely. Only their handles
will be assigned to the new object and hence both the packets will point to the same nested
object instance.

Class packet;

Bit [7:0] a;

Bit [7:0] b;

//constructor

Function new();

© Cranes Varsity V1-2020-21 46/ 123


System verilog www.cranesvarsity.com

a=8’h12;

b=8’h14;

Endfunction

Function display();

$display(“a=%h”,a);

$display(“b=%h”,b);

Endfunction

Endclass

Module main_class;

packet p1;

Packet p2;

Initial begin

P1=new();

P1.display();

P2=new p1;

P2.display();

P1.b=8’h15;

P1.display();

P2.display();

End

Endmodule

Output

A=12------------>display the value of a

A=12------------>created object of the memory

A=15------------>change in the value of object but no nested for object b only handler copied.

A=12------------>old value displayed again


© Cranes Varsity V1-2020-21 47/ 123
System verilog www.cranesvarsity.com

Deep Copy:

 SystemVerilog deep copy copies all the class members and its nested class members.

 unlike in shallow copy, only nested class handles will be copied.

 In shallow copy, Objects will not be copied, only their handles will be copied. to perform

a full or deep copy, the custom method needs to be added.

Packet p1,p2;----------->declaring handle

P1=new();--------------->creating object memory for p1;

P2=new();--------------->creating object memory for p2;

P2.copy(p1);------------>deep copy of p2 from p1;

Example of deep copy:

Class packet;

Bit [7:0] a;

Bit [7:0] b;

//constructor

Function new();

a=8’h12;

b=8’h13;

endfunction

Function display();

$display(“a=%h”,a);

$display(“b=%h”,b);

endfunction

© Cranes Varsity V1-2020-21 48/ 123


System verilog www.cranesvarsity.com

endclass

module main_class;

packet p1;

Packet p2;

Initial begin

P1=new();

P1.display();

P2=new p1;

P2.display();

P1.b=8’h15;

P1.display();

P2.display();

End

endmodule

Output:

A=12-------->display the value of object

B=13-------->display the value of object

A=12-------->creating memory for p1

B=13-------->creating memory for p2

A=12

B=15-------->changed value with pkt2 handle because

A=12

B=1

Oops concept
Inheritance and polymorphism

© Cranes Varsity V1-2020-21 49/ 123


System verilog www.cranesvarsity.com

How to share code between classes:


1. Instantiated a class within another class

2. Inherits from one class to another (inhertance/derivation)

 Inheritance allows us to add extra properties (data member) and methods

 Change the behavior of an existing method

 Common code can be grouped into a base class

 Addition and changes to common code (base class) can go into the derived class

 Reuse existing classes from previous projects with less debug

 Wont break what already works

SystemVerilog Inheritance

 Inheritance is an OOP concept that allows the user to create classes that are built upon
existing classes.

 The new class will be with new properties and methods along with having access to all the
properties and methods of the original class. Inheritance is about inheriting base class
members to the extended class.

 New classes can be created based on existing classes, this is referred to as class inheritance
 A derived class by default inherits the properties and methods of its parent class.
 An inherited class is called a subclass of its parent class
 A derived class may add new properties and methods, or modify the inherited properties
and methods

 Inheritance allows re-usability. i.e. derived class by default includes the properties and
methods, which is ready to use
 If the class is derived from a derived class, then it is referred to as Multilevel inheritance

© Cranes Varsity V1-2020-21 50/ 123


System verilog www.cranesvarsity.com

Inheritance Terminology
Parent Class

 It's an existing class;


 The class whose features are inherited
 The parent class is also known as a base class, superclass

Child Class

 It's an extended class;


 The class that inherits the other class is known as subclass
 The child class is also known as an extended class, derived class, subclass

What can be done in extended classes?


 A subclass inherits all of the public and protected members of its parent.
But all local members can not be inherited
You can use the inherited members as is replace them, hide them, or supplement them with the
new members.
 The inherited field can be used directly, like any other fields.
 You can declare a field / method/ constraint in the extended class with the same name as
the one in the super class, thus hiding it .
 You can declare new fields / methods in the subclass that are not in the super class.
 You can write a subclass constructor that invokes the constructor of the superclass by using
the keyword super.

Inheritance Example:
© Cranes Varsity V1-2020-21 51/ 123
System verilog www.cranesvarsity.com

//base class

Class packet;

Bit [3:0] a;

endclass

// sub class

By using extends keyword base class inherited

Class child_class extends packet;

//child_class is derived from a base class, and it inherits the properties of the parent class.

Bit [3:0] b;

endfunction

Module inheritance;

Initial begin

Child_class pkt;--------->declaration of handler

Pkt=new(); --------------->creating dynamic memory for object

 Pkt.a=10; //Parent class properties are accessed using child class handle, i.e child class will
have parent class properties and methods.

//Though the addr is not declared in child_class, it is accessible. because it is inherited from the
parent class.

Pkt.b=20;

$display(“\t , value of pkt.a=%d, value of pkt.b=%d”,pkt.a,pkt.b);

end

endmodule

Output:

Value of pkt.a= 10

Value of pkt.b= 20

© Cranes Varsity V1-2020-21 52/ 123


System verilog www.cranesvarsity.com

SystemVerilog Polymorphism:
Polymorphism means many forms. Polymorphism in SystemVerilog provides an ability to an
object to take on many forms.

Method handle of super-class can be made to refer to the subclass method, this allows
polymorphism or different forms of the same method.

//example of polymorphism:

Class base_class;

Virtual function void display();

$display(“this is base class”);

Endfunction

Endclass

//extended class 1

Class sub_class_1 extends base_class;

Function void display();

$display(“this is super class1”);

Endfunction endclass

//extended class2

Class sub_class_2 extends base_class;

Function void display();

$display(“thsi is super class2”);


© Cranes Varsity V1-2020-21 53/ 123
System verilog www.cranesvarsity.com

Endfunction endclass

Module class_polymorphism;

Initial begin

//declare and create extended class

Sub_class_1 sc_1=new();

Sub_class_2 sc_2=new();

//base class handle

Base_class bc[2];

//assigning extended class to base class

Bc[0]=sc1;

Bc[1]=sc2;

//accessing extended class method using base class handle

Bc[0].display();

Bc[1].dispay();

End

Endmodule

Output:

This is super class1;

Thsi is super class2;

SystemVerilog Overriding class members


Overriding class members
Base class or parent class properties and methods can be overridden in the child class or
extended class.

Base class or parent class properties and methods can be overridden in the child class or
extended class.

Overriding class member example


In below example,

© Cranes Varsity V1-2020-21 54/ 123


System verilog www.cranesvarsity.com

 The parent class has the method display().

 display() method is re-defined in the child class, which will override the parent class
method.

 c is the handle to the child class, because of override calling c.display will call display
method of the child class, not the parent class.

Example:

Calss base_class;

Bit [3:0] addr;

Function void display();

$display(“addr=%d”,addr);

Endfunction

Endclass

Class sub_class extends base_class;

Bit[3:0] data;

Function void display(); //display method is re defined in the child class which will
overridethe parent classmethod

$display(“data=%d”,data);

Endfunction

Endclass

Module method1;

Initial begin

Sub_class c=new();

B. addr=8;

c.data=12;

C.display();

End

Endmodule

Output:
© Cranes Varsity V1-2020-21 55/ 123
System verilog www.cranesvarsity.com

Data=00001100

SystemVerilog Super keyword


Super keyword
The super keyword is used in a derived class to refer to the members of the parent class.

 When class members are overridden in the derived class, It is necessary to use
the super keyword to access members of a parent class
 With super keyword, it is allowed to access the class members of parent class which is
only one level up
If the method of the parent class is overridden in the child class, then using the 'super' keyword
parent class method can be accessed from the child class.

In below example,
The parent class has the method 'display'.
Implementing the method display in the child class will override the parent class method.
By calling super.display() from child class, the display method of the parent class can be
accessed.

Example:

Calss base_class;

Bit [3:0] addr;

Function void display();

$display(“addr=%d”,addr);

Endfunction

Endclass

© Cranes Varsity V1-2020-21 56/ 123


System verilog www.cranesvarsity.com

Class sub_class extends base_class;

Bit[3:0] data;

Function void display(); //display method is re defined in the child class which will override
the parent class method

$display(“data=%d”,data);

Super.display();

Endfunction

Endclass

Module method1;

Initial begin

Sub_class c=new();

C. addr=8;

c.data=12;

C.display();

End

Endmodule

Output:

Data=00001100

Addr=00001000

If from the above example we remove super.display() from the display method of child class
then output is

Data=00001100

SystemVerilog Casting
Casting
 SystemVerilog casting means the conversion of one data type to another datatype.

© Cranes Varsity V1-2020-21 57/ 123


System verilog www.cranesvarsity.com

 During value or variable assignment to a variable, it is required to assign value or variable


of the same data type. Some situations need assignment of different data type, in such
situations, it is necessary to convert data type and assign.

 Otherwise, the assignment of different data type results in a compilation error.

 The method of data type conversion is called casting.

assigning child class handle to parent class handle


Calss base_class;

Bit [3:0] addr;

Function void display();

$display(“addr=%d”,addr);

Endfunction

Endclass

Class sub_class extends base_class;

Bit[3:0] data;

Function void display(); //display method is re defined in the child class which will
overridethe parent classmethod

$display(“data=%d”,data);

Super.display();

Endfunction

Endclass

Module method1;

Initial begin

Base_class bc=new();

Sub_class c=new();

C.addr=8;

c.data=12;

Bc=c; //assigning child class handle to parent class

C.display();

© Cranes Varsity V1-2020-21 58/ 123


System verilog www.cranesvarsity.com

End

Endmodule

Addr=8

Data=12

assigning parent class handle to child class handle


This assignment is invalid, it leads to a compilation error.

Calss base_class;

Bit [3:0] addr;

Function void display();

$display(“addr=%d”,addr);

Endfunction

Endclass

Class sub_class extends base_class;

Bit[3:0] data;

Function void display(); //display method is re defined in the child class which will
overridethe parent classmethod

$display(“data=%d”,data);

Super.display();

Endfunction

Endclass

Module method1;

Initial begin

Base_class bc=new();

Sub_class c=new();

C.addr=8;

c.data=12;

© Cranes Varsity V1-2020-21 59/ 123


System verilog www.cranesvarsity.com

Bc=c; //assigning child class handle to parent class

C.display();

End

Endmodule

Use of $cast or casting method

In the above example, assigning parent class handle (which is pointing to child class handle) to
child class handle is valid but compilation error is observed.

During the compile time, as the handle of bc is of parent class type which leads to compile
error.

With the use of $cast(), type check during compile time can be skipped.

Example:

Calss base_class;

Bit [3:0] addr;

Function void display();

$display(“addr=%d”,addr);

Endfunction

Endclass

Class sub_class extends base_class;

Bit[3:0] data;

Function void display(); //display method is re defined in the child class which will
overridethe parent classmethod

$display(“data=%d”,data);

Super.display();

Endfunction

Endclass

Class sub_class extends base_class;

Bit[3:0] data;

© Cranes Varsity V1-2020-21 60/ 123


System verilog www.cranesvarsity.com

Function void display(); //display method is re defined in the child class which will
overridethe parent classmethod

$display(“data=%d”,data);

Super.display();

endfunction

endclass

Module method1;

Initial begin

Base_class bc=new();

Sub_class c=new();

Sub_class c1;

C.addr=8;

c.data=12;

bc=c; //assigning child class handle to parent class

$cast(c1,bc); //with the use of $cast, type chek will occur during runtime

C.display();

End

Endmodule

Addr=8

Data=12

Systemverilog Data Hiding and Encapsulation


The technique of hiding the data within the class and making it available only through the
methods, is known as encapsulation.

Because it seals the data (and internal methods) safely inside the "capsule" of the class, where
it can be accessed only by trusted users (i.e., by the methods of the class).

Access control rules that restrict the members of a class from being used outside the class, this
is achieved by prefixing the class members with the keywords

© Cranes Varsity V1-2020-21 61/ 123


System verilog www.cranesvarsity.com

 local
 protected

EXAMPLE: local variblg error

Class parent;

Local int I; // variable I decalred as local

Endclass

Program main

Initial begin

Parent p=new();

P. I=12;

End

Endprogram

Local member 'i' of class 'base' is not accessible from scope 'main'

The above examples gives compilation error.

EXAMPLE: local variblg accessing using method:

Class parent;

Local int I; // variable I decalred as local

Endclass

Function display(int i);

$display(I);

endfunction

Program main

Initial begin

Parent p=new();

P.display=12;

End

© Cranes Varsity V1-2020-21 62/ 123


System verilog www.cranesvarsity.com

Endprogram

Output 12

EXAMPLE: local variblg accessing in extended class:

Class parent;

Local int I; // variable I decalred as local

Endclass

Function display(int i);

$display(I);

Endfunction

//extended class

Class child_class extends parent;

Function new();

i=10;

endfunction

Endclass

Local member 'i' of class 'base' is not accessible from scope 'ext'

A protected class property or method has all of the characteristics of a local member, except
that it can be inherited; it is visible to subclasses.

Class parent;

protected int I; // variable I decalred as protected

Endclass

Function display(int i);

$display(I);

Endfunction

//extended class

Class child_class extends parent;


© Cranes Varsity V1-2020-21 63/ 123
System verilog www.cranesvarsity.com

Function new();

I=10;

endfunction

Endclass

Program main

Initial begin

Child_class sc=new();

sc.display=12;

End

Endprogram

Output:12

Class parent;

protected int I; // variable I decalred as protected

Endclass

Program main

Initial begin

Parent p=new();

P.I=12;

End

Endprogram

Protected member 'i' of class 'base' is not accessible from scope 'main'

System verilog virtual method :

Virtual Methods in SystemVerilog


SystemVerilog Methods declared with the keyword virtual are referred to as virtual methods.

A set of classes can be created that can be viewed as being derived from a common class

For instance a common base class that sets out the structure of the packet is never instantiated
but executed to derive useful subclasses.
© Cranes Varsity V1-2020-21 64/ 123
System verilog www.cranesvarsity.com

Since the base class is not intended to be instantiated it can be made abstract by specifying as
virtual.

Similarly virtual method are meant to be overridden in the extended classes.

SystemVerilog Virtual Methods:

About Virtual Method


In a virtual method,

If the base_class handle is referring to the extended class, then the extended class method handle
will get assigned to the base class handle.

In the below explanation, extended_class is an extended class of base_class.

Base_class bc;

Extended_class ec;

Considering both the class's has the method display().

assigning ec to bc,

Bc=ec;

On calling bc.display()

 if display() method in base_class is virtual, then extended class display method will get
called
 if display() method in base_class is non-virtual, then base class display method will get
called

Virtual Method Examples


Method without virtual keyword
In the below example,
the method inside the base class is declared without a virtual keyword, on calling method of the
base class which is pointing to the extended class will call the base class method.

Class parent;

Function void display();

$display(“ this is parent class”);

Endfunction

Endclass

© Cranes Varsity V1-2020-21 65/ 123


System verilog www.cranesvarsity.com

Class extpacket1 extends parent;

Funstion display();

$display(“ this is sub class1”);

Endfunction

Endclass

Class extpacket2 extends parent;

Function display();

$display(“this is sub class2”);

Endfunction end

Module main;

Extpacket1 ec1;

Extpacket2 ec2;

Parent p;

Initial begin

Ec1=new();

Ec2=new();

P=new();

P=ea1;

Q. display();

end

Endmodule

Output:this is parent class

A method with virtual keyword


Class parent;
© Cranes Varsity V1-2020-21 66/ 123
System verilog www.cranesvarsity.com

Virtual Function void display();

$display(“ this is parent class”);

Endfunction

Endclass

Class extpacket1 extends parent;

Funstion display();

$display(“ this is sub class1”);

Endfunction

Endclass

Module main;

Extpacket1 ec1;

Extpacket2 ec2;

Parent p;

Initial begin

Ec1=new();

P=new();

P=ea1;

P.display();

end

Endmodule

Output: this is sub class1

SystemVerilog Randomization and SystemVerilog Constraint


This section provides object-based randomization and constraint programming, explanation on
random variables, randomization methods and constraint blocks.

randomization in SystemVerilog:
 Randomization is the process of making something random;

 SystemVerilog randomization is the process of generating random values to a variable.

 Verilog has a $random method for generating the random integer values.
© Cranes Varsity V1-2020-21 67/ 123
System verilog www.cranesvarsity.com

 This is good for randomizing the variables alone, but it is hard to use in case of class object
randomization.

 for easy randomization of class properties, SystemVerilog provides rand keyword and
randomize() method.

random variables
The class variables which get random values on randomization are called random variables. In
order to make variables as random variables, Class variables need to be declared using the rand
and randc type-modifier keywords.

Following types can be declared as rand and randc,

 singular variables of any integral type


 arrays
 arrays size
 object handle's

rand keyword
Variables declared with the rand keyword are standard random variables. Their values are
uniformly distributed over their range.

Rand bit [3:0] addr;

addr is a 4-bit unsigned integer with a range of 0 to 15. on randomization this variable shall
be assigned any value in the range 0 to 15 with equal probability.

randc keyword
randc is random-cyclic. For the variables declared with the randc keyword, on
randomization variable values don't repeat a random value until every possible value has been
assigned.

Randc bit wr_rd;

In order to randomize the object variables, the user needs to call randomize() method.

example:

Object.randomize();

Random class properties:

Integral class properties can be defined as random using rand or randc.

 Rand =randomization with uniform distribution.

So here is example

© Cranes Varsity V1-2020-21 68/ 123


System verilog www.cranesvarsity.com

Class randclass;

Rand bit [1:0] p1;

Randc bit [1:0] p2;

Endclass

So here rand property output are 00 01 11 00 11 10 11 00 01 11

Here each value has an equal probability

Close repetition is common

randomization example
In the example below,

Two variables addr1 and addr2 of same bit type are declared as rand and randc respectively,
observe the randomized values of addr1 and addr2.

addr1 - takes the random value on every randomization


addr2 - takes the random value on every randomization, but takes random value until every
possible value has been assigned

//class

Class packet;

Rand bit [3:0] a;

Randc bit [3:0] b;

Endclass

Module rand_method;

Initial begin

Packet pkt;

Pkt=new();

Repeat(10) begin

Pkt.randomize();

$display(“a=%d b=%d, pkt.a,pkt.b);

End

© Cranes Varsity V1-2020-21 69/ 123


System verilog www.cranesvarsity.com

End

Endmodule

Output:

A=1 b=4

A= 5 b=6

A=12 b=0

A=2 b=2

A=15 b=12

A=9 b=12

A=0 b=14

A=2 b=8

A=1 b=10

A=2 b=5

SystemVeilog Randomization Methods

SystemVerilog randomization provides a built-in method randomize. The randomize() method


generates random values for all the active random variables of an object, subject to the active
constraints. Variables declared with the rand keyword will get random values on the
object.randomize() method call.The randomize() method returns 1 if the randomization is
successful i.e on randomization it's able to assign random values to all the random variables,
otherwise, it returns 0.
randomize method associated with below callbacks,

 pre_randomize
 post_randomize
pre randomize and post randomize methods

 On calling randomize(), pre_randomize() and post_randomize() functions will get


called before and after the randomize call respectively
 Users can override the pre_randomize() and post_randomize() functions

randomization control from pre_randomize method

© Cranes Varsity V1-2020-21 70/ 123


System verilog www.cranesvarsity.com

In the example below,

Packet has three variables, addr, and wr,rd.

assuming wr_rd = 0 read operation.


wr_rd = 1 write operation.

 In order to perform write operation followed by reading to the same addr,

 randomization of addr is controlled based on the previous randomization value of wr_rd.

 this controlling is done in pre_randomize() function.

//class

Class packet;

Rand bit [3:0] addr;

Randc bit wr;

Bit rd;

//pre randomization function -disabling randomization of addr

// if the previous operation is write;

Function void pre_randomize();

If(wr==1) addr.rand_mode(0);

Else addr.rand_mode(1);

Endfunction

//post randomization function -store the wr value to the rd

// display randomize value of addr and wr.

Function void post_randomize();

Rd=wr;
© Cranes Varsity V1-2020-21 71/ 123
System verilog www.cranesvarsity.com

$display(“post randomization :: addr=%d,wr=%d”,addr,rd);

Endfunction

Endclass

Module rand_method;

Initial begin

Packet pkt;

Pkt=new();

Repeat (4)

Pkt.randomize();

End

Endmodule

Output:

Post randomization:: addr=5 , wr=1

Post randomization:: addr=5 , wr=0

Post randomization:: addr=1 , wr=1

Post randomization:: addr=1 , wr=0

Constrained randomization
Constraint block contains declarative statements which restrict the range of variable or defines
the relation between variables.

 As the name says random variable will get random value on randomization.

 In some situations it is required to control the values getting assigned on randomization,


this can be achieved by writing constraints.

 By writing constraints to a random variable, the user can get specific value on
randomization. constraints to a random variable shall be written in constraint blocks.

Constraint blocks:
 Constraint blocks are class members like tasks, functions, and variables
 Constraint blocks will have a unique name within a class
 Constraint blocks consist of conditions or expressions to limit or control the values for
a random variable
© Cranes Varsity V1-2020-21 72/ 123
System verilog www.cranesvarsity.com

 Constraint blocks are enclosed within curly braces { }


 Constraint blocks can be defined inside the class or outside the class like extern
methods, constraint block defined outside the class is called as extern constraint block
Constraint block syntax

Constarint <constarint_block_name>{<condition/expression>;

<condition/expression>;}

Class randclass ;

Rand bit [1:0] p1;

Randc bit [1:0] p2

Constraint c1 {p1!=2’b00;} constraint p1 to the values 01,10,11

Endclass

randclass myrand=new; ; after the constraint expression not after the constarint
block

Int ok;

Initial begin

Ok=myrand.randomize(); now calling the randomize method by instantiation using


myrand object

…..

end

Constraint block inheritance

Constraint block can be inherited like any other.

Constraint are class member and are inherited just like others members.

class randclass;

Rand bit [1:0] p1;

Constarint not0 {p1!=2’b00;} not0 constriaint is in base class

Endclass

Class rcx1 extends randclass;


© Cranes Varsity V1-2020-21 73/ 123
System verilog www.cranesvarsity.com

Constraint not3 {p1!=2’b11;} rcx1 adds constraint not3 to constraint not0from randclass

Endclass

Class rcx2 extends randclass; //rcx2 my 2nd subclass and redefinig the constraint not0

Constraint not0 {p1!=2’b01;} rcx2 override constraint not0

Endclass

Rcx1 myrand=new;

Initial begin

Ok=myrand.randomize();

…...

Types of constraint:

 inside constarint is particularly used for when u want to build the list of values that property
can be randomized within it.

Example of this constraint is

Class randclass;

Rand bit [3:0] a;

Constraint c1 { a inside {3,8, {12:22}};} //c1 constarint a to the set3,7,11,20

Endclass

Randclass myrand =new;

Int ok;

Initial begin

Ok=myrand.randomize();

…...

end

Now u can also invert the any constraint suppose any list of values cannot be taken inside the
constraint block.

U can take it outside the constarint.

© Cranes Varsity V1-2020-21 74/ 123


System verilog www.cranesvarsity.com

So u have to be very carefull with operator and brackets.

So the example is :

Class not_inside;

Rand bit [3:0] a;

Constarint c2{!(a inside {4,8,[13:24]});} // c2 constarint a to outside the set 4,8,[13:24]

Constraint rand class ;

rand bit [3:0] a;

Constraint c2 {a dist { [0:12]:=2, [13:55]:=1 };}

Endclass

From the above example

 with dist operator, some values can be allocated more often to a random variable. this is
called a weighted distribution.

 dist is an operator, it takes a list of values and weights, separated by := or :/ operator.

 it's possible to control the occurrence or repetition of the same value on randomization.

randomization with dist operator


In the example belowOn randomization, the possibility of 'addr' is getting the value of 10 is
more than 7 and 2. this is because of weight specified to get value 10 is more than the other two
values.

Class packet;

Rand bit [3:0] addr;

Constraint addr_range{addr dist {2:=5, 7:=5, 10:=5};}

Endclass

Module method;

Initial begin

Packet pktl;

Pkt=new()

Repeat(3)

© Cranes Varsity V1-2020-21 75/ 123


System verilog www.cranesvarsity.com

Begin pkt.randomize();

$display(“ addr=%d”,pkt.addr);

End

End

endmodule

Now two ways assign the Weight:

:= - this assign weight to the item or every value in a range.

:/ - this assign weight to the item or to a range as whole divide of the weight among all the
values in a range.

Next constraint is conditional constraint:

This constraint is depending on the value of properties of the class.

There are two ways of defining conditional constraint.

1) Implication, using -> operator

If the expression on the LHS of implication operator (->) is true, then the only constraint on the
RHS will be considered.

In the example below,

If addr_range == small, then addr will get a value less than 8.

i. e implication operator is used to mention condition between the two variables addr_range
and addr.

Class packet;

Rand bit [3:0] addr;

String addr_range;

Constraint adress_range{(addr_range==”small”)->(addr<9);}

Endclass

Module method;

Initial begin

Packet pkt;
© Cranes Varsity V1-2020-21 76/ 123
System verilog www.cranesvarsity.com

Pkt=new();

Pkt.addr_range=”small”;

Repeat(4) begin

Pkt.randomize();

$display(“addr_range=%d addr=%d”,pkt.addr_range,pkt.addr);

End

end

Endmodule

2) Other form is if_else -

 if else block allows conditional executions of constraints.

 If the expression is true, all the constraints in the first constraint/constraint-block must be
satisfied, otherwise all the constraints in the optional else constraint/constraint-block must
be satisfied.

 Example:

Class packet;

Rand bit [3:0] addr;

String addr_range;

Constraint adress_range{ if(addr_range==”small”)

Addr<9

Else

Addr>9;} //Above an example of

implication operator usage is written with if

else condition.

endclass

Module method;

Initial begin

Packet pkt;

© Cranes Varsity V1-2020-21 77/ 123


System verilog www.cranesvarsity.com

Pkt=new();

Pkt.addr_range=”small”;

Repeat(4) begin

Pkt.randomize();

$display(“addr_range=%d addr=%d”,pkt.addr_range,pkt.addr);

End

End

Endmodule

• Constraint Modes

• The constraint_mode() method can be used to disable any particular constraint block.By
default constraint_mode value for all the constraint blocks will be 1.

• constraint_mode() can be used as follow,

• addr_range.constraint_mode(0); //disable addr_range constraint

• packet.addr_range.constraint_mode(0);

• Static Constraints

• A constraint block can be defined as static, by including static keyword in its definition.
static constraint addr_range { addr > 5; }

• Any mode change of static constraint will afect in all the objects of same class type.

class packet;

rand bit [3:0] addr;

static constraint addr_range { addr > 5; }

endclass

module static_constr;

initial begin

packet pkt1;

packet pkt2;

© Cranes Varsity V1-2020-21 78/ 123


System verilog www.cranesvarsity.com

pkt1 = new();

pkt2 = new();

pkt1.randomize();

$display("\taddr = %0d",pkt1.addr);

pkt1.addr_range.constraint_mode(0);

$display("\tAfter disabling constraint");

pkt1.randomize();

$display("\taddr = %0d",pkt1.addr);

pkt2.randomize();

$display("\taddr = %0d",pkt2.addr);

end

endmodule

Inline Constraints in SystemVerilog

• the inline constraint is written using with keyword

• during randomization, constraint solver will consider both inline constraints and
constraints written inside the class

• the inline constraint will not override the constraints written inside the class

• the inline constraint shouldn't conflict with the constraint written inside the class, else it
will lead to randomization failure

• for example, constraint inside the class written as var < 5, and inline constraint written
as var > 5

class packet;

rand bit [3:0] addr;

endclass

module inline_constr;

initial begin

packet pkt;
© Cranes Varsity V1-2020-21 79/ 123
System verilog www.cranesvarsity.com

pkt = new();

repeat(2) begin

pkt.randomize() with { addr == 8;};

$display("\taddr = %0d",pkt.addr);

end

end

endmodule

Conflict with inline constraint

• The addr is the random variable. constraint inside the class written as addr < 5, and
inline constraint written as addr > 5.

• Conclusion: Conflict between the class and inline constraints leads to randomization
failure.

class packet;

rand bit [3:0] addr;

constraint addr_range {addr < 5;};

endclass

module inline_constr;

initial begin

packet pkt;

pkt = new();

repeat(2) begin

pkt.randomize() with { addr > 5;};

$display("\taddr = %0d",pkt.addr);

end

end

endmodule

© Cranes Varsity V1-2020-21 80/ 123


System verilog www.cranesvarsity.com

Class and inline constraints for the same random variable

• The addr is the random variable. constraint inside the class written as addr between 6:12,
and inline constraint is written as addr == 8.

• Conclusion: Constraint solver considers both class and inline constraints.

class packet;

rand bit [3:0] addr;

constraint addr_range {addr inside {[6:12]};};

endclass

module inline_constr;

initial begin

packet pkt;

pkt = new();

repeat(2) begin

pkt.randomize() with { addr == 8;};

$display("\taddr = %0d",pkt.addr);

end

end

endmodule

 Functions in Constraints

• In some cases constraint can't be expressed in a single line, in such cases function call
can be used to constrain a random variable. calling the function inside the constraint is
referred to as function in constraints.

• The function will be written outside the constraint block

• Constraint logic shall be written inside the function as function definition and function
call shall be placed inside the constraint block

• Functions shall be called before constraints are solved, and their return values shall be
treated as state variables.

class packet;

rand bit [3:0] start_addr;


© Cranes Varsity V1-2020-21 81/ 123
System verilog www.cranesvarsity.com

rand bit [3:0] end_addr;

constraint start_addr_c { start_addr == s_addr(end_addr); }

function bit [3:0] s_addr(bit [3:0] e_addr);

if(e_addr < 4)

s_addr = 0;

else

s_addr = e_addr - 4;

endfunction

endclass

module func_constr;

initial begin

packet pkt;

pkt = new();

repeat(3) begin

pkt.randomize();

$display("\tstart_addr = %0d end_addr =",pkt.start_addr,pkt.end_addr);

end

end

endmodule

• Functions in Constraints

• In some cases constraint can't be expressed in a single line, in such cases function call
can be used to constrain a random variable. calling the function inside the constraint is
referred to as function in constraints.

• The function will be written outside the constraint block

• Constraint logic shall be written inside the function as function definition and function
call shall be placed inside the constraint block

• Functions shall be called before constraints are solved, and their return values shall be
treated as state variables.

© Cranes Varsity V1-2020-21 82/ 123


System verilog www.cranesvarsity.com

class packet;

rand bit [3:0] start_addr;

rand bit [3:0] end_addr;

constraint start_addr_c { start_addr == s_addr(end_addr); }

function bit [3:0] s_addr(bit [3:0] e_addr);

if(e_addr < 4)

s_addr = 0;

else

s_addr = e_addr - 4;

endfunction

module func_constr;

initial begin

packet pkt;

pkt = new();

repeat(3) begin

pkt.randomize();

$display("\tstart_addr = %0d end_addr =",pkt.start_addr,pkt.end_addr);

end

end

endmodule

class packet;

rand bit [3:0] start_addr;

rand bit [3:0] end_addr;

constraint start_addr_c { start_addr == s_addr(end_addr); }


© Cranes Varsity V1-2020-21 83/ 123
System verilog www.cranesvarsity.com

function bit [3:0] s_addr(bit [3:0] e_addr);

if(e_addr < 4)

s_addr = 0;

else

s_addr = e_addr - 4;

endfunction

endclass

module func_constr;

initial begin

packet pkt;

pkt = new();

repeat(3) begin

pkt.randomize();

$display("\tstart_addr = %0d end_addr =",pkt.start_addr,pkt.end_addr);

end

end

endmodule

Soft Constraints

• SystemVerilog constraints declared with the keyword soft is called as soft constraints.
any conflict between class constraint and inline constraint leads to a randomization
failure, from this it is clear that it is not possible to override the class constraint by inline
constraint. Some test scenarios demand to override the constraints, this can be done by
writing a soft keyword in class constraint.

A soft constraint is a constraint on a random variable, which allows overriding the constraint

class packet;

rand bit [3:0] addr;

constraint addr_range { addr > 6; }

endclass

© Cranes Varsity V1-2020-21 84/ 123


System verilog www.cranesvarsity.com

module soft_constr;

initial begin

packet pkt;

pkt = new();

repeat(2) begin

pkt.randomize() with { addr < 6;};

$display("\taddr = %0d",pkt.addr);

end

end

endmodule

class packet;

rand bit [3:0] addr;

constraint addr_range { soft addr > 6; }

endclass

module soft_constr;

initial begin

packet pkt;

pkt = new();

repeat(2) begin

pkt.randomize() with { addr < 6;};

$display("\taddr = %0d",pkt.addr);

end

end

endmodule
© Cranes Varsity V1-2020-21 85/ 123
System verilog www.cranesvarsity.com

Bidirectional Constraints

• SystemVerilog constraints are solved bidirectionally, which means constraints on all


random variables will be solved parallel.

• constraint c_name { if(a == 0) b == 1;

• else b == 0; }

class packet;

rand bit [3:0] a;

rand bit [3:0] b;

rand bit [3:0] c;

constraint a_value { a == b + c; }

constraint b_value { b > 6; }

constraint c_value { c < 8; }

endclass

module bidirectional_constr;

initial begin

packet pkt;

pkt = new();

repeat(5) begin

pkt.randomize();

$display("Value of a = %0d \tb = %0d \tc =%0d",pkt.a,pkt.b,pkt.c);

end

end

endmodule

Solve Before Constraints:

 Solve before is the constraint property. solve before is used inside the constraint
block to specify the order of constraint solving. If the variables are dependent,

© Cranes Varsity V1-2020-21 86/ 123


System verilog www.cranesvarsity.com

due to the bidirectional nature of constraints value of one variable will influence
the value of another variable.

 solve before constraints are used to force the constraint solver to choose the
order in which constraints are solved.

 constraint solver will give equal weight-age to all the possible values. i.e On
multiple randomization solver should assign all the possible values

class pakcet;

rand bit a;

rand bit [3:0] b;

constraint a_b { (a == 1) -> b == 0; }

endclass

Possible value of,

a -> 0 and 1; // 2 possible values

b -> 0 to 15; // 16 possible values

• Writing below constraint will direct solver to solve 'a' first, so more frequently a will
take value of 1.

• constraint sab { solve a before b;}

class packet;

rand bit a;

rand bit [3:0] b;

constraint a_b { (a == 1) -> b == 0; }

endclass

module inline_constr;

initial begin

packet pkt;

pkt = new();

repeat(10) begin

pkt.randomize();

© Cranes Varsity V1-2020-21 87/ 123


System verilog www.cranesvarsity.com

$display("\tValue of a = %0d, b = %0d",pkt.a,pkt.b);

end

end

endmodule

• Value of a = 0, b = 6

Value of a = 0, b = 3

Value of a = 1, b = 0

Value of a = 0, b = 15

Value of a = 0, b = 7

Value of a = 0, b = 2

Value of a = 0, b = 15

Value of a = 0, b = 4

Value of a = 0, b = 7

Value of a = 0, b = 11

• this example is without solve before constraint, so we can see the simulation result that
the occurrence of value a == 1 is less.

• this example is to solve before constraint, so we can see the simulation result that the
occurrence of value a == 1 is more than without solve before constraint.

• $urandom( )

$urandom( )

The system function $urandom provides a mechanism for generating pseudorandom


numbers.

The function returns a new 32-bit random number each time it is called. The number shall
be unsigned.

• The seed is an optional argument that determines the sequence of random numbers
generated. The seed can be an integral expression. for a particular seed, the same value
will get generated.

module system_funcations;

bit [31:0] addr1;


© Cranes Varsity V1-2020-21 88/ 123
System verilog www.cranesvarsity.com

bit [31:0] addr2;

bit [64:0] addr3;

bit [31:0] data;

initial begin

addr1 = $urandom();

addr2 = $urandom(89);

addr3 = {$urandom(),$urandom()};

data = $urandom * 6;

© Cranes Varsity V1-2020-21 89/ 123


System verilog www.cranesvarsity.com

Chapter-4
System verilog based Coverage

The main goal of this course is to help you to achieve the objective of the functional coverage
and design.

 Functional covergae -introduction

 Methodology- Fuctional coverage based methodology

 Coverpoint, cover group

 Bins

 Cross

 Transition

 Under system verilog we have not only the assertion based verification,at the same time
we have another sub language, that is cover key word.

 So not only you have verified the properties but also make sure that the property has been
covered so for all low level temporal domain condition u need to use the cover which is
part of the system verilog.

The second part of the coverage is using covergroup and cover point features which is part of
the functional based coverage verification.

Systemverilog Functional Coverage Features

 Coverage of variables and expressions

 Cross coverage

 Automatic and user-defined coverage bins-Values, transitions, or cross products

What does coverage means:

Coverage is used to measure tested and untested portions of the design. Coverage is defined as
the percentage of verification objectives that have been met.

Code Coverage

 Code coverage measures how much of the “design Code” is exercised.


 This includes the execution of design blocks, Number of Lines, Conditions, FSM,
Toggle and Path.
 The simulator tool will automatically extract the code coverage from the design code.
What are its limitations ?

© Cranes Varsity V1-2020-21 90/ 123


System verilog www.cranesvarsity.com

This is only as good as the code written for it. Say you have 10 features mentioned in the design
document, and you have some hoe overlooked /missed or were not aware of the 3 features, You
will write functional coverage code for only 7 of them. If all the 7 have been hit in the tests,
you might come to the conclusion that all the the features are covered. So you need to make
sure that all the the required information from the design specification is included in the
functional coverage block.

Functional Coverage

Functional coverage is a user-defined metric that measures how much of the design
specification has been exercised in verification.

Defining the coverage model

 The coverage model is defined using Covergroup construct.

 The covergroup construct is a user-defined type.

 The type definition is written once, and multiple instances of that type can be created in
different contexts.

 Similar to a class, once defined, a covergroup instance can be created via the new()operator.
A covergroup can be defined in a module, program, interface, or class.

Each covergroup specification can include

 A clocking event that synchronizes the sampling of coverage points


 A set of coverage points
 Cross coverage between coverage points
 Optional formal arguments
 Coverage options
How is functional coverage done in SystemVerilog ?
Example:

Module tb;

Bit[3:0]addr;

Bit [1:0] data;

endmodule

Addr can take 16 values, while data can take 4 values. So , there is some thing to monitor these
two variables in a simulation and report what values of addr and data have been exercised.

The good part is that there are option in simulator to dump out such coverage details into a
single a file so that it can be reviewed after the simulation has finished.

How to write covergroups ?


© Cranes Varsity V1-2020-21 91/ 123
System verilog www.cranesvarsity.com

Class packet;

Rand bit [3:0] addr; // properties

Rand bit [1:0] data; // properties

Function display(); // method

$display(“ addr=%d data=%b”,$time, addr, data);

Endfunction

Covergroup covgrp;

Coverpoint addr {

bins a={0};

Bins b={[1:3]};

Coverpoint data;

Endgroup

Endclass

So from the above code let me clear about coverpoint, bins etc.So coming to the point of
program - program started with class . under class properties and methods are declared.

Then I have written coverage program.

Coverage program stated and ended with covergroup and endgroup.

 A Cover group is defined between key words covergroup & endgroup.


A Covergroup Instance can be created using the new() operator.

 The above example defines a covergroup named "covgrp".

 Variables are mentioned as a coverpoint.

 Coverpoint are put together in a covergroup block.

 Multiple covergroups can be created to sample the same variable with the different set of
bins.

© Cranes Varsity V1-2020-21 92/ 123


System verilog www.cranesvarsity.com

 Bins are said to be hit/covered when the variables recahes the corresponding values. So
that bins b is hit when the addr takes either 1,2,or3 values.

Now let discuss about coverpoint which is written under the covergroup.

COVER POINTS

A covergroup can contain one or more coverage points. A coverage point can be an integral
variable or an integral expression. A coverage point creates a hierarchical scope, and can be
optionally labeled. If the label is specified then it designates the name of the coverage point.

Program main;

Bit [0:2] addr;

Covergroup covgrp;

A:coverpoint addr;

Endgroup

Covgrp covgrp_inst=new():

Initial

Foreach (values[I])

Begin addr=values[I];

Covgrp_inst.sample();

End

Endmodule

In the above example, we are sampleing the cover point "addr". The cover point is named "a" .
In the Coverage report you will see this name. A cover group "covgrp" is defined and its
instance "covgrp_inst" is created. The value of "addr" is sampled when covgrp_inst.sample()
method is called. Total possible values for addr are 0,1,2,3,4,5,6,7. The variable "addr" is
assigned only values 3,5,6. The coverage engine should report that only 3 values are covered
and there are 8 possible values.

How to specify when to sample ?

Coverage should be triggered to sample the coverage values. Sampling can be done using

 Any event expression -edge, variable

 End-point of a sequence

 Event can be omitted


© Cranes Varsity V1-2020-21 93/ 123
System verilog www.cranesvarsity.com

 Calling sample() method.

Covergroup covgrp @(posedge clk);

….…

….…

….…

Endgroup

The above example defines a covergroup named "covgrp". This covergroup will be
automatically sampled each time there is a posedge on "clk" signal.

How to specify when to sample ?

There are two ways to trigger coverge collection in a cover group.

Use sample() method of a particular covergroup to sample coverpoints.

Class coverage ;

Covergroup covgrp;

….

endgroup

Function new();

Covgrp=new; // create an instance of the covgroup

Endfunction

Endclass

Module tb_top();

Coverage cov=new(); //craete an instance of the class

Initial begin

Cov.covgrp.smaple();End

endmodule

© Cranes Varsity V1-2020-21 94/ 123


System verilog www.cranesvarsity.com

Sampling can also be done by calling explicitly calling .sample() method in procedural code.
This is used when coverage sampling is required based on some calculations rather than events.

Coverage Bins:

A covergroup can contain one or more coverage points. A coverage point can be an integral
variable or an integral expression. Each coverage point is associated with “bin”.On each sample
clock simulator will increment the associated bin value.

The bins will automatically be created or can be explicitly defined.

For an “n” bit integral coverpoint variable, a 2^n number of automatic bins will get created.

Lets do an example :

Module cov;

Logic clk;

Logic [3:0] addr;

Logic wr_rd;

Covergroup cg @(posedge clk);

C1:coverpoint addr;

C2:coverpoint ar_rd;

Covergroup:cg

Cg cover_inst=new():

….

Endmodule

“bins” keyword is used to declare the bins automatically to a variable.

Below are the bins, will get created automatically,

for addr: c1.auto[0] c1.auto[1] c1.auto[2] … c1.auto[255]

for wr_rd: c2.auto[0].

Implicit Bins:

While define cover point, if you do not specify any bins, then Implicit bins are created. The
number of bins creating can be controlled by auto_bin_max parameter.
© Cranes Varsity V1-2020-21 95/ 123
System verilog www.cranesvarsity.com

program main;
bit [0:2] y;
bit [0:2] values[$]= '{3,5,6};

covergroup cg;
cover_point_y : coverpoint y
{ option.auto_bin_max = 4 ; }
endgroup

cg cg_inst = new();
initial
foreach(values[i])
begin
y = values[i];
cg_inst.sample();
end

endprogram

In the above example, the auto_bin_max is declared as 4. So, the total possible values are
divided in 4 parts and each part correspoits to one bin.
The total possible values for variable "y" are 8. They are divided in to 4 groups.

Bin[0] for 0 and 1


Bin[1] for 2 and 3
Bin[2] for 4 and 5
Bin[3] for 6 and 7

Varible Y is assigned values 3,5 and 6. Values 3,5 and 6 belongs to bins bin[1],bin[2] and bin[3]
respectively. Bin[0] is not covered.

So lets check the coverage report.:

Coverage report:
--------------------
VARIABLE : cover_point_y
Expected : 4
Covered : 3
Percent: 75.00

Uncovered bins
------------------
auto[0:1]

Covered bins
© Cranes Varsity V1-2020-21 96/ 123
System verilog www.cranesvarsity.com

------------------
auto[2:3]
auto[4:5]
auto[6:7]

Example of enum data type:

For Enum data type, the numbers of bins are equal to the number of elements of enum data
type. The bin identifiers are the enum member name.

typedef enum { A,B,C,D } alpha;


program main;
alpha y;
alpha values[$]= '{A,B,C};

covergroup cg;
cover_point_y : coverpoint y;
endgroup

cg cg_inst = new();
initial
foreach(values[i])
begin
y = values[i];
cg_inst.sample();
end

endprogram

In The above example, the variable "y" is enum data type and it can have 4 enum members
A,B,C and D. Variable Y is assigned only 3 Enum members A,B and C.

Coverage report:
---------------------
VARIABLE : cover_point_y
Expected : 4
Covered : 3
Percent: 75.00

Uncovered bins
--------------------
auto_D

Covered bins
© Cranes Varsity V1-2020-21 97/ 123
System verilog www.cranesvarsity.com

--------------------
auto_C
auto_B
auto_A

Explicit bins:

BINS DECLARATION:

module cov;

Logic [3:0]addr;

Logic ar_rd;

Coverage cg @(posedge clk);

C1: cover point addr{ bins b1:{1,3,4};

Bins b2[3]={11,12};

Bins b3 ={[30:40],[50:60],77};

Bins b4[]={[25:36],[90:96],123};

Bins b5 ={200:$};

Bins b6= default;}

C2: coverpoint wr_rd{bins wrrd};

Endgrp:cg

Cg cover_inst=new();

endmodule

Bins b1= {1,3,4}; // bins b1 incremented for addr 1,3,4;

Bins b2[3]={11:20}; // crerates 3 bins b2[0],b2[1],b2[3]. and 10 possibles values are distributed
as follows (11,12,13),(14,15,16),(17,18,19,20) respectively

Bins b4[]={[25:36],[90:96],123}; // bins b3 incremented for addr =25:36,90:96,123;

Bins b5 ={200:$}; // bins b5 incremented for addr =200 to max value ie255

default bin; // catches the values of the coverage point that do not lie within any of the defined
bins.
Array Of Bins:

© Cranes Varsity V1-2020-21 98/ 123


System verilog www.cranesvarsity.com

To create a separate bin for each value (an array of bins) the square brackets, [], must follow
the bin name.

program main;
bit [0:2] y;
bit [0:2] values[$]= '{3,5,6};

covergroup cg;
cover_point_y : coverpoint y {
bins a[] = {[0:7]};
}

endgroup

cg cg_inst = new();
initial
foreach(values[i])
begin
y = values[i];
cg_inst.sample();
end

endprogram

In the above example, bin a is array of 8 bins and each bin associates to one number between 0
to 7.

Coverage report:
--------------------
VARIABLE : cover_point_y
Expected : 8
Covered : 3
Percent: 37.50

Uncovered bins
-------------------
a_0
a_1
a_2
a_4
a_7
© Cranes Varsity V1-2020-21 99/ 123
System verilog www.cranesvarsity.com

Covered bins
-------------------
a_3
a_5
a_6

To create a fixed number of bins for a set of values, a number can be specified inside the square
brackets.

program main;
bit [0:3] y;
bit [0:2] values[$]= '{3,5,6};
covergroup cg;
cover_point_y : coverpoint y {
bins a[4] = {[0:7]};
}
endgroup
cg cg_inst = new();
initial
foreach(values[i])
begin
y = values[i];
cg_inst.sample();
end
endprogram

In the above example, variable y is 4 bit width vector. Total possible values for this vector are
16.
But in the cover point bins, we have giving the interested range as 0 to 7. So the coverage report
is calculated over the range 0 to 7 only. In this example, we have shown the number bins to be
fixed to size 4.

Coverage report:
--------------------
VARIABLE : cover_point_y
Expected : 4
Covered : 3
Percent: 75.00

Uncovered bins
-------------------
a[0:1]

© Cranes Varsity V1-2020-21 100/ 123


System verilog www.cranesvarsity.com

Covered bins
------------------
a[2:3]
a[4:5]
a[6:7]

bins for transitions


The transition of coverage point can be covered by specifying the sequence,

value1 => value2

It represents transition of coverage point value from value1 to value2.

sequence can be single value or range,

value1 => value2 => value3

range_list_1 => range_list_2

Example of bins transition:

Single value transition is specified as:

value1 => value2

program main;
bit [0:3] y;
bit [0:2] values[$]= '{3,5,6};

covergroup cg;
cover_point_y : coverpoint y {
bins tran_34 = (3=>4);
bins tran_56 = (5=>6);
}

endgroup

cg cg_inst = new();
initial
foreach(values[i])
begin
y = values[i];
© Cranes Varsity V1-2020-21 101/ 123
System verilog www.cranesvarsity.com

cg_inst.sample();
end

endprogram

In the above example, 2 bins are created for covering the transition of point "y" from 3 to 4 and
other for 5 to 6.

The variable y is given the values and only the transition 5 to 6 is occurring.

Coverage report:
--------------------
VARIABLE : cover_point_y
Expected : 2
Covered : 1
Percent: 50.00

Uncovered bins
------------------
tran_34

Covered bins
----------------
tran_56

A set of transitions can be specified as:


range_list1 => range_list2

program main;
bit [0:3] y;
bit [0:2] values[$]= '{3,5,6};

covergroup cg;
cover_point_y : coverpoint y {
bins trans[] = (3,4=>5,6);
}

endgroup

cg cg_inst = new();
initial
foreach(values[i])
begin
© Cranes Varsity V1-2020-21 102/ 123
System verilog www.cranesvarsity.com

y = values[i];
cg_inst.sample();
end

endprogram

In the above example, bin trans creates 4 bin for covering 3=>5,4=>5,3=>6 and 4=>6.

Ignore Bins

A set of values or transitions associated with a coverage-point can be explicitly excluded from
coverage by specifying them as ignore_bins.

program main;
bit [0:2] y;
bit [0:2] values[$]= '{1,6,3,7,3,4,3,5};

covergroup cg;
cover_point_y : coverpoint y {
ignore_bins ig = {1,2,3,4,5};
}

endgroup

cg cg_inst = new();
initial
foreach(values[i])
begin
y = values[i];
cg_inst.sample();
end
endprogram

In the above program, total possible values for y are 0 to 7.

Ignore_bins specified to Ignored values between 1 to 5.

So the Expected values are 0,6 and 7.

Out of these expected values, only 6 and 7 are generated.

Coverage report:
--------------------
VARIABLE : cover_point_y
Expected : 3
© Cranes Varsity V1-2020-21 103/ 123
System verilog www.cranesvarsity.com

Covered : 2
Percent: 66.66

Uncovered bins
------------------
auto[0]

Excluded/Illegal bins
-------------------------
ig
auto[1]
auto[2]
auto[3]
auto[4]
auto[5]

Covered bins
----------------
auto[6]
auto[7]

Illegal Bins

A set of values or transitions associated with a coverage-point can be marked as illegal by


specifying them as illegal_bins. All values or transitions associated with illegal bins are
excluded from coverage. If an illegal value or transition occurs, a runtime error is issued.

program main;
bit [0:2] y;
bit [0:2] values[$]= '{1,6,3,7,3,4,3,5};

covergroup cg;
cover_point_y : coverpoint y {
illegal_bins ib = {7};
}

endgroup

cg cg_inst = new();
initial
foreach(values[i])
begin
y = values[i];
© Cranes Varsity V1-2020-21 104/ 123
System verilog www.cranesvarsity.com

cg_inst.sample();
end

endprogram

Result:
------------
ERROR
Illegal state bin ib of coverpoint cover_point_y in
covergroup cg got hit with value 0x7

Cross Coverage

Cross allows keeping track of information which is received simultaneous on more than one
cover point. Cross coverage is specified using the cross construct.

program main;
bit [0:1] y;
bit [0:1] y_values[$]= '{1,3};

bit [0:1] z;
bit [0:1] z_values[$]= '{1,2};

covergroup cg;
cover_point_y : coverpoint y ;
cover_point_z : coverpoint z ;
cross_yz : cross cover_point_y,cover_point_z ;
endgroup

cg cg_inst = new();
initial
foreach(y_values[i])
begin
y = y_values[i];
z = z_values[i];
cg_inst.sample();
end

endprogram

In the above program, y has can have 4 values 0,1,2 and 3 and similarly z can have 4 values
0,1,2 and 3. The cross product of the y and z will be 16 values
(00),(01),(02),(03),(10),(11)........(y,z)......(3,2)(3,3) .
Only combinations (11) and (32) are generated.
© Cranes Varsity V1-2020-21 105/ 123
System verilog www.cranesvarsity.com

Cross coverage report: cover points are not shown.

Covered bins
-----------------
cover_point_y cover_point_z
auto[3] auto[2]
auto[1] auto[1]

Passing cover group arguments:

Bit [2:0] port_a,port_b;

Covergroup cover port(ref bit[2:0]port,input int mid); // passing cover group arguments

Coverpoint port{

Bins lo={[0:mid-1]};

Bins hi={[mid:$]};

Endgroup

Coverport cpa,cpb;

Initial begin

Cpa=new(port_a,4); // port_a, lo=0:3,hi=4:7

Cpb=new(port_b,4); // port_b, lo=0:3,hi=4:7

End

SYSTEM TASKS

SystemVerilog provides the following system tasks and functions to help manage coverage data
collection.

$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
© Cranes Varsity V1-2020-21 106/ 123
System verilog www.cranesvarsity.com

types.

$get_coverage ( ) :
Returns as a real number in the range 0 to 100 the overall coverage of all coverage group types.
This number is computed as described above.

Summery of functional coverage in sv:

 Create a cover group ehich encapsulates:

 Coverage bins definition:

 State

 Transition

 Cross correlation

 Coverage bins sample timing definition

 Coverage attributes

Functional coverage example:

class coverage;

base_packet pkt;

covergroup cg; //create cover group

option.per_instance=1;

coverpoint pkt.data; // creates coverpoint which includes variable

Bins b1={12,14,15] // craeting bins for particular data variable

};

coverpoint pkt.rst;

//coverpoint pkt.dataframe;

coverpoint pkt.tx_strt;

© Cranes Varsity V1-2020-21 107/ 123


System verilog www.cranesvarsity.com

coverpoint pkt.rx_strt;

coverpoint pkt.dout;

coverpoint pkt.baudclk;

coverpoint pkt.count;

//coverpoint pkt.y;

endgroup

function new();

cg=new(); // craeting instance

endfunction

task cov_run(base_packet pkt);

this.pkt=pkt;

cg.sample(); // sample coverage

endtask

endclass

From the above example - coverage is written within class and endclass

Coverage program is wriiten non emebeddedly.

Then creates the cover group

Under cover group cover points are craeted

Under cover points cover bins are created.

Cross Coverage

• Cross Coverage is specified between the cover points or variables. Cross coverage is
specified using the cross construct.

Cross coverage by cover_point name

bit [3:0] a, b;

covergroup cg @(posedge clk);

c1: coverpoint a;

© Cranes Varsity V1-2020-21 108/ 123


System verilog www.cranesvarsity.com

c2: coverpoint b;

c1Xc2: cross c1,c2;

endgroup : cg

Cross coverage by the variable name

bit [3:0] a, b;

covergroup cov @(posedge clk);

aXb : cross a, b;

endgroup

Cross coverage

class trasaction;

rand bit [3:0] a;

rand bit [2:0]b;

endclass

Transaction tr;

covergroup covport;

a: coverpoint tr.a;

b: coverpoint tr.b;

cross a,b;

endgroup

how many nos of automatic bins created? 128(16*8)

Chapter-5

System verilog based assertion

In this lecture I am going to figure out about


© Cranes Varsity V1-2020-21 109/ 123
System verilog www.cranesvarsity.com

What is assertion?

Why it is used ?

Assertion based verification means how the design will be verified by using assertion and then
we will use typically system verilog language to write assertion code.

Introduction to Assertion:

Assertion is the simply check. In order to check the design we need to have some important
behaviour or specification that design should obey. These are specified requirement.

What is assertion?

 It is an embedded check in the code.This code will be either added in the design file or in
the test bench file or written separately or it could be associated with design file. In general
an assertion is added to vast to specific set of condition.

So we can say

 Assertions are primarily used to validate the behavior of a design.

 An assertion is a check embedded in design or bound to a design unit during the simulation.

 Warnings or errors are generated on the failure of a specific condition or sequence of


events.

 An assertion’s sole purpose is that design things to be implemented and what designer is
implemented. Which means it should ensure the consistency between the designer’s
intention and what is implemented.

It will watch

 If a specific condition occurs

 If a specific sequence occurs.

After assertion it can monitor or reports two kind of behaviour either

 forbidden behaviour or

 expected behaviour.

For the first case when we use for the reporting forbidden behaviour it will flag error for the
specific condition or sequence has violated in simulation.So it is common usage of assertion.

But same set of assertion can also be used to check whether expected behaviour is accurate in
the design or in other words to cover that specific scenario or sequence has occur in the design.

Why we need assertion?

© Cranes Varsity V1-2020-21 110/ 123


System verilog www.cranesvarsity.com

Suppose take example

If (req1 && req2) then

Next_cycle(grnt1 && !grnt2)

So from above example

When req1 and req2 are on then next cycle grant1 will be accepted but grant2 will not be
accepted. So it is not boolean formula, it is a spam over time. Request1 and request2 will on in
one cycle but next cycle grant1 will be on but grant2 will not be on. So for each time spam it is
boolean but overall through time spam it is sequence.

So these specification are captured by assertion. These scenarios are interesting and has to be
verified. When you simulate the test bench then we just put the behaviour into our hand and
check that behaviour are matching or not when design simulates.

Apart from that assertion can also be used for collection of coverage.

Next question is who should write the assertion RTL designer or verification engineer?

Answer is design engineer or verification engineer both are comfortable to write the assertion.

There are two kinds of assertions:

 Immediate Assertions
 Concurrent Assertions

Immediate Assertions:

 Immediate assertions check for a condition at the current simulation time.


 An immediate assertion is the same as an if..else statement with assertion control.
Immediate assertions have to be placed in a procedural block definition.

Syntax:

LABEL: assert(expression) action_block;

 The optional statement label (identifier and colon) creates a named block around the
assertion statement
 The action block is executed immediately after the evaluation of the assert expression
 The action_block specifies what actions are taken upon success or failure of the
assertion
Now let me explain about action block
action_block;

Pass_statement; else fail_statement;

 The pass statement is executed if the expression evaluates to true


© Cranes Varsity V1-2020-21 111/ 123
System verilog www.cranesvarsity.com

 The statement associated with else is called a fail statement and is executed if the
expression evaluates to false

 Both pass and fail statements are optional

 Since the assertion is a statement that something must be true, the failure of an assertion
shall have a severity associated with it.

 Other severity levels can be specified by including one of the following severity system
tasks in the fail statement:

 $fatal is a run-time fatal.


 $error is a run-time error.
 $warning is a run-time warning, which can be suppressed in a tool-specific
manner.
 $info indicates that the assertion failure carries no specific severity.

 If an assertion fails and no else clause is specified, the tool shall, by default call $error.
Let me take one simple one example of immediate assertion:

Always @(posedge clk)assert (a && b);

assert(a&&b)

Module assertion_ex;
Bit clk,a,b;
Always #5 clk=~clk;
Initial begin
a=1;
b=1;
#15 b=0;
© Cranes Varsity V1-2020-21 112/ 123
System verilog www.cranesvarsity.com

b=1;
a=0;
#20 a=1;

#10;
$finish;
End

always@(posedge clk) assert(a&&b) ;


Endmodule

So from the above example and after simulation we can observe that green line is indicating
pass and and red line is indicating no passing any data.

Concurrent assertion:

Definition of concurrent assertion:Concurrent assertion describes behaviour that spans


over simulation time and are evaluated only at the occurence of a clock.
 The concurrent assertion is evaluated only at the occurrence of a clock tick
 The test expression is evaluated at clock edges based on the sampled values of the
variables involved
 It can be placed in a procedural block, a module, an interface or a program definition
C_assert :assert property (@(Posedge clk) not (a&&b))
The Keyword differentiates the immediate assertion from the concurrent assertion is "property."

Below is one example :


Module tb;
Bit a,b;
Bit clk;
Always #10 clk=~clk;
Initial begin
For (int I=0; I<10; I++) begin
@(posedge clk)
a<=$random;
B<=$random;
$display(“a=%b b=%b”,a,b);
End
#10 $finish;
Assert property (@(posedge clk)a &b);
Endmodule

Now Let me discuss about few definition such as sequence,property,and assert.


© Cranes Varsity V1-2020-21 113/ 123
System verilog www.cranesvarsity.com

Sequence

Boolean expression events that evaluate over a period of time involving single/multiple clock
cycles. SVA provides a keyword to represent these events called "sequence."
Syntax:
Sequence name_of _sequence;
…..
Endsequence

Property

A number of sequences can be combined logically or sequentially to create more complex


sequences. SVA provides a keyword to represent these complex sequential behaviors called
"property".
Syntax
Property name_of_property;
Test expression or complex sequence expression;
Endproperty

Assert
The property is the one that is verified during a simulation. It has to be asserted to take effect
during a simulation. SVA provides a keyword called "assert" to check the property.
Syntax
Assertion_name:assert_property(property_name);

SVA Sequence

Boolean expression events that evaluate over a period of time involving single/multiple clock
cycles. SVA provides a keyword to represent these events called "sequence".

SVA Sequence example

Sequence seq_1;
@(posedge clk) a==1;
Endsequence

In the above example the sequence seq_1 checks that the signal "a" is high on every positive
edge of the clock. If the signal "a" is not high on any positive clock edge, the assertion will fail.

A sequence with a logical relationship

Sequence seq_1;
@(posedge clk) a||b;
Endsequence
© Cranes Varsity V1-2020-21 114/ 123
System verilog www.cranesvarsity.com

From above example sequence, seq_1 checks that on every positive edge of the clock, either
signal "a" or signal "b" is high. If both the signals are low, the assertion will fail.
Sequence Expressions

By defining arguments in a sequence definition, the same sequence can be re-used for similar
behavior.

For example, we can define a sequence as below.


Sequence seq_lib(a,b)
a||b;
Endsequence

The sequence can be written as


Sequence s_lib_inst
Seq_lib(req1,req2);
Endsequence

Sequences with timing relationship

In SVA, clock cycle delays are represented by a "##" sign. For example, ##2 means 2 clock
cycles.

Sequence seq_1;
a ##2b;
Endsequence
Property p;
@(posedge clk)seq
Endproperty
A_1:assert property (p);

Forbidding a property

 A separate property definition is not needed to assert a sequence. the expression to be


checked can be called from the assert statement directly as shown below.
 In all the examples shown so far, the property is checking for a true condition. we expect
the property to be false always. If the property is true, the assertion fails.
Sequence seq;
A ##2 b;
Endsequence
A_2:assert property(@(posedge clk)seq);

Calling a property with a clock definition from within the assert statement is not allowed.
A_3:assert property(@(posedge clk)p);
The above example is not allowed.
© Cranes Varsity V1-2020-21 115/ 123
System verilog www.cranesvarsity.com

Sequence seq;
@(posedge clk) a##2 b;
Endsequence

Property p;
Not seq;
Endproperty
A_1:assert property(p);

From the above example I can conclude that sequence checks that if signal "a" is high on a
given positive edge of the clock, then after 2 clock cycles, signal "b" shall not be high. The
keyword "not" is used to specify that the property should never be true.

Implication Operator

Sequence seq;
@(posedge clk) a##2 b;
Endsequence
If we want the sequence to be checked only after “a” is high, this can be achieved by using
the implication operator.

The implication is equivalent to an if-then structure. The left-hand side of the implication
is called the "antecedent" and the right-hand side is called the "consequent." The antecedent is
the gating condition. If the antecedent succeeds, then the consequent is evaluated.

The implication construct can be used only with property definitions. It cannot be used in
sequences.

There are 2 types of implication:

OVERLAPPED IMPLICATION

 Non-overlapped implication

© Cranes Varsity V1-2020-21 116/ 123


System verilog www.cranesvarsity.com

Overlapped implication

|->.

Property p;

@(posedge clk) a|->##b;

Endproperty

A:assert property(p);

Non-overlapped implication

The non-overlapped implication is denoted by the symbol |=>.

If there is a match on the antecedent, then the consequent expression is evaluated in the next
clock cycle.

Below property checks that, if signal "a" is high on a given positive clock edge, then signal "b"
should be high on the next clock edge.

Property p;

@(posedge clk) a|=>##b;

Endproperty

A:assert property(p);

Timing windows in SVA Checkers

Property p;

@(posedge clk) a|-> ##[1:4]b;

Endproperty

A:assert property(p);

Overlapping timing window

Below property checks that, if signal "a" is high on a given positive clock edge, then signal "b"
should be high in the same clock cycle or within 4 clock cycles.

Property p;

@(posedge clk) a|-> ##[0:4]b;

© Cranes Varsity V1-2020-21 117/ 123


System verilog www.cranesvarsity.com

Endproperty

a:assert property(p);

Indefinite timing window

Property p;

@(posedge clk) a|-> ##[1:$]b;

Endproperty

a:assert property(p);

From above example i can say that sequence checks for the signal "a" being high on a given
positive edge of the clock. If the signal "a" is not high, then the sequence fails. If signal "a" is
high on any given positive edge of the clock, the signal "b" should be high 2 clock cycles after
that. If signal "b" is not asserted after 2 clock cycles, the assertion fails.

SystemVerilog Repetition operators

Repetition Operators

Propertyp;
@(posedge clk) a|-> ##1 b ##1b;
Endproperty
a:assert property(p);
The above property checks that, if the signal “a” is high on given posedge of the clock, the
signal “b” should be high for 3 consecutive clock cycles.
The Consecutive repetition operator is used to specify that a signal or a sequence will match
continuously for the number of clocks specified.

Syntax

Signal [*n] or sequence[*n]

N is the number of repetition.

with repetition operator above sequence can be re-written as,

Propertyp;
@(posedge clk) a|-> ##1 b[*2];

Endproperty
© Cranes Varsity V1-2020-21 118/ 123
System verilog www.cranesvarsity.com

a:assert property(p);
SVA Methods
$rose

$rose(boolean expression or signal name)

returns true if the least significant bit of the expression changed to 1. Otherwise, it returns false.

Sequence seq_rose;

@(posedge clk) $rose(a);

Endsequence

Sequence seq_rose checks that the signal "a" transitions to a value of 1 on every positive edge
of the clock. If the transition does not occur, the assertion will fail.

$fell

$fell(boolean expression or signal name)

returns true if the least significant bit of the expression changed to 0. Otherwise, it returns false.

Sequence seq_rose;

@(posedge clk) $fell(a);

Endsequence

Sequence seq_fell checks that the signal "a" transitions to a value of 0 on every positive edge
of the clock. If the transition does not occur, the assertion will fail.

$stable

$fell(boolean expression or signal name)

returns true if the least significant bit of the expression changed to 0. Otherwise, it returns false.

Sequence seq_rose;

@(posedge clk) $stablel(a);

Endsequence

Sequence seq_stable checks that the signal "a" is stable on every positive edge of the clock. If
there is any transition occurs, the assertion will fail.

$past

$past(boolean expression or signal name)

© Cranes Varsity V1-2020-21 119/ 123


System verilog www.cranesvarsity.com

provides the value of the signal from the previous clock cycle.

Below Property checks that, in the given positive clock edge, if the “b” is high, then 2 cycles
before that, a was high.

Property p;

@(posedge clk) b|->($past(a,2)==1);

Endproperty

A:assert property(p);

Below is a one simple example: using SVA method

module tb;

bit a;

bit clk;

int i;

sequence s_a;

@(posedge clk) $fell(a);

endsequence

assert property(s_a);

always #10 clk=~clk;

initial begin

for(i=0;i<10;i++)

a=$random;

@(posedge clk);

$display("a=%d",$time,a);

end

// $finish;

Endmodule

The above example will be executing

© Cranes Varsity V1-2020-21 120/ 123


System verilog www.cranesvarsity.com

Built-in system functions

 $onehot(expression)
o checks that only one bit of the expression can be high on any given clock edge.
 $onehot0(expression)
o checks only one bit of the expression can be high or none of the bits can be high
on any given clock edge.
 $isunknown(expression)
o checks if any bit of the expression is X or Z.
 $countones(expression)
o counts the number of bits that are high in a vector.

A_1:assert property(@(posedge clk) $onehot(state));

A_2:assert property(@(posedge clk) $onehot0(state));

A_3:assert property(@(posedge clk) $isunknown(bus));

Assert statement a_1 checks that the bit vector "state" is one-hot.
Assert statement a_2 checks that the bit vector "state" is zero one-hot.
Assert statement a_3 checks if any bit of the vector "bus" is X or Z.
Assert statement a_4 checks that the number of ones in the vector "bus" is greater than one.

disable iff and ended construct

disable iff

In certain design conditions, we don't want to proceed with the check if some condition is true.
this can be achieved by using disable iff.

Properety p;

@(posedge clk)

Disable iff(rest)a|->##1 b[->3] ##1 c;

endproperty

a:assert property(p);

From the above example we can conclude that property checks that, if the signal “a” is high on
given posedge of the clock, the signal “b” should be high for 3 clock cycles followed by “c”
should be high after ”b” is high for the third time. During this entire sequence, if reset is detected
high at any point, the checker will stop.

Using operator: some example

module tb1;
© Cranes Varsity V1-2020-21 121/ 123
System verilog www.cranesvarsity.com

bit a,b;

bit clk;

sequence s_a;

@(posedge clk) a## 2 b;

endsequence

assert property(s_a);

// $display("assertion pass!",$time);

always #10 clk=~clk;

initial begin

for (int i=0; i<10; i++) begin

@(posedge clk);

a<=$random;

b<=$random;

// $finish;

$display("a=%d b=%d", $time ,a,b);

end

end

endmodule

© Cranes Varsity V1-2020-21 122/ 123


System verilog www.cranesvarsity.com

© Cranes Varsity V1-2020-21 123/ 123

You might also like