[go: up one dir, main page]

0% found this document useful (0 votes)
0 views49 pages

system verilog pdf

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 49

SYSTEM VERILOG

1. What is System Verilog?


A:- System Verilog is an extension of Verilog with many features that allow
engineers to verify the design using complex testbench structures and random
stimuli in stimulation.

2. What is verification?
A:- In the front-end design process of VLSI (Very Large Scale Integration),
verification refers to the important step of ensuring the correctness and
functionality of the design before moving forward to the physical implementation
stages. The front-end design encompasses the stages of architecture design, logic
design, and functional verification before the design is translated into a physical
layout (the back-end design).
SV Verification architecture:-
Top
Tests

ENV Generator

Reference model t Scoreboard

Write Write Read Read


driver monitor monitor Driver

Write interface Read interface

DUV
Verifications are two types Functional verification and STA(static timing
analysis).
Functional verification: - This stage focuses on ensuring that the design
performs its intended functions correctly. It involves creating test cases that cover
all aspects of the design's functionality and simulating the design to check its
behaviour under various scenarios.
Formal verification: Formal verification is the process of mathematically
checking that the behaviour of a system, described using a formal model, satisfies
a given property, also described using a formal model.

3. What are the System Verilog features?


A:- Assertions and Functional Coverage: System Verilog includes built-in
constructs for writing assertions and functional coverage, enabling designers to
define and verify the desired behaviour of their designs more easily.

4. Different datatypes in the system Verilog?


A:- 4-state(0,1,x,z) and 2-state(0,1) data types
4-state:- reg, logic, integer, wire.
2-state:- bit, byte, shortint, int, longint.

5. What is a logic datatype?


A: -Logic is a 4-state data type that supports input and output ports. It can’t
support an inout port. It's working similarly to the reg data type.
Logic ‘0’
Logic ‘1’
Logic ‘x’ - x is unknown
Logic ‘z’ - z is high impedance
Ex :-
Module ex (logic a, b, c);
initial begin
a=10;
b=20;
c=a+b;
$display(c);
end
endmodule

6. What is a struct datatype?


A:- Struct is defined using the Struct keyword, followed by variables of multiple
data types enclosed in curly braces.

Syntax:- typedef struct packed {


type_1 var_1;
type_2 var_2;
type_3 var_3;
} struct_name;
Ex:- module ex;
Struct {int a; int b; int c;}op;
initial begin
op.a=10;
op.b=20;
op.c=op.a+op.b;
$display(op.c);
end
endmodule

7. What are an enum and a typedef datatype?


A:- Enum(Enumeration):-‘enum’ in System Verilog provides a way to define a
set of named constants, enhancing code readability and maintainability.
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.
Syntax:- enum { red, green, blue, yellow, white, black } Colors;
enum { red=1, green=2, blue=3, yellow=4, white=5, black=6 } Colors;

typedef:-Allows users to define new types built up from the predefined types or
other user-defined types in Verilog and SystemVerilog.
syntax:-typedef data_type type_name [range];
ex:- module ex;
typedef enum {g, be}op;
op a,a1;
initial begin
a = g;
a1=b;
if(a == g)
$display("a is g packet");
else
$display("a is b packet");
if(a1 == g)
$display("a1 is g packet");
else
$display("a1 is b packet");
end
endmodule
output:-
a is g packet
a1 is b packet
8. What is an array?
A:- An array is a group of variables having the same data type. It can be accessed
using an index value. An index is a memory address, and the array value is stored
at that address.

9. What is a packed and unpacked array?


A:- Packed array: The packed array is used to refer to the dimensions declared
before the data identifier name.
Syntax:-data_type [range]var_name;
• bit [2:0][2:0][2:0]block;//packed array of bit type

Unpacked array :- The term unpacked array is used to refer to the dimensions
declared after the data identifier name types bit temp_var [7:0]; // unpacked array
of real types.
Syntax:-data type [range] var_name;
• bit [2:0][3:0]array[2:0];
10. Difference between packed and unpaced array?
A:-
Packed array Unpacked array
1.Packed refers to data storage where 1. Unpacked refers to data storage
multiple bits of data are stored in where each element of the data
contiguous memory locations. This is structure is stored independently. This
typically used for arrays of bits (logic is typically used for larger data types
or bit data types) or arrays of smaller or when elements need to have
bit-width data types. different memory addresses.

2.Elements can be stored as continues. 2. Elements can store random.

3.bit[2:0][3:0]array; 3.bit [2:0][3:0]array[3:0];

4.Synthesizable 4.Not-synthesizable

11.What is a Dynamic array?


A:- A dynamic array is one dimension of an unpacked array whose size can be
set or changed at run-time.
Syntax:- data type var_name [];
• bit arr[];
Methods:-
new[ ] –> allocates the storage.
Ex:-bit ar [];//Allocates the storage.

Size[ ] –> returns the current size of a dynamic array.


Ex:-bit ar[];
Initial begin
ar=new[10];//Here declare size of an array.
end
delete( ) –> empties the array, resulting in a zero-sized array.
Ex:-bit array_name[];
Initial begin
Array_name=new[10];
array_name.delete() ;//Here, delete the array by using the delete method.
end

12. Difference between new() and new[]?


A:- They both allocate memory and initialize values.
new()--> Can take arguments for setting object values.
-->You can define your own new function so that you can set the values
as you prefer.
-->The big difference is that the new() function is called to construct a
single object
new[]--> Only takes a single value for the array size
--> Used to set the size of dynamic arrays.

13. What is a queue array?


A:- 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.
Syntax:-data type var_name[$];
• bit arr[$];
Queue array is two types
• Bounded array
Ex:bit ar[$:0];
• Unbounded array
Ex:-bit ar [$];
Methods:-
=>size( ) :- Returns the number of items in the queue.
=>delete( ):- Deletes the item at the specified index position.
=>insert( ) :- Inserts the given item at the specified index position.
=>pop_back ( ) :- Removes and returns the end element of the queue.
=>pop_fron t( ) :- Removes and returns the first element of the queue.
=>push_front( ) :- Inserts the given element at the front of the queue.
=>push_back( ) :- Inserts the given element at the end of the queue.
Ex:-
Module queue_r;
bit [3:0] ar[$];
string ar1[$];
int k;
initial begin
ar={0,1,2,3,4,5};
ar1={“a”, “b”, “c”, “d”, “e”};
$display(ar.size());// 6
ar.delete(5);//detete the ar of array index 5 element .//01234
ar1.insert(0, “chinni”);//inserting string in the 0th index.
$display(ar1);//chinni a b c d e
ar.push_front(6);
$display(ar.size());//7
ar.push_back(7);
$display(ar.size());//8
k = ar.pop_front();
$display(k);//6
k= ar.pop_back();
$display(k);//7
end
endmodule

14. What is an associative array?


A:- Associative arrays are a special type of dynamic array in which the memory
is not allocated immediately when the array is declared. Instead, the memory is
allocated as and when data is stored in the array. As the memory is not allocated
immediately thus the allocated memory is not continuous in nature, which makes
it slower than dynamic arrays.
Syntax:- data type var_name [index data type];
• int arr[int];
Associative array functions or methods:-
Function Description
function int num (); Returns the number of entries in the
associative array
function int size (); Also returns the number of entries, if
empty 0 is returned
function void delete ( [input index] ); Index when specified deletes the entry
at that index, else the whole array is
deleted
function int exists (input index); Checks whether an element exists at
specified index; returns 1 if it does,
else 0
function int first (ref index); Assigns to the given index variable the
value of the first index; returns 0 for
empty array
function int last (ref index); Assigns to given index variable the
value of the last index; returns 0 for
empty array
function int next (ref index); Finds the smallest index whose value
is greater than the given index
function int prev (ref index); Finds the largest index whose value is
smaller than the given index

15. What is Type conversion?


A:- It will convert one data type into another data type.
There are two types
=>Static casting
• System Verilog static casting does not apply to OOP.
• Static casting converts one data type to another compatible data type (for
example string to int).
• As the name says ‘Static’, the conversion data type is fixed.
• Static casting will be checked during compilation, so there won’t be run-
time checking and error reporting.
• Casting applies to value, variable, or expression.
• A data type can be changed by using a cast ( ‘ ) operation.
• The vale/variable/expression to be cast must be enclosed in parentheses or
within concatenation or replication braces.
Ex:-module test;
int a;
real b;
initial begin
a=int’(20.0);
b=real’(10);
$display(“real value %f”,b);
$display(“int value %d”,a);
end
endmodule

o/p:- real value 10.0


int value 20
=>Dynamic casting
• Dynamic casting is used to, safely cast a super-class pointer (reference)
into a subclass pointer (reference) in a class hierarchy.
• Dynamic casting will be checked during run time, an attempt to cast an
object to an incompatible object will result in a run-time error.
• Dynamic casting is done using the $cast(destination, source) method.
• With $cast compatibility of the assignment will not be checked during
compile time, it will be checked during run-time.
• It is always legal to assign a child class variable to a variable of a class
higher in the inheritance tree (parent class).
parent_class = child_class;
Ex:- class base;
bit [31:0] addr;
function display();
$display ("Addr = %0d",addr);
endfunction
endclass
class sub extends base;
bit [31:0] data;
function display();
super.display();
$display ("Data = %0d",data);
endfunction
endclass

module inheritence;
initial begin
base p;
sub c=new();
sub c1;
c.addr = 10;
c.data = 20;
p = c; //p is pointing to child class handle c.
$cast (c1, p); //with the use of $cast, type check will occur during
runtime
c1. display ();
end
endmodule
o/p:- Addr = 10
Data = 20

16. what is a system verilog String?


A:- The string data type is an ordered collection of characters. The length of a
string variable is the number of characters in the collection which can have
dynamic length and vary during a simulation.
Syntax:- data_type var_name= “initial value”;
• String var= “chinni”;
Ex:- module str;
string var= “VLSI”;
initial begin
$display (“DV %s”, var);
end
endmodule
o/p:-DV VLSI

String operations:
Operator Description
Equality (Str1 == Str2) Returns 1 if the two strings are equal
and 0 if they are not.
Inequality (Str1 != Str2) Returns 1 if the two strings are not
equal and 0 if they are.
Comparison (Str1 < Str2 Returns 1 if the corresponding
Str1 <= Str2 condition is true and 0 if false
Str1 > Str2
Str1 >= Str2)
Concatenation ({Str1, Str2, ..., All strings will be concatenated into
StrN}) one resultant string.
Replication ({multiplier{Str}}) Replicates the string N number of
times, where N is specified by the
multiplier.
Indexing (Str[index]) Returns a byte, the ASCII code at the
given index. If given index is out of
range, it returns 0.
Methods (Str.method([args])) The dot(.) operator is used to call
string functions.

17. What is a system Verilog package?


A:- Packages provide a mechanism for storing and sharing data, methods,
properties, and parameters that can be reused in multiple other modules,
interfaces, or programs.
-> Package is used defined datatype.
->Good for reusable environments.
->Test cases import the package.

18. Difference between Function and Task?

Function Task
1. A function enables another function 1. A task can enable other tasks and
but not another task. functions.

2. Function always executes zero 2. Task may execute non_zero


simulation time. simulation time.

3. Function must not contain any delay, 3. Tasks may contain delay, event, or
event, or timing control statements. timing control statements.

4. Functions must have at least one 4. Tasks may have zero or more
input argument. They can have more arguments of type input, output, or
than one input. inout.

5. Function always return a single 5. Tasks do not return with a value,


value. They cannot have output or but can pass multiple values through
inout arguments. output and inout arguments.
19. Difference between VHDL and Verilog?
VHDL Verilog
1. Compilation should not be an issue. 1. We should take care of the
compilation order.

2. User-defined data types are allowed. 2. User-defined data types are not
allowed.

3. VHDL may be preferred because it 3. Verilog may be preferred because of


allows a multitude of languages or its simplicity.
user-defined data types.

4. VHDL is “harder” to learn ADA-like. 4. Verilog is “easier” to learn C_like.

5. Procedures functions may be placed 5.No concept of “Package”.


in the package.

6. The library is present. 6. The library is absent.

7. It manages the large design. 7. It doesn’t manage the large design,


because no concept of a package.

8. Unary reduction operator not present. 8. Unary reduction operator present. a


a mod operator is present. mod operator is not present.

9. VHDL allows concurrent procedure 9. Verilog does not allow concurrent


calls. task cells.

10. Generate statements that replicate 10. Generate statements are not present
the number of instances. in Verilog.

11. Strong datatype. 11. Weak datatype.

12. Supports multi-dimensional array. 12. It does not support multi-


dimensional arrays.

20. What is a Task in System Verilog?


A:- A Task can contain a declaration of parameters, input arguments, output
arguments, in-out arguments, registers, events, and zero or more behavioral
statements.
SystemVerilog task can be,
• Static
->Static tasks share the same storage space for all task calls

Ex:-

• Automatic
->Automatic tasks allocate unique, stacked storage for each task call.
SystemVerilog allows,
• to declare an automatic variable in a static task
• to declare a static variable in an automatic task
• more capabilities for declaring task ports
• multiple statements within task without requiring a begin…end or
fork…join block
• returning from the task before reaching the end of the task
• passing values by reference, value, names, and position
• default argument values
• the default direction of argument is input if no direction has been
specified
• default arguments type is logic if no type has been specified
ex:- module sv_task;
int x;
task sum;// task arguments in declarations and mentioning directions
input int a,b;
output int c;
c = a+b;
endtask
/*task sum(input int a, b, output int c);// task arguments in parentheses
c = a+b;
endtask*/
initial begin
sum(10,5,x);
$display("\tValue of x = %0d",x);
end
endmodule
o/p:- Value of x = 15

21. What is the Function of system Verilog?


A:- The primary purpose of a function is to return a value that can be used in an
expression and cannot consume simulation time. A function cannot have time-
controlled statements like @, #, fork-join, or wait. A function cannot start a task
since tasks are allowed to consume simulation time.
Ex:- module function;
int x;
function int sum(input int a,b);
sum = a+b;
endfunction
initial begin
x=sum(10,5);
$display("\tValue of x = %0d",x);
end
endmodule
o/p:-Value of x=15
22. What is an interface?
A:- The interface is a static component. It can avoid mismatching port
connections.
Syntax: - interface interface_name;
// Declare signals and variables
// Declare modports (optional)
// Declare methods (optional)
endinterface

23. What is a mod port?


A:- The modport gives directional information. The modport selected the required
ports, and it will provide direct information.
Syntax:- interface InterfaceName;
// Declare signals and variables modport
modport_name ( // Specify port directions for signals and variables);
// Declare methods (optional)
Endinterface

24. What is a clocking block?


A:- A clocking block specifies timing and synchronization for a group of signals.
The clocking block specifies,
• The clock event that provides a synchronization reference for DUT and
testbench
• The set of signals that will be sampled and driven by the testbench
• The timing, relative to the clock event, that the testbench uses to drive and
sample those signals
A clocking block can be declared in an interface, module, or program block.
Signals sampled and driven by the clocking block, from_DUT and to_DUT are
the clocking signals.
Clocking block declaration:-
clocking cb @(posedge clk);
default input #1 output #2;
input from_Dut;
output to_Dut;
endclocking

25. What is the System Verilog event scheduler?


A:- System Verilog is a parallel programming language, and the System Verilog
Event Scheduler plays a important role in it. The execution of certain language
constructs is defined by the parallel execution of blocks or processes.
Event for sequential circuit:-
posedge clock: This event occurs on the rising edge of the clock signal (clk). It's
commonly used to trigger state updates or operations that need to occur
synchronously with the clock.

clk Always @(posedge clk) begin


//Sequential logic
end

Event for combinational circuit:-


Input Signal Change: An event occurs whenever there is a change in the value
of one or more input signals to the combinational circuit. This change
immediately propagates through the logic gates of the circuit to compute the
new output.
Always @(input) begin
clk //comb logic
end

Preponed Region: Preponed region is for the verification environment. The


assertion signals and the clocking block inputs with #1step delay are sampled in
this region. Sampling in the Preponed region is equivalent to sampling in the
previously postponed region.
Active Region: The Active region holds the current active region set events being
evaluated and can be processed in any order. The events are,
• All the blocking assignments in the module block.
• Evaluate the Right-Hand-Side (RHS) of all nonblocking assignments in the
module block and schedule updates into the NBA region.
• All module continuous assignments in the module block.
• Evaluate inputs and update outputs of Verilog primitives.
• Execute the $display and $finish commands.
Inactive Region: This region is where #0 blocking assignments in the module
block are scheduled. It is not recommended to make #0 assignments in RTL.
NBA Region: In this region, the Left- Hand-side variables of non-blocking
assignment statements in the module block get updated.
Observed Region: The concurrent assertions are evaluated in this region. Also,
clocking block inputs with explicit #0 step delay are sampled in the Observed
region.
Reactive Region: The following events take place in this region,
• Action blocks of the concurrent assertions.
• Blocking assignments in the program block.
• Evaluate the Right-Hand-Side (RHS) of all program nonblocking
assignments in the program block and schedule updates into the Re-NBA
region.
• All continuous assignments in the program block.
• Execute the $exit and implicit $exit commands.
Re-Inactive Region: #0 delays in the program block are executed in this region.
Re-NBA Region: In this region, the Left- Hand-side variables of non-blocking
assignment statements in the program block get updated. Also, clocking block
outputs with explicit #0 skew shall be driven at the same time as their specified
clocking event, in the Re-NBA region.
Postponed Region: $monitor and $strobe are scheduled in the Postponed region.

26. Why are we using the clocking block in System Verilog?


A:- A clocking block is a set of signals synchronised on a particular clock. It
basically separates the time related details from the structural, functional and
procedural elements of a testbench. It helps the designer develop testbenches in
terms of transactions and cycles.

27. What is input and output skew?


A:-Skew:- Clocking skew specifies the moment (w.r.t clock edge) at which
input and output clocking signals are to be sampled or driven respectively. A
skew must be a constant expression and can be specified as a parameter.
Input skew:- Input skew refers to the timing difference between the arrival
times of signals at different inputs of a component or module. This difference
can affect the correct operation of synchronous circuits, especially those driven
by a common clock. Input skew is typically specified in terms of a maximum
allowed difference in arrival times between different inputs.
Output skew:- Output skew refers to the timing difference between the departure
times of related output signals. This difference can affect the synchronization and
reliability of signals driven by the same source, such as a clocked register or a
bus interface.

28. Difference between input and output skew?


Feature Input skew Output skew
Definition Timing difference between Timing difference between
arrival times of related departure times of related
input signals. output signals.

Measurement Typically measured in Typically measured in terms of


terms of maximum maximum allowable time
allowable time difference. difference.

Control Managed using input delay Managed using output delay


statements (‘input delay’). statements (‘output delay’).

Ensure synchronous Ensure synchronous and


Purpose operation of inputs relative properly timed outputs relative
to a clock edge. to a clock edge.

Application Critical for setup and hold Critical for ensuring proper
time requirements in synchronization and timing
synchronous circuits. closure in designs.

Implementation Specified in RTL coding Specified in RTL coding and


for simulation and through constraints in
verification. synthesis tools.
Verification Validated using timing Validated using timing checks
checks (setup, hold checks) (setup, hold checks) in
in simulations. simulations.

29. What is OOPS in SV?


A: OOPS stands for Object-Oriented Programming System. SystemVerilog is an
extension of Verilog, a hardware description language used for designing and
verifying digital circuits. SystemVerilog introduces object-oriented programming
(OOP) concepts to enhance the capabilities of traditional Verilog for design and
verification.

30. What is class?


A: Class is collection of objects. Classes define the properties and methods.
Ex: Properties: Variables
Methods: Function and Task

31. What is an object?


A: - Objects are instances of classes.

32. What is deep copy?


A: - Deep copy copies both properties and object.
Syntax: h2=h1.copy;
Ex: module test;
class sub;
int a;
function sub copy ()
copy=new (); //object creation
copy. a=this. a; //this keyword is referred to global properties
endfunction
endclass
class base;
int b;
sub h=new (); //h is the handle of sub class type
function base copy ();
copy=new ();
copy. b=this. b;
copy.h= this.h. copy;
endfunction
endclass
base h1, h2; //h1, h2 is the handle of base class type
initial h1

begin
h1=new (); h
a=20
h1. b=10;
b=10
h1.h. a=20;
h2=h1.copy() ;//deep copy
h2.h. a=30;
end
endmodule h2

a=30
h
b=10

33. What is shallow copy?


A: Shallow copy is only base-class properties only copy and sub class objects
Pointing to the base class properties.
Syntax: h2=new h1;
Ex: class sub;
int a
endclass
class base;
int b;
sub h=new ();
h1
endclass
module test;
base h1, h2 b=10 h a=20
initial
begin
h2
h1=new();
h1.b=10;
h1.h.a=20;
b=10
h2=new h1;//shallow copy //handle assignment
h2.h.a=30;
end
endmodule

34. What is inheritance?


A: -Allows you to create new classes based on existing classes. This mechanism
facilitates code reuse and promotes hierarchical design, making it easier to
manage and extend complex designs.
Syntax: - class base-class extends derived-class;
Ex: - class base;
int a;
endclass
class sub extends base;
int b;
endclass
module test;
sub h;
initial begin
h=new ();
h. a=10;
h. b=20;
end
endmodule
35. What is polymorphism?
A: - Polymorphism means having many forms. A base class handle can invoke
methods of its child class which has the same name. Hence, an object can take
many forms.
Rules: -
=>Assignment of derived class handle to base class handle is allowed.
Ex: -
Class base;
//definition
Endclass
Class child;
//definition
endclass

module test;
base b = new;
child c = new;
initial begin
b = c; // Allowed
end
endmodule
=>Assignment of base class handle to derived class handle is NOT allowed and
results in compilation error.
Ex: -
Class base;
//definition
endclass
Class child;
//definition
endclass
module test;
base b = new;
child c = new;
initial begin
c=b; // Compilation error
end
endmodule
=>$cast returns 0 if the cast failed, so use the return type to throw an error.
Use if or assert to ensure that the cast is successful.
Ex: -
Class base;
//definition
Endclass
Class child;
//definition
Endclass
module test;
base b = new;
child c = new;
initial begin
if ($cast (c, b))
$display (“casting ture”);
else
$display (“casting fail”);
end
endmodule

36. What are global constant properties?


A: - Global constant properties: We are using the const keyword before datatype.
We cannot change values inside the program; for example, if we change the value,
it shows an error.
Ex: class base;
const int b=20;
endclass
base h= new ();
module test;
initial begin
h. b=10;///here shows error
end
endmodule

37. What is a super keyword?


A: - The “super” keyword is referred to base class properties.
Ex:- class base ;
int a;
endclass
class sub;
int a;
function void ();
return super. a+a;
endfunction
endclass

38. What is a chaining constructor?


A: -
Ex: class base;
int a;
endclass
class sub extends base (4);//When creating instance for class base ,it passes 4
to the constructor of class sub.
int b;
endclass

39. What is the overriding method?


A:- Class base;
task body();
//definition
endtask
endclass
Class child;
task body();
//definition
endtask
endclass
module test;
child h=new();
initial begin
h. body () ;//we call body it can overriding
end
endmodule

40. What are parameterized classes?


A: -Parameters are like constants that are local to the specified class.
Syntax: - class <class name> # (datatype var=1)
<body>
endclass
Ex: class c # (int size=1);
bit [size-1:0] a;
endclass

41. What is a virtual class?


A: virtual class:
 Virtual class northing but abstract class.
 Abstract classes are classes that cannot be instantiated be used as base
classes for the classes.
 Abstract classes can provide a high level of abstraction and flexibility for
the code.
 Abstract classes are defined using virtual keyword before class.
Syntax:
virtual class <class name>;
<class body>;
endclass
 Abstract classes cannot be instantiated directly as they are not actual
classes.
 We need to create a sub-class from this abstract class which can be
instantiated and used in the code.
 Creating a sub-class of abstract class is like creating a sub-class of normal
classes.
 We use extends keyword to define a sub-class.
Syntax: class <sub_class> extends <virtual_class_name>;

42. What is pure virtual method?


A: -Pure virtual functions:
=>These are special kinds of method definition which can only be used inside a
virtual class.
=>By using a pure keyword with the method definition, we do not need to write
the body of method inside virtual class.
Syntax: pure virtual <method name> ();
=> We cannot have a method body defined while using pure virtual methods.
Doing so will lead to compile time errors.

43. What is randomization?


A: - Randomization:
=>Randomization is the process of assigning random values to variables or
objects in System Verilog.
=> It helps achieve better functional and code coverage of DUT.
=> In a test bench, we need to generate lots of stimulus for the DUT.
=> The $random and $urandom without system function we can randomize.
=> we can declare any variable defined inside a class as random. These random
variables are randomized whenever we call randomize function on the class
object handle.
Randomization variables:
=>rand: The rand keyword means that the variable or object can take any value
within its range.
=>randc: The randc keyword means that the variable or object can take any value
within its range, but not the same value until on the possible random values have
been used.
• Using randc ensures that we get unique random values.

Ex:- Class tx;


rand bit[1:0]a;//0,1,2,3 vaild -0,1,2,0 vaild
randc bit[1:0]b;//0,1,2,3 vaild -0,1,2,1 invaild
endclass
Randomize () Methods:
=> In System Verilog all classes have an in-built method randomize which can be
called to randomize the variables.
=> It is a return type method; it will return “1” randomization is successful, or
return “0” randomization will fail.
Ex: module test;
class trans;
rand bit [1:0] a;
randc bit [1:0] b;
endclass
trans h=new ();
initial begin
assert (h. randomize ())
end
endmodule
pre_randomize ():
=>This is a callback function which is called automatically when we
call randomize function.
=>This function is defined within the same class object will be randomized and
before randomization.
=> The pre-randomize method is void type.
Syntax: function void pre_randomize ();
Ex: class trans;
rand bit [7:0] var;
constraint c {var inside { [1:10]};}
function void pre_randomize ();
$display (“before randomize”);
endfunction
endclass
post_randomize ():
=>This is a callback function which is called automatically when we
call randomize function.
=>This function is defined within the same class object will be randomized and
after randomization.
=> The post_randomize method is void type.
Syntax: function void post_randomize ();
Ex: class trans;
rand bit [7:0] var;
constraint c {var inside { [1:10]};}
function void post_randomize ();
$display (“after randomize”);
endfunction
endclass
44. What are the constraints in system Verilog?
A: - Constraints restrict the random data generation to meaningful values.
Syntax: constraint constraint_name {expression;}
• rand_mode ()
• constraint_mode ()
Ex: module test;
class trans;
rand bit [7:0] var;
constraint c {var inside { [1:10]};
endclass
trans h=new ();
initial begin
int success;
if (h. rand_mode ())// if rand_mode is one randomization happen
begin
for (int i=0;i<10;i++)
success= h. randomize ();
end
h. c. constraint_mode (0);//the constraint_mode is “0” constraint is
not working
success=h. randomizes () with {var >90;};
h. c. constraint_mode (1); // the constraint_mode is “1”
constraint is working
success= h. randomize ();
end
endmodule
Constraints inheritance:
=>Constraint blocks for a parent class can be overridden by its child class.
=>Thus, the inherited class can modify constraints based on the requirement.
=>The constraints name should be same.
Ex: module test;
class trans;
rand bit [7:0] var;
constraint c {var inside { [1:19]};}
endclass
class trans1 extends trans;
rand bit [7:0] var;
constraint c1 {var inside { [19:40]};}
endclass
trans1 h=new ();
initial begin
int success;
success= h. randomize ();
$display (“display var %d”, h .ar );
end
endmodule
Constraints overriding:
=>The randomize() function is virtual ,constraint is act like virtual.
=>The constraint name must be same.
Ex: module test;
class trans;
rand bit [7:0] var;
constraint c {var inside {[1:19]};}///constraint name c
endclass
class trans;
rand bit [7:0] var;
constraint c {var inside {[19:40]};}// constraint name c
endclass
trans h=new ();
initial begin
int success;
success= h. randomize ();
$display (“display var %d”, h .var );
end
endmodule
soft constraints:
=>A soft constraint is a constraint on a random variable, which allows overriding
the constraint.
Syntax: constraint c_name {soft variable {condition};}
module test;
class trans;
rand bit [7:0] var;
constraint c {soft var >60;}//Here we used soft keyword it will
endclass disable the constraint
trans h1=new ();
initial begin
assert (h1. randomize () with {var<60;})//tempary constraint
end
endmodule
set membership constraints:
=>A set membership is a list of expressions or a range. This operator searches for
the existences of the value in the specified expression or range.
Syntax: constraint c_name {variable inside {values or range};}
module test;
class trans;
rand bit [7:0] var;
constraint c {var inside {[0:10]};} //here giving range 0 to 10
endclass
trans h1=new ();
initial begin
assert (h1. randomize ())
$display (“display values %0d”, h1.var);
end
endmodule
o/p:0,1,2,3,4,5,6,7,8,9,10
set membership from an array constraint:
module test;
class trans;
rand bit [3:0] var;
bit [3:0] var_1[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14};
constraint c {var inside {var_1};}
endclass
trans h1=new ();
initial begin
assert (h1. randomize ())
$display (“display values %0d”, h1.var);
end
endmodule
o/p: 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14
conditional constraints:
(->) implication operator:
module test;
class trans;
rand bit [3:0] var;
int var_1;
constraint c {var_1==1 -> var<20;
var_1==0 -> var>20;}
endclass
trans h1=new ();
initial begin
var_1=1;//var_1=0 ;//o/p:20……………
assert (h1. randomize ())
$display (“display values %0d”, h1.var);
end
endmodule
o/p:0……...20;
if _else operator:
module test;
class trans;
rand bit [3:0] var;
int var_1;
constraint c {if(var_1==1)
var<20;
else if(var_1==0)
var>20;}
endclass
trans h1=new ();
initial begin
var_1=1;//var_1=0 ;//o/p:20……………
assert (h1. randomize ())
$display (“display values %0d”, h1.var);
end
endmodule
o/p:0……...20;
Distribution constraints:
=>In weighted distribution weight will be specified to the values inside the
constraint block.
=>Value with the more weight will get allocated more often to a random variable.
=> Value: desired value to a random variable.
=> weight: indicates how often the value needs to be considered on
randomization
• :=
Syntax: value := weight
=>constraint c{var dist{value:=weight;}
=> The := operator assigns the specified weight to the item, or if the item is a
range, specified weight to every value in the range.

• :/
Syntax: value :/ weight
=>constraint c{var dist{value:/weight;}
=> The :/ operator assigns the specified weight to the item, or if the item is a
range, specified weight/n to every value in the range.
=> where n is the number of values in the range.
module test;
class trans;
rand int var;
constraint c {var dist {5:/10, 2=:10, [0:9]:=2,[0:9]:/2};}
endclass
trans h1=new ();
initial begin
assert (h1. randomize ())
$display (“display values %0d”, h1.var);
end
endmodule
static constraints:
=> “static” keyword using before constraint. We write multiple handles it will
create only one memory.
module test;
class trans;
rand int var;
static constraint c {var dist {5:/10, 2=:10, [0:9]:=2,[0:9]:/2};}
endclass
trans h1=new ();
initial begin
assert (h1. randomize ())
$display (“display values %0d”, h1.var);
end
endmodule
extern constrains:
module test;
class trans;
rand int var;
constraint c;
endclass
constraint c1::c {var inside {[1:19]};}
trans h1=new ();
initial begin
assert (h1. randomize ())
$display (“display values %0d”, h1.var);
end
endmodule
(::) scope resolution operator:
=>The scope resolution operator is used to refer identifier within the scope of a
class.
class packet;
bit [31:0] addr;
static bit [31:0] id;
function display (bit [31:0] a,b);
$display ("Values are %0d %0d”, a, b);
endfunction
endclass

module test;
int id=10;
initial begin
packet p;
p = new();
packet::id = 20;
p. display (packet::id,id);
end
endmodule
inline constraints:
module test;
class trans;
rand bit [7:0]z,b, c;
constraint c{c=a+b};
endclass
trans h1=new ();
initial begin
if (! h1. randomize () with {a<b;})
$display (“randomization fail);
end
endmodule

45. What are threads in System Verilog?


=> A thread or process is any piece of code that gets executed as a separate entity.
In Verilog, each of the initial and always blocks are spawned off as separate
threads that start to run in parallel from zero time.
=>We have three types of threads
• fork ->join
=> Finishes when all child threads are over
Ex: module test;
initial begin
#10 $display (“thread A”, $time);
fork
#10 $display (“thread A1”, $time);
#20 $display (“thread A2”, $time);
#30 $display (“thread A3”, $time);
join
#50 $display (“thread B”, $time);
end
endmodule
o/p: time unit10-thread A, time unit 20-thread A1, time unit 30-thread A2, time
unit 40-thread A3, time unit 90-thread B

• fork ->join_any
=> Finishes when any child thread gets over.
Ex: module test;
initial begin
#10 $display (“thread A”, $time);
fork
#10 $display (“thread A1”, $time);
#20 $display (“thread A2”, $time);
#30 $display (“thread A3”, $time);
join_any
#50 $display (“thread B”, $time);
end
endmodule
o/p: : time unit10-thread A, time unit 20-thread A1, time unit 50-thread B
time unit 30-thread A2, time unit 40-thread A3

• fork ->join_none
=> Finishes soon after child threads are spawned.
Ex: module test;
initial begin
#10 $display (“thread A”, $time);
fork
#10 $display (“thread A1”, $time);
#20 $display (“thread A2”, $time);
#30 $display (“thread A3”, $time);
join_none
#50 $display (“thread B”, $time);
end
endmodule
o/p: time unit 10-thread A, time unit 20-thread A1, time unit 30-thread A2, time
unit 40-thread A3, time unit 50-thread B.

46. What is a mailbox in System Verilog?


A: =>mailbox is inbuilt parameterized class is used for communication.
=>mailbox method are two types
• blocking methods
 get ()
=>Blocking method until it can retrieve one message from the
mailbox, if empty blocks the process
 put ()
=>Blocking method that stores a message in the mailbox in FIFO
order; message is any singular expression.
 peek ()
=>Copies one message from the mailbox without removing the
message from the mailbox queue.
• non_blocking methods
 try_get ()
=>Non-blocking method which tries to get one message from the
mailbox, returns 0 if empty.
 try_put ()
=>Non-blocking method that stores a message if the mailbox is not
full, returns a positive integer if successful else 0.
 try_peek ()
=>Tries to copy one message from the mailbox without removing
the message from queue.
Mailbox types:
• parameterized mailbox
syntax: mailbox #(trans) mail_h=new ();
 parameterized mailbox that can accept items of only a specific data
type.

• bounded mailbox
syntax: mailbox mail_h=new (10);

• unbounded mailbox
syntax: mailbox mail_h=new ();

• generic mailbox
syntax: mailbox mail_h=new ();
 generic mailbox that can accept items of any data type.
Ex:
module test;
mailbox mbx=new ();
initial begin
for (int i=0; i<10; i++)
begin
mbx.put(i);
$display (i);
end
end
initial begin
forever
begin
int idx;
mbx.get(idx);
$display (idx);
end
end
endmodule
47. What is a semaphore?
A: =>Semaphore is built in class
=>Syntax: semaphore [var_name];
=>Semaphore used for access control to shared resources, and for basic
synchronization.
=> The same memory location is accessed by two different cores.
=> To avoid unexpected results when cores try to write or read from the same
memory location, a semaphore can be used.
Semaphore methods:
get ()
=>The get () method in semaphore is used to obtain a specified number of keys.
=>By default, one key is returned if no value is specified.
=> The get () method is a blocking method and execution continues after
successful key or keys are obtained.
Syntax:
=>semaphore. get(no_of_keys);
put ()
=>The put () method in semaphore is used to return a specified number of keys
to the semaphore container or bucket.
Syntax:
=>semaphore. put (no_of_keys);
try_get ()
=>The try_get () is a non-blocking method. The execution is not blocked even if
the number of keys is not available.
=>The try_get () function returns 1 if keys are available otherwise, it returns 0 if
no keys are available,
Syntax:
=>semaphore.try_get(no_of_keys);
semaphore: multiple keys and single key also we can use.
Ex: module semaphore_example ();
semaphore sem = new (3);
task process_A ();
sem.get (3);
$display ("process_A started");
#5ns;
$display ("process_A completed");
sem.put (3);
endtask

task process_B ();


sem.get (2);
$display ("process_B started");
#4ns;
$display ("process_B completed");
sem.put (2);
endtask

initial begin
fork
process_A ();
process_B ();
join
end
endmodule
o/p:
process_A started
process_A completed
process_B started
process_B completed

48. What is a functional coverage?


A: =>Functional coverage deals with covering design functionality or feature
metrics that talks about how much design specification has been exercised.
=> The coverage model is defined using covergroup construct. The covergroup
construct is a user-defined type.
Syntax: covergroup cov_grp;
cov_p1: coverpoint a;
endgroup
cov_grp cov_inst = new () ;//cov_inst is the handle of covergroup
coverpoint: 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.
Bins are two types
Implicitly bins or automatic bin:
=>An automatically single bin will be created for each value of the coverpoint
variable range. These are called automatic, or implicit, bins.
=>For an “n” bit integral coverpoint variable, a 2^n number of automatic bins
will get created.
Ex: module cov;
logic [7:0] addr;
logic wr_rd;
covergroup cg;
c1: coverpoint addr;
c2: coverpoint wr_rd;
endgroup: cg
cg cover_inst = new ();
...
endmodule
o/p:
for addr: c1. auto [0] c1. auto [1] c1. auto [2] … c1. auto [255]
for wr_rd: c2. auto [0]
Explicit bins:
=> “bins” keyword is used to declare the bins explicitly to a variable.
=>A separate bin is created for each value in the given range of variable or a
single/multiple bins for the rage of values.
=>Bins are explicitly declared within curly braces { } along with the bins
keyword followed by bin name and variable value/range, immediately after the
coverpoint identifier.
Ex: module cov;
logic clk;
logic [7:0] addr;
logic wr_rd;
covergroup cg @(posedge clk);
c1: coverpoint addr { bins b1 = {0,2,7};
bins b2[3] = {11:20};
bins b3 = {[30:40],[50:60],77};
bins b4[] = {[79:99],[110:130],140};
bins b5[] = {160,170,180};
bins b6 = {200:$};
bins b7 = default;}
c2: coverpoint wr_rd {bins wrrd};
endgroup : cg
cg cover_inst = new();
...
endmodule
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.
covergroup cg @ (posedge clk);
c1: coverpoint addr{ ignore_bins b1 = {6,60,66};
ignore_bins b2 = (30=>20=>10);}
endgroup

illegal_bins:
=>A set of values or transitions associated with a coverage-point can be marked
as illegal by specifying them as illegal_bins.
Ex: covergroup cg @ (posedge clk);
c1: coverpoint addr{ illegal_bins b1 = {7,70,77};
ignore_bins b2 = (7=>70=>77);}
endgroup
cross:
=>Cross Coverage is specified between the cover points or variables. Cross
coverage is specified using the cross construct.
=> Expressions cannot be used directly in a cross; a coverage point must be
explicitly defined first.
Ex: bit [3:0] a, b;
covergroup cg;
c1: coverpoint a;
c2: coverpoint b;
c1Xc2: cross c1, c2;
endgroup : cg

You might also like