0% found this document useful (0 votes)
58 views60 pages

System Verilog Interview Questions

The document provides a comprehensive list of SystemVerilog interview questions and answers, covering topics such as packed and unpacked arrays, inheritance, polymorphism, and the differences between various data structures. It explains concepts like dynamic and associative arrays, virtual methods, abstract classes, and the importance of copy methods in transactions. Additionally, it addresses common programming issues like forward referencing and circular dependency, emphasizing best practices in SystemVerilog programming.

Uploaded by

Lakshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views60 pages

System Verilog Interview Questions

The document provides a comprehensive list of SystemVerilog interview questions and answers, covering topics such as packed and unpacked arrays, inheritance, polymorphism, and the differences between various data structures. It explains concepts like dynamic and associative arrays, virtual methods, abstract classes, and the importance of copy methods in transactions. Additionally, it addresses common programming issues like forward referencing and circular dependency, emphasizing best practices in SystemVerilog programming.

Uploaded by

Lakshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

SV Interview Questions

1. What is the difference between a packed array and an unpacked


array?
- Packed array refers to the dimensions declared before the
object name. Unpacked array is used to refer to the
dimension declared after the object name.
- Packed arrays can be made of single bit type (bit, logic,
reg, wire and other net types) while Unpacked arrays can be
made of any types.
- Example: bit [7:0] c1 ; //packed array
real u [7:0] ; //unpacked array

u
2. What is the difference between a packed and unpacked struct?
ur
- A packed structure consists of a bit fields , which are
packed together in a memory without gap. They are easily
converted to and form bit vectors. An unpacked structure has
an implementation-dependent packing normally matching the C
G
compiler.
- Packed Structure can be used as a whole with arithmetic and
logical operator. The structures are declared using the
sic

packed keyword , which can be followed by the signed or


unsigned keywords, according to the desired arithmetic
behaviour. The signing of unpacked array is not allowed.

- Example: struct packed signed {


A

int a;
shortint b;
byte c;
bit [7:0] d;
} pack1 ; //signed, 2 states packed
structure

3. Difference between Associative array and Dynamic array ?


- A Dynamic array is one dimension of an unpacked array whose
size can be set or changed at runtime. The space for a
dynamic array doesn’t exist until the array is explicitly
created at runtime. The new[] operator is used to set or
change the size of the array.

- Example: bit [3:0] nibble[]; //dynamic array of 4-bit


vector
nibble = new[100]; //creates a 100-
elements array
- Associative array is used when the data space is sparse.
They do not have any storage allocated until it is used, and
the index expression can be of any type.

- Example: bit [20:0] array_b[string]; // associative array


of 21 bitvector , index by string

u
4. Which of the array types: dynamic array or associative array,
are good to model really large arrays?
ur
- To model really large arrays in system Verilog , associative
arrays are generally better than dynamic array as it is
efficient for sparse data and enables flexible indexing.
G
5. Given a dynamic array of size 100, how can the array be re-
sized to hold 200 elements while the lower 100 elements are
sic

preserved as original?
- bit dyn_arr [];
dyn_arr = new[100]; // dynamic array of size 100
dyn_arr = new[200](dyn_arr); //resizing of dynamic array to
hold 200 elements preserving lower 100 elements
A

6. What is the difference between new() and new[] in


SystemVerilog?
- new() : Constructor to create and allocate an object for a
class. Creates memory for the class members and initializes
them with their default values.
- Ex: class pkt;
pkt p1;
p1 = new();
- new[] : operator to size/resize a dynamic array. Takes a
single value which defines the size of the array.
- Ex: bit dyn_arr [];
dyn_arr = new[100]; // dynamic array of size 100

7. What is OOPS?
- OOPS stands for Object Oriented Programming , it brings
object-oriented features into hardware verification, making
testbenches more modular, reusable and scalable.

8. What is inheritance and polymorphism?


- Inheritance is a mechanism of adding new
features(properties, methods) to an existing class by means
of new derived classes without modifying the existing
classes.
- INHERITANCE EXAMPLE:

u
class Animal;
function void speak();

endfunction
endclass
ur
$display("Animal speaks");
G
class Dog extends Animal;
function void speak();
$display("Dog barks");
sic

endfunction
endclass
// Dog inherits from Animal and overrides the speak()
method.
A

- Polymorphism allows the use of a variable in the superclass


to hold subclass objects, and to reference the methods of
those subclasses directly from the superclass variable.
- POLYMORPHISM EXAMPLE:
class Animal;
virtual function void speak(); // must be virtual
$display("Animal speaks");
endfunction
endclass

class Dog extends Animal;


function void speak();
$display("Dog barks");
endfunction
endclass

module test;
Animal a;
Dog d = new();

initial begin
a = d; // base class handle to derived class
object
a.speak(); // dynamic dispatch → Dog's speak() is called
end
endmodule

9. What is the relationship between classes and objects?

u
- A class is a type that includes data and subroutines that
operate on that data.
ur
- A class defines a data type. An object is an instance of
that class. An object is used by first declaring a variable
of that class type and then creating an object of that
class(using the new function) and assigning it to the
G
variable.
- Ex: Packet p; // declare a variable of class packet
P = new; // initialize variable to a new allocated
sic

object of the class packet

10. Explain about the virtual task and methods.


- Virtual methods are basic polymorphic construct. A virtual
A

method overrides a method in all the base classes, whereas a


normal method only overrides a method in that class and its
descendents.
- CODE EXAMPLE:
class Parent;
// Virtual method definitions
virtual function void show_msg();
$display("Parent: show_msg()");
endfunction

virtual task do_work();


$display("Parent: do_work()");
endtask
endclass
class Child extends Parent;
// Override the methods
function void show_msg();
$display("Child: show_msg()");
endfunction

task do_work();
$display("Child: do_work()");
endtask
endclass

module tb;
Parent p;
Child c;

u
initial begin
p = new();
p = c;
p.show_msg();
p.do_work();
end
ur
// Calls Child's function
// Calls Child's task
G
endmodule
sic

11. What is the difference between a virtual function and a


pure virtual function in SystemVerilog?
- In virtual function base class implementation can be
overridden in child class. The function in the base and
extended class should have same name, number & type of
A

arguments and same return type.


- Pure virtual function have only prototype in base class and
no implementation, while implementation is must in the child
class. It can be declared in a virtual class only.
- CODE EXAMPLE:
// Base class with virtual and pure virtual functions
class Base;

// Regular virtual function: has a default implementation


virtual function void show();
$display("Base: show()");
endfunction

// Pure virtual function: no implementation here


pure virtual function void display();
endfunction
endclass

// Derived class must implement the pure virtual function


class Derived extends Base;

// Override virtual function (optional)


function void show();
$display("Derived: show()");
endfunction

// Must implement pure virtual function


function void display();
$display("Derived: display()");

u
endfunction

endclass

module tb;
Base obj;
ur
G
initial begin
obj = new Derived();
obj.show(); // Calls Derived::show()
sic

obj.display(); // Calls Derived::display()


end
endmodule
A

12. What is the use of abstract class?


- An abstract class in SystemVerilog is a class that cannot be
instantiated directly. It serves as a base class that
provides a common interface (structure) for its derived
classes.
- CODE EXAMPLE:
// Abstract base class
class Shape;
// Pure virtual function — must be implemented in child
classes
pure virtual function void draw();
endclass

// Derived class 1
class Circle extends Shape;
function void draw();
$display("Drawing Circle");
endfunction
endclass

// Derived class 2
class Square extends Shape;
function void draw();
$display("Drawing Square");
endfunction
endclass

// Test
module test;

u
Shape s;
Circle c = new();
Square sq = new();

initial begin
s = c;
ur
G
s.draw(); // Outputs: Drawing Circle

s = sq;
sic

s.draw(); // Outputs: Drawing Square


end
endmodule
A

13. Explain about pass by ref and pass by value in System


Verilog?
- Pass by value is the default mechanism for passing arguments
to subroutines. This argument passing mechanism works by
copying each argument into the subroutine area.
- Arguments passed by reference are not copied into the
subroutine area, rather a reference to the original argument
is passed to the subroutine. The subroutine can then access
the argument data via the reference. Arguments passed by
reference must be matched with equivalent data types.
- CODE EXAMPLE:
module test;
// Pass by value: changes inside function do NOT affect
original variable
function void pass_by_value(int x);
x = x + 10;
$display("Inside pass_by_value: x = %0d", x);
endfunction

// Pass by reference: changes inside function DO affect


original variable
function void pass_by_ref(ref int x);
x = x + 10;
$display("Inside pass_by_ref: x = %0d", x);
endfunction

initial begin

u
int a = 5;
int b = 5;

pass_by_value(a);
ur
$display("After pass_by_value: a = %0d", a);
// a remains 5
G
pass_by_ref(b);
$display("After pass_by_ref: b = %0d", b);
sic

// b becomes 15
end

endmodule
A

14. What is the concept of a “ref” and “const ref” argument


in System Verilog function or task?
- To indicate argument passing by reference, the argument
declaration is preceded by the ref keyword.
- To protect arguments passed by reference from being modified
by a subroutine, the const qualifier can be used together
with ref to indicate that the argument, although passed by
reference, is a read-only variable. When the formal argument
is declared as a constref , the subroutine cannot alter the
variable, and an attempt to do so shall generate a compile
error.
- CODE EXAMPLE:
module test_ref_constref;
// Task with ref argument (can modify original)
task modify_ref(ref int x);
x = x + 10;
$display("Inside modify_ref: x = %0d", x);
endtask

// Task with const ref argument (cannot modify original)


task read_constref(const ref int x);
// x = x + 10;
// ERROR: cannot modify const ref argument
$display("Inside read_constref: x = %0d", x);
endtask

initial begin

u
int a = 5;

modify_ref(a);
ur
$display("After modify_ref: a = %0d", a);
// a becomes 15
G
read_constref(a);
$display("After read_constref: a = %0d", a);
// a remains 15
sic

end

endmodule
A

15. How to call the task which is defined in parent object


into derived class ?
- To call the task which is defined in parent class into
derived class , super keyword is used. This tells the
derived class to access the method defined in its base
class.
- Ex: class parent;
class child extends parent;
task display();
task display();
$display(“This is parent task”);
$display(“This is childtask”);
endtasksuper.display(); // calling
endclass
parent class task
endtask
endclass

16. What is forward referencing and how to avoid this


problem?
- Forward Referencing happens when one use or refer to an
identifier (like a variable, function, class, or module)
before it is declared or defined in the code. This causes a
compilation error because the compiler doesn’t know about
that identifier yet.
- To avoid forward referencing:
 Declare or define identifiers before use:Always write

u
the declaration/definition of variables, functions,
classes, or modules before they are referenced.
ur
 Use forward declarations:In SystemVerilog, one can use
forward declarations for classes or functions to let
the compiler know about their existence before full
definition.
G
- CODE EXAMPLE:
// forward declarations of functions to avoid forward
referencing
sic

class MyClass;
function void display();
// function prototype (declaration)
endfunction
endclass
A

// Later full definition outside the class


function void MyClass::display();
$display("Hello from display");
endfunction

17. What is circular dependency and how to avoid this problem


?
- Circular Dependency occurs when two or more modules,
classes, or files depend on each other directly or
indirectly, causing a cycle that the compiler or tools
cannot resolve.
- To avoid Circular Dependency:
 Use forward declarations :Declare a class or module
before full definition.
 Use hierarchical references carefully: Avoid cross-
dependencies.
- CODE EXAMPLE:
// Bad: Circular dependency
class ClassA;
ClassBb; // ClassB used here
endclass

class ClassB;
ClassAa; // ClassA used here → circular reference!
endclass

u
Fix by Forward Declaration:
class ClassB; // Forward declaration
endclass

class ClassA;
ur
ClassBb; // Now ClassB is known
G
endclass

class ClassB;
sic

ClassAa; // Now ClassA is fully declared


endclass

18. Which is best to use to model transaction? Struct or


class ?
A

- Class is better to use to model transaction because:


 Memory is allocated dynamically for classes.
 Classes supports randomization.
 Enables object-oriented programming (inheritance,
polymorphism)
 Classes can include methods for behavior.
 Suitable for complex, reusable verification
environments.

So, we can conclude that class provides


flexibility, reusability, and advanced

features essential for transaction modelling in modern


verification which is not
present in Struct.

19. What is the need to implement explicitly a copy() method


inside a transaction , when we can simple assign one object to
other ?
- When one object is assigned to other , a new object is not
created with the same values, instead the handles now point
to the same object in the memory( Shallow Copy is created)
- Ex. transaction t1,t2;
t1 = new();
t2 = t1; // this does not copy the content , it copies the
reference
Here t2 and t1 now point to the same object in memory
(Shallow Copy). So, any modification through t2 also affects

u
t1.

ur
To do a full (deep) copy, where everything (including nested
objects) are copied, custom code is typically needed.
For example:
Packet p1 = new;
G
Packet p2 = new;
p2.copy(p1)
sic

20. How different is the implementation of a struct and union


in SV.
- Difference in the implementation of a struct and union in
SV:
A

Aspect struct union


Memory Each member gets its own All members
Allocation distinct memory space. share the same
memory
location.
Size in bits Total size = sum of sizes of Total size =
all members (plus possible size of the
alignment). largest member.
Storage All fields can store values Only one field
Behavior simultaneously. can hold a
valid value at
a time — others
get
overwritten.
Access Accessing one member does not Accessing one
Semantics affect others. member affects
the value of
all others.
Assignment Whole struct can be assigned Assigning to
Semantics at once; members stay one field
independent. modifies the
shared memory,
impacting
others.

- Ex. typedef struct { bit [7:0] opcode;


bit [23:0] addr; } instruction; // named structure type
instruction IR; // define variable
Here opcode, addr have separate storage.
- Ex. typedef union { inti; shortreal f; }num;

u
- // named union type
num n;

21.
-
What is "this"?
ur
Here i and f share the same memory.

The this keyword is used to unambiguously refer to class


G
properties or methods of the current instance.
- The this keyword denotes a predefined object handle that
refers to the object that was used to invoke the subroutine
sic

that this is used within.


- The this keyword shall only be used within non-static class
methods, otherwise an error shall be issued.
- Ex. class Demo ;
integer x;
A

function new (integer x)


this.x = x;
endfunction
endclass
- In the above example xis both a property of the class and
an argument to the function new. To access the instance
class property, it is qualified with the this keyword, to
refer to the current instance.

22. What is tagged union ?


- The qualifier tagged in a union declares it as a tagged
union, which is a type-checked union.
- An ordinary (untagged) union can be updated using a value of
one member type and read as a value of another member type,
which is a potential type loophole.
- A tagged union stores both the member value and a tag, i.e.,
additional bits representing the current member name. The
tag and value can only be updated together consistently,
using a statically type-checked tagged union expression.

23. What is "scope resolution operator"?


- The class scope operator :: is used to specify an identifier
defined within the scope of a class.
- The scope resolution operator enables:
 Access to static public members (methods and class

u
properties) from outside the class hierarchy.
 Access to public or protected class members of a
ur
superclass from within the derived classes.
 Access to type declarations and enumeration named
constants declared inside the class from outside the
G
class hierarchy or from within derived classes.
- Ex. class Base;
typedef enum {bin,oct,dec,hex} radix;
static task print( radix r, integer n ); ... endtask
sic

endclass
...
Base b = new();
int bin = 123;
A

b.print( Base::bin, bin );


Base::print( Base::hex, 66 );
- Here ,
 Base::bin → enum value bin
 bin → the integer 123 defined as a local variable

24. What are void functions ?


- SystemVerilog allows functions to be declared as type void,
which do not have a return value.
- It is used for actions like logging, updating state, etc.
- Ex. function void print_msg(string msg);
$display("Message: %s", msg);
endfunction
25. How to make sure that a function argument passed has ref
is not changed by the function?
- To protect arguments passed by reference from being modified
by a subroutine, the const qualifier can be used together
with ref to indicate that the argument, although passed by
reference, is a read-only variable.
- Ex. function void show_val(const ref int data);
$display("Data: %0d", data);
data = 10; // ❌ Compilation error: Cannot modify const ref
endfunction

26. What is the use of "extern"?


- Extern keyword in system Verilog is used to move method
definitions out of the body of the class declaration.

u
- This is done in two steps. Declare, within the class body,
the method prototypes, the full argument specification plus

-
the extern qualifier. ur
The extern qualifier indicates that the body of the method
(its implementation) is to be found outside the declaration.
Then, outside the class declaration, declare the full
G
method. And, to tie the method back to its class, qualify
the method name with the class name and a pair of colons:
- Ex. class MyClass;
sic

extern function void display(int val);


endclass
function void MyClass::display(int val);
$display("Value = %0d", val);
endfunction
A

- Using the extern keyword to place function (or task)


definitions in a separate file is highly beneficial for code
organization, readability, and reusability.

27. How to check whether a handles is holding object or not ?


- In System Verilog, to check whether a handle is holding an
object or not , a simple null check can be used.
- Ex. class Packet;
int data;
endclass

Packet p;
initial begin
if (p == null)
$display("Handle p is null — no object allocated.");
else
$display("Handle p is valid.");

// Allocate object
p = new();

if (p != null)
$display("Now handle p points to an object.");
end

28. What is the difference between private, public and

u
protected data members of a System Verilog class?
- Public:
ur
Class data members and methods are accessible from
anywhere: inside the class, outside the class, and in
derived classes. It is a default access type in
SystemVerilog.
G
Ex. class A;
int a = 10; // public by default
endclass
sic

initial begin
Aobj = new;
$display("a = %0d", obj.a); // ✅ Allowed
end
A

- Private:
Class data members and methods are accessible only inside
the class where it is defined and not accessible from
outside the class or in derived classes.
Ex. class A;
private int x = 42;
function void show();
$display("x = %0d", x); // ✅ Allowed
endfunction
endclass

class B extends A;
function void try_access();
$display("x = %0d", x); ❌ Error: private member not
accessible
endfunction
endclass

- Protected:
Class data members and methodsare accessible inside the
class and in derived classes and not accessible from outside
the class hierarchy.
Ex. class A;
protected int y = 7;
endclass

class B extends A;
function void show();

u
$display("y = %0d", y); // ✅ Allowed
endfunction
endclass

initial begin
B b = new();
ur
G
$display("%0d", b.y); ❌ Error: protected member not
accessible from outside
end
sic

29. Are System Verilog class members public or private by


default ?
- System Verilog class members are public by default that is
class data members and methods are accessible from anywhere:
A

inside the class, outside the class, and in derived classes.

30. What are interfaces in SystemVerilog?


- Interfaces in SystemVerilog are a powerful abstraction
mechanism used to bundle related signals and communication
protocols into a single unit.
- By encapsulating the communication between blocks, the
interface construct also facilitates design re-use.
- Ex. interface simple_bus; // Define the interface
logic req, gnt;
logic [7:0] addr, data;
logic [1:0] mode;
logic start, rdy;
endinterface: simple_bus
- Above example defines an interface named simple_bus that
bundles together a group of related signals (like req, gnt,
addr, data, etc.) used for communication between modules.
- Instead of declaring all these signals separately in every
module (e.g., master, slave), the interface allows you to
pass them asa single object, making the design cleaner,
modular, easier to maintain and scale.

31. What is a modport construct in an interface?


- To provide direction information for module ports and to
control the use of tasks and functions within particular
modules, the modport construct is provided. As the name
indicates, the directions are those seen from the module.

u
- Ex. interface i2;
wire a, b, c, d;

-
endinterface
ur
modport master (input a, b, output c, d);
modport slave (output a, b, input c, d);

In the above example i2 interface uses modports to control


G
access:
master reads a,b , writes c,d while slave writes a,b ,
reads c,d.
sic

32. What is the use of modports ?


- Modports in SystemVerilogorganize and protect how modules
use interface signals
A

- Control signal directions (input/output/inout) for different


modules using an interface.
- Restrict access to interface signals (prevents incorrect
usage).
- Define clear roles, like master or slave, in a communication
system.

33. Are interfaces synthesizable?


- Yes, interfaces in SystemVerilog are synthesizable, but with
limitations:
- Synthesizable Features:
 Grouping of signals (like logic a, b, c)
 Modport definitions for direction control
 Constant declarations and parameterization
- Not Synthesizable:
 Tasks, functions, or procedural code inside the
interface
 Clocking blocks (in many synthesis tools)
 Assertions or initial blocks

34. What is the need of virtual interfaces?


- Virtual interfaces are used in testbenches to allow dynamic
access to physical interfaces from class-based components
( like drivers, monitors, etc).
- Normal interfaces are static hardware constructs meant for
connecting modules, not classes.

u
- Virtual interfaces provide a reference (handle) to a normal
interface, so that classes (like drivers, monitors, etc.)
ur
can access and control design signals dynamically at
runtime.
G
35. What are Semaphores? When are they used?
- A semaphore is a SystemVerilog built-in class used to
sic

control access to shared resources, mutual exclusion, and


for basic synchronization in concurrent environments.
- A semaphore is like a bucket of keys. Each key allows one
process to proceed. When all keys are taken, other processes
must wait until a key is returned. This controls how many
A

processes can access a shared resource at the same time.


- Semaphores are used when one need to:
 Control access to shared resources
 Limit the number of concurrent operations
 Synchronize parallel processes
- Ex. semaphore sema;
initial begin
sema = new(1); // Allow only 1 process at a time
end

initial begin
sema.get(1); // Wait to acquire
// Critical section
sema.put(1); // Release
end

36. What are Mailboxes? What are the uses of a Mailbox?


- A mailbox is a communication mechanism that allows messages
to be exchanged between processes. Data can be sent to a
mailbox by one process and retrieved by another.
- It acts like a FIFO queue where one process can send data
and other can receive it.
- Uses of a Mailbox:
 Inter-process communication: Used to pass data or
transactions between threads or components.
 Synchronization: Helps coordinate execution order
between processes.
 Decoupling: Helps data buffering.

u
- Ex. mailbox mbx = new();
initial begin

end
initial begin
ur
mbx.put(100); // Producer sends value
G
int val;
mbx.get(val); // Consumer receives value
$display("Received: %0d", val);
end
sic

37. What is difference between bounded and unbounded


mailboxes? How can we create unbounded mailboxes?
A

- A bounded mail box becomes full when it contains the bounded


number of messages. A process that attempts to place a
message into a full mailbox shall be suspended until enough
room becomes available in the mailbox queue. Unbounded
mailboxes never suspend a thread in a send operation.
- Bounded mailbox creation:
 mailbox #(5) mbx = new(5); // Holds up to 5 messages
- Unbounded mailbox creation:
 mailbox mbx = new(); // No size limit

38. What is the difference between mailbox and queue?


- Mailbox is a built-in class while queue is built-in data
type.
- Mailbox is used for inter-process communication while queue
is used for intra-process data storage and manipulation.
- Mailbox handles synchronization between processes but in
queue there is no synchronization, must be handled manually.
- Ex. Mailbox:
mailbox mbx = new();
initial begin
mbx.put(100); // Producer
end
initial begin
int val;
mbx.get(val);
// Consumer (blocks until value is available)
end
- Ex. Queue:

u
int q[$]; // Dynamic queue
initial begin
q.push_back(100); ur
// Add item
int val = q.pop_front(); // Remove item
end
G
39. What are the advantages of linkedlist over the queue ?
- Advantages of linkedlist over the queue :
sic

 Flexible Insertion/Deletion :Linked lists allow for


efficient insertion and deletion of elements at any
point in the list, regardless of their position.
 Dynamic Memory Allocation :Linked lists can grow or
shrink dynamically at runtime, allowing for efficient
A

memory usage without a predefined size limit.


 No Size Limitation :Linkedlist grows dynamically
without predefined size (unlike bounded queues).
 Better for Complex Data Handling :Linkedlist is Ideal
for situations with frequent and irregular data access
patterns.

40. How to pick a element which is in queue from random


index?
- To pick an element from a queue at a random index in
SystemVerilog:
 Use $urandom_range(0, queue.size()-1) to generate a
random valid index within the queue bounds.
 Access the element at that index using
queue[random_index].
- CODE EXAMPLE:
module queues_array;
//declaration
int queue[$];
int index;
int temp_var;

initial begin
//Queue Initialization:
queue = {7,3,1,0,8};

u
$display("----- Queue elements with index -----");
foreach(queue[i])
ur
$display("\tqueue[%0d] = %0d",i,queue[i]);
$display("-------------------------------------\n");

$display("Before Queue size is %0d",queue.size());


G
repeat(2) begin //{
index = $urandom_range(0,4); //index of queue is
from 0 to 4
sic

temp_var = queue[index];
$display("Value of Index %0d in Queue is
%0d",index,temp_var);
end //}
$display("After Queue size is %0d",queue.size());
A

end
endmodule
41. What data structure is used to store data in your
environment and why ?
- Data structure used to store data in environment are:
 Queue (queue[$]) :can grow and shrink during
simulation and elements can be accessed by index.
CODE EXAMPLE:
module simple_queue_example;
int queue[$]; // Declare a queue of integers

initial begin
// Add elements to the queue
queue.push_back(5);
queue.push_back(10);
queue.push_back(15);

// Display queue elements


foreach (queue[i])
$display("queue[%0d] = %0d", i, queue[i]);

// Remove first element


int removed = queue.pop_front();
$display("Removed element: %0d", removed);

// Display updated queue


foreach (queue[i])
$display("queue[%0d] = %0d", i, queue[i]);
end

u
endmodule

 ur
Associative Array: Useful when keys are not sequential
integers or are strings, enums, etc. Useful for sparse
or random access with custom keys.
CODE EXAMPLE:
G
module assoc_array_example;
// Declare associative array with int key and int
value
sic

int assoc_array[string];

initial begin
assoc_array["apple"] = 10;
assoc_array["banana"] = 20;
A

assoc_array["cherry"] = 30;

foreach (assoc_array[key])
$display("Key = %s, Value = %0d", key,
assoc_array[key]);
end
endmodule

 Dynamic Array :use when resizable ordered collection


of elements is needed andwant to change the size at
runtime (grow or shrink).
CODE EXAMPLE:
module dynamic_array_example;
int dyn_array[];
initial begin
// Allocate size 3
dyn_array = new[3];
dyn_array[0] = 10;
dyn_array[1] = 20;
dyn_array[2] = 30;

foreach(dyn_array[i])
$display("dyn_array[%0d] = %0d", i,
dyn_array[i]);

// Resize to 5
dyn_array = new[5];
dyn_array[3] = 40;

u
dyn_array[4] = 50;

ur
$display("After resizing:");
foreach(dyn_array[i])
$display("dyn_array[%0d] = %0d", i,
dyn_array[i]);
G
end
endmodule
sic

42. What is the difference between $random and $urandom?


- $random is a SystemVerilog system function used to generate
32-bit signed pseudo-random numbers.
A

- Syntax: int rand_val;


rand_val = $random;
- The $urandom system function returns a new 32-bit unsigned
random number each time it is called.
- Syntax: int unsigned rand_val;
rand_val = $urandom;
- The $urandom function is similar to the $random system
function, with two exceptions. $urandom returns unsigned
numbers and is automatically thread stable.
- Ex. initial fork
begin
repeat (3) $display("T1: %0d", $urandom);
end
begin
repeat (3) $display("T2: %0d", $urandom);
end
join
- Here each thread (T1, T2) will produce independent random
values. If $random is used instead, the output may interfere
and overlap due to shared state.

43. What is scope randomization.


- Scope randomization in SystemVerilog allows you to apply
randomization constraints to individual variables or
specific parts of a design hierarchy, outside of classes.
- CODE EXAMPLE:
module tb;
byte data;

u
initial begin

result
end
ur
randomize(data) with { data>0 }; // Randomize data > 0
$display("data = 0x%0h", data); // Display the
G
endmodule
// randomization applies to variables in the current
procedural scope
sic

44. List the predefined randomization methods.


- Randomization methods:
 randomize() : triggers randomization of class
A

variables marked with rand or randc.


 pre_randomize() :Automatically called before
randomize() is executed. Used to set up or modify
constraints or states before randomization.
 post_randomize() :Automatically called after
randomization is done.
Used to take actions based on the randomized values.
- CODE EXAMPLE:
class packet;
rand bit [3:0] addr;

// Called before randomize()


function void pre_randomize();
$display(">> Inside pre_randomize()");
endfunction

// Called after randomize()


function void post_randomize();
$display(">> Inside post_randomize(): addr = %0d",
addr);
endfunction
endclass

module tb;
initial begin
packet p = new();

if (p.randomize())

u
$display(">> Randomization SUCCESS");
else

end
endmodule
ur
$display(">> Randomization FAILED");
G
45. What is the difference between rand and randc?
- Variables declared with the rand keyword are standard random
sic

variables. Their values are uniformly distributed over their


range.
- Ex. rand bit [7:0] y;
- This is an 8-bit unsigned integer with a range of 0 to 255.
If unconstrained, this variable shall be assigned any value
A

in the range 0 to 255 with equal probability.


- Variables declared with the randc keyword are random-cyclic
variables that cycle through all the values in a random
permutation of their declared range. Random-cyclic variables
can only be of type bit or enumerated types, and can be
limited to a maximum size.
- Ex. consider a 2-bit random variable y:
randc bit [1:0] y;
- Here randc randomly iterates over all the values in the
range and that novalueis repeated within an iteration. When
the iteration finishes, a new iteration automatically
starts.
46. Without using randomize method or rand,generate an array
of unique values?
- To generate an array of unique values one can implement a
loop that generates unique random values and stores them in
a queue, without using rand or randomize(). Instead, we'll
use $urandom or $urandom_range() and check for uniqueness
before pushing.
- CODE EXAMPLE:
module tb;
int queue_of_unique_values[$]; // Dynamic queue
int rand_val;
int count = 0;

function bit exists_in_queue(int val);


foreach (queue_of_unique_values[i]) begin

u
if (queue_of_unique_values[i] == val)
return 1;
end
return 0;
endfunction
ur
G
initial begin
// Goal: Generate 10 unique random values in the range
0–19
sic

while (queue_of_unique_values.size() < 10) begin


rand_val = $urandom_range(0, 19);
if (!exists_in_queue(rand_val)) begin
queue_of_unique_values.push_back(rand_val);
end
A

end

// Display the unique values


$display("Unique random values:");
foreach (queue_of_unique_values[i])
$write("%0d ", queue_of_unique_values[i]);
$display();
end
endmodule

47. How to randomize dynamic arrays of objects?


- Steps to randomize dynamic arrays of objects :
- Declaring the dynamic array with the rand keyword in the
class.
- Creating constraints that apply to the array size and/or the
properties of the individual objects inside the array.
- Ensuring that the objects in the dynamic array are
instantiated (created with new) before calling randomize().
- Using randomize() on the containing class instance will
randomize the size of the dynamic array (if constrained) and
the properties of each object if those are marked rand and
constrained.
- CODE EXAMPLE:
class Packet;
rand bit [3:0] d_array []; // Declare a dynamic
array with "rand"

u
// Constrain size of dynamic array between 5 and 10
constraint c_array{ d_array.size() > 5; d_array.size() <
10; } ur
// Constrain value at each index to be equal to the index
itself
G
constraint c_val { foreach (d_array[i])
d_array[i] == i;
}
sic

// Utility function to display dynamic array contents


function void display();
foreach (d_array[i])
$display ("d_array[%0d] = 0x%0h", i, d_array[i]);
A

endfunction
endclass

module tb;
Packet pkt;

// Create a new packet, randomize it and display contents


initial begin
pkt = new();
pkt.randomize();
pkt.display();
end
endmodule
48. What is rand sequence and what is its use?
- randsequence is a SystemVerilog construct used to generate
constrained random scenarios using a grammar-like production
rule structure.
- Ex. randsequence( main )
main : first second done ;
first : add | dec ;
second : pop | push ;
done :{ $display("done"); } ;
add:{ $display("add"); } ;
dec :{ $display("dec"); } ;
pop :{ $display("pop"); } ;
push :{ $display("push"); };
endsequence

u
- The production main is defined in terms of three
ur
nonterminals: first, second, and done. When main is chosen,
it generates the sequence, first, second, and done. When
first is generated, it is decomposed into its productions,
which specifies a random choice between add and dec.
G
Similarly, the second production spec ifies a choice between
pop and push. All other productions are terminals; they are
completely specified by their code block, which in the
sic

example displays the production name.


- Thus, the grammar leads to the following possible outcomes:
add pop done
add push done
dec pop done
A

dec push done


- USE:
 To model random scenarios, sequences of actions, or
stimuli.
 Commonly used in testbenches for protocol simulation,
bus transactions, and random event generation.
 Allows weighted random choices and hierarchical
control over random behavior.

49. How to add a new processs without disturbing the random


number generator state ?
- To add a new process without disturbing the random number
generator state in SystemVerilog, one should use $urandom
or $urandom(seed) instead of $random.
- It ensures independent and thread-stable randomization for
each process.
- Ex. initial begin
fork
begin
int a = $urandom;
$display("Thread 1: %0d", a);
end
begin
int b = $urandom;
$display("Thread 2: %0d", b);
end

u
join
end
- ur
Here each thread will generate independent random values.
G
What are pre_randomize() and post_randomize() functions?
- Every class contains built-in pre_randomize() and
post_randomize() functions, that are automatically called by
sic

randomize() before and after computing new random values.


- When obj.randomize() is invoked, it first invokes
pre_randomize() on obj and also all of its random object
members that are enabled. pre_randomize() then calls
super.pre_randomize().
A

- After the new random values are computed and assigned,


randomize() invokes post_randomize() on obj and also all of
its random object members that are enabled. post_randomize()
then calls super.post_randomize().
- These are empty built-in hooks (i.e., callback functions).So
, they will do nothing until we override them.
- Ex. class Packet;
rand bit [3:0] addr;
function void pre_randomize();
$display(">>> About to randomize...");
//overriding pre_randomize
endfunction
function void post_randomize();
$display("<<< Done randomizing. addr = %0d",
addr); //overriding post_randomize
endfunction
endclass
module tb;
initial begin
Packet p = new();
p.randomize();
end
endmodule

50. What are bi-directional constraints?


- Bi-directional constraints are constraints where multiple
random variables influence each other simultaneously, and

u
the solver finds values for all variables together to
satisfy all constraints without conflict.
- CODE EXAMPLE:
class seq_item;
ur
rand bit [7:0] val1, val2, val3, val4;
rand bit t1, t2;
G
constraint val_c {val2 > val1;
val3 == val2 - val1;
sic

val4 < val3;


val4 == val1/val3; }

constraint t_c{ (t1 == 1) -> t2 == 0;}


endclass
A

module constraint_example;
seq_item item;

initial begin
item = new();

repeat(5) begin
item.randomize();
$display("val1 = %0d, val2 = %0d, val3 = %0d, val4 =
%0d", item.val1, item.val2, item.val3, item.val4);
$display("t1 = %0h, t2 = %0h", item.t1, item.t2);
end
end
endmodule

- This code demonstrates bi-directional constraints where


multiple variables (val1, val2, val3, val4) are
interdependent and solved together by the randomizer (e.g.,
val3 == val2 - val1 and val4 == val1 / val3). The solver
adjusts all variables simultaneously to satisfy all
constraints without conflicts.

51. What is a unique constraint in SystemVerilog?


- The unique constraint ensures that all specified variables
or expressions get distinct values during randomization.

u
- Ex. class Example;
rand int a, b, c;
constraint unique_c {

endclass
}
ur
unique {a, b, c};
G
- This ensures that a, b, and c will be different from each
other every time they are randomized.
sic

52. How can we disable or enable constraints selectively in a


class?
- The constraint_mode() method can be used to enable or
disable any named constraint block in an object.
A

- Ex. class Packet;


rand bit [7:0] addr;
constraint high_range{ addr inside {[100:200]}; }
constraint low_range {addr inside {[0:50]}; }
endclass

module tb;
initial begin
Packet p = new();
// Disable low_range and enable high_range
p.low_range.constraint_mode(0);
p.high_range.constraint_mode(1);
p.randomize();
$display("Addr = %0d", p.addr);
end
endmodule

53. What is the difference between hard and soft constraints


- No keyword is required for hard constraints while soft
keyword is required for soft constraints.
- Hard constraints always take priority while soft constraint
applies only if no other constraint overrides it.
- Randomization failure occurs if hard constraint can’t be
met while soft constraint does not cause failure if
overridden.
- Ex. class Example;
rand int a;
// Soft constraint

u
constraint default_val{ soft a == 10; }
// Hard constraint overrides soft

-
ur
constraint limit_val{ a inside {[5:15]}; }
endclass
If limit_val is not defined, a will be 10 due to the soft
constraint.
G
But if a hard constraint defines a different allowed value,
it takes precedence over the soft one.
sic

54. Is it possible to override a constraint defined in base


class in a derived class and how?
- Yes , it is possible to override a constraintdefined in a
base class in a derived class.
A

- A constraint in a derived class that uses the same name as a


constraint in its parent classes overrides the base class
constraints.
- Ex. class A;
rand integer x;
constraint c { x< 0; }
endclass
class B extends A;
constraint c { x> 0; }
endclass
- The extended class B overrides the definition of constraint
c.
55. What is the purpose of solving constraints before
randomization?
- Constraint solving is essential before randomization to
ensure valid, consistent, and dependency-aware value
generation.
- Ex. class Packet;
rand bit [3:0] a, b;
constraint c {
a < b;
b < 10;
}
endclass
- Before generating values, the solver determines:
 Valid range for b is 1 to 9.

u
 Valid range for a is 0 to (b-1).
 Then it randomly assigns values satisfying both.

56.
-
ur
What is the use of packagess?
SystemVerilog packages provide an additional mechanism for
G
sharing parameters, data, type, task, function, sequence,
and property declarations amongst multiple SystemVerilog
modules, interfaces and programs.
- Packages are explicitly named scopes appearing at the
sic

outermost level of the source text


- Packages are powerful for modularity, code reuse, and
organization in large designs or verification environments.
- Ex. package common_pkg;
A

typedef enum {IDLE, BUSY} state_t;


function int add(int a, b); return a + b;
endfunction
endpackage
import common_pkg::*; // Use in module/testbench

57. How to import all the items declared inside a package ?


- To import all items declared inside a package in
SystemVerilog, use the wildcard ::* syntax with the import
statement.
- SYNTAX:
import package_name::*;
58. What is casting? Explain about the various types of
casting available in SV.
- Casting is the process of converting a variable or handle
from one data type to another. It helps in interpreting or
treating data differently without changing the actual bits
unless explicitly converted.
- Types of Casting in SystemVerilog:
1. Explicit Cast (Type Conversion) :Converts a value from
one data type to another explicitly.
Ex. int a = 10;
bit [7:0] b = bit'(a); // Cast int to 8-bit
bit vector
2. Handle Casting (Class Casting) :Converts one class
handle type to another.
Ex. class Base; endclass

u
class Derived extends Base; endclass
Derived d = new();
Base b = d; ur // Upcasting (implicit)
Derived d2 = Derived'(b); // Downcasting (explicit)
3. Dynamic Cast (using cast() method) :Safe runtime
casting for class handles.
G
Ex. Derived d3;
if (!$cast(d3, b)) //converting base class
handle to derived class handle at runtime.
sic

$display("Cast failed");
4. Wildcard Cast (type'()) :Similar to explicit cast but
used mainly for built-in types like bit, logic, int.
A

59. What is the use of $cast?


- The $cast system task in SystemVerilog is used for type
casting between class handles or data types, with runtime
type checking to ensure safety.
- $cast can be used either as a task or as a function to
determine how invalid assignments are handled.
- When called as a task, $cast attempts to assign the source
expression to the destination variable. If the assign ment
is invalid, a runtime error occurs and the destination
variable is left unchanged.
- When called as a function, $cast attempts to assign the
source expression to the destination variable, and returns 1
if the cast is legal& 0 if cast fails. No run time error
occurs when called as a function.
60. What is the need of clocking block?
- Clocking block identifies clock signals, and captures the
timing and synchronization requirements of the blocks being
modeled.
- The clocking block separates the timing and synchronization
details from the structural, functional, and procedural
elements of a testbench. Thus, the timing for sampling and
driving clocking block signals is implicit and relative to
the clocking-block’s clock. This enables a set of key
operations to be written very succinctly, without explicitly
using clocks or specifying timing.
- These operations are:
 Synchronous events

u
 Input sampling
 Synchronous drives
- Ex.
ur
interface intf (input logic clk);
logic req, gnt;
clocking cb@(posedge clk);
input gnt;
G
output req;
endclocking
endinterface
sic

- Here, req will be driven on the posedge of clk, and gnt will
be sampled on the posedge of clk, making testbench timing
predictable.
A

61. What is the difference between program block and module ?


How to implement always block logic in program block ?

Feature Module Program block


Purpose Models actual Used for testbench
hardware (DUT) logic
Region of Active Region Reactive region
execution
Always block Allowed( always, Not allowed
usage initial, etc)
Race Avoidance May have race Designed to avoid race
conditions with conditions
testbench
Synthesizable Yes (used in No (only for
synthesis) simulation/testbenches
)

- To implement always block logic in program block one can


use initial blocks combined with forever loops or event
control in a program.
- Ex. program test(input logic clk);
logic a;
initial begin
forever begin
@(posedge clk); // Like always @(posedge clk)
a = ~a;
end
end
endprogram

u
- This mimics always @(posedge clk) without using always.

62.
-
ur
Why always block is not allowed in program block?
Always block is not allowed in program block because:
 always is used to model hardware behavior, typically
G
inside a module.
 program blocks execute in a reactive region, after
hardware logic (RTL) finishes executing.
sic

 allowing always in a program block would blur the line


betweentestbench and DUT, causing race conditions and
timing issues.
A

63. What is advantage of program block over clockcblock w.r.t


race condition?
- program blocks guarantee no race with RTL because they
execute after module blocks (in the Reactive Region).
- clocking blocks help control timing within a testbench but
do not inherentlyprevent races—they still require careful
signal direction and timing control.

64. How to avoid the race condition between programblock ?


Difference b/w Procedural and Concurrent Assertions?
- Synchronize using semaphores/mailboxes if multiple programs
are used.
- Avoid shared variables between program blocks without
synchronization.
- Difference b/w Procedural and Concurrent Assertions:
 Procedural Assertions is Used inside procedural blocks
like always , initial while Concurrent Assertions is
used for monitoring temporal sequences over multiple
clock cycles.
 Syntax for Procedural
Assertions :assert(condition);,assume(condition);,cove
r(condition);.
 Syntax for Concurrent Assertions : assert property
(...), assume property (...), cover property (...)
 Procedural Assertions is Checked immediately during
execution while Concurrent Assertion is Checked in
concurrent assertion region after simulation time

u
advances.
 Procedural Assertion is Useful for simple, single-time
ur
checks while Concurrent Assertion is Ideal for
protocol and timing checks.
G
65. Difference between assert and expect statements?
- Assert:
 Checks a condition and immediately reports a failure
sic

if false.
 Does not block the current thread (non-blocking).
 Failure usually marks the test as failed or triggers
an error.
A

 Used for functional correctness


- Expect:
 Used to wait for a condition to become true within a
time frame (temporal check).
 Blocks the current thread until the condition passes
or fails.
 Failure does not count as a test failure—used for
coverage and monitoring expected behaviors.
 Think of it as a temporal if.
- CODE EXAMPLE:
module test_assert_expect;
bit clk = 0;
bit signal = 0;
always #5 clk = ~clk; // Clock with 10 time unit period

initial begin
// After 15 time units, signal becomes 1
#15 signal = 1;

// Assert example: checks immediately at this time, does


NOT block
assert(signal == 1) else $error("Assert failed: signal is
not 1");

// Expect example: waits up to 20 time units for signal


to become 0 (which it never does)
expect(signal == 0) @(posedge clk) else $display("Expect
failed: signal did not become 0 within timeout");

u
$finish;
end
endmodule
ur
G
66. What is the difference between assumes and assert?

Aspect Assume Assert


sic

Purpose Specifies Specifies


assumptions about properties the
the input design must
environment satisfy
Use case Used to constrain Used to check
A

input stimuli for design correctness


formal tools (output behavior)
Direction Input-driven Output-driven
(environment side) (design side)
Failure Assumption failure Assertion failure
interpretation means invalid means design bug —
input — formal must be fixed
tool ignores that
path
Usage Scenario assume property assert property
(reset == 0 ->req (req |-> ##1 gnt);
== 0); //Means: "If req
// Means: "We happens, then
assume that if grant must follow
reset is 0, then after 1 cycle."
req must be 0."
67. What is the difference between $rose and posedge?

Feature posedge $rose


Type Event control System function
expression (used in
assertions)
Usage Context Used in procedural Used in concurrent
blocks only (e.g., assertions.
always, initial,
wait)
Return Type Not a value — it's Returns a boolean
an event trigger (1 or 0)
Detects Rising edge of a True if signal
signal rose (0 → 1) in
current cycle

u
Ex( Posedge) :module posedge_example;
ur
logic clk, signal;
always @(posedge signal) begin
$display("posedge detected on
signal at time %0t", $time);
G
end
endmodule
 Here the always @(posedge signal) block waits for a
sic

rising edge of signal.It triggers procedural code


execution like $display.

Ex($rose) : module rose_example;


logic clk, signal;
A

// Simple clocking block to drive


property
property p_rise;
@(posedge clk) $rose(signal);
endproperty
// Assert the property
assert property(p_rise)
else $error("No rising edge on signal
detected at time %0t", $time);
endmodule
 Here $rose(signal) returns true for a single cycle
when signal goes from 0 to 1.
 It's used within a property and asserted.
 It is not used to trigger code but to validate
behavior.

68. What is the difference between fork/joins, fork/join_none


fork/join_any ?

Option Description
join The parent process blocks until all the
processes spawned by this fork complete. .
join_any The parent process blocks until any one of
the processes spawned by this fork complete.
join_none The parent process continues to execute
concurrently with all the processes spawned
by the fork. The spawned processes do not
start executing until the parent thread
executes a blocking statement.

u
CODE EXAMPLE:
initial begin
fork
#10 $display("Task
ur
1");
G
#20 $display("Task 2");
#30 $display("Task 3");
join // Waits for all 3 to complete
end
sic

initial begin
fork
#10 $display("Task A");
#20 $display("Task B");
A

#30 $display("Task C");


join_any // Waits for first to finish
$display("One task done");
end

initial begin
fork
#10 $display("X");
#20 $display("Y");
#30 $display("Z");
join_none // Does not wait
$display("Continue immediately");
end
69. How to kill a process in fork/join?
- To kill a process in a fork...join, we can use the process
class in SystemVerilog, specifically the kill() method, by
getting a handle to the process using process::self().
- CODE EXAMPLE:
module kill_fork_example;
process p1; // process handle

initial begin
fork
begin : TASK1
p1 = process::self(); // get handle to current
process

u
$display("[%0t] TASK1 started", $time);
#20;

end
join_none
ur
$display("[%0t] TASK1 completed", $time);
G
#5; // wait for a bit
if (p1.status() != process::FINISHED) begin
$display("[%0t] Killing TASK1", $time);
sic

p1.kill(); // kill the process


end

#10;
$display("[%0t] Simulation finished", $time);
A

end
endmodule

70. How to disable multiple threads which are spawned by


fork...join?
- To disable multiple threads spawned using fork...join, we
can use disable fork statement.
- The disable fork statement terminates all active descendants
(sub-processes) of the calling process.
- CODE EXAMPLE:
fork
begin : T1
#10 $display("Thread 1");
end
begin : T2
#20 $display("Thread 2");
end
join_none

#5;
disable fork; // disable both T1 and T2 threads

71. What is the use of “ wait fork” and “ disable fork”


constructs?
- The wait fork statement is used to ensure that all child
processes (processes created by the calling process) have
completed their execution.

u
- CODE EXAMPLE:
task do_test;
fork

join_any
exec1();
exec2();
ur
G
fork
exec3();
exec4();
sic

join_none
wait fork; // block until exec1 ... exec4 complete
endtask
- The disable fork statement terminates all active descendants
(sub-processes) of the calling process.
A

- CODE EXAMPLE:
fork
begin : T1
#10 $display("Thread 1");
end
begin : T2
#20 $display("Thread 2");
end
join_none
#5;
disable fork; // disable both T1 and T2 threads

72. What is final block ?


- The final block is a special procedural block in
SystemVerilog that is executed once at the end of simulation
— after all other events, time advancement, and simulation
activities are completed.
- CODE EXAMPLE:
module test;

int count = 0;

initial begin
repeat (5) begin
#10 count++;
end
end

u
final begin
$display("Simulation ended. Final count = %0d", count);
end

endmodule
ur
G
73. What is the difference between initial block and final
block?
sic

- The initial block executes once at the start of the


simulation, right after time 0. It is used to initialize
signals, variables, or perform setup tasks.
- CODE EXAMPLE:
initial begin
A

reset = 1;
#10 reset = 0;
end
- This sets reset high at time 0 and then de-asserts it after
10 time units.
- The final block executes once at the end of the simulation,
right before the simulation finishes and all processes
terminate.
- CODE EXAMPLE:
final begin
$display("Simulation finished at time %0t", $time);
end
- This prints a message just before the simulator stops.
74. What is callback?What is factory pattern ?
- Callbacks are a general programming concept available in
almost any language — basically, passing a function or
method to be called later in response to an event.
- Factory pattern overrides are a more specific Object-
Oriented Programming (OOP) design technique used to
dynamically instantiate different subclasses at runtime,
allowing flexible object creation without changing the
client code.

75. Explain the difference between data types logic, reg and
wire in system Verilog?

u
- Wire:
Represents a net data type. It models physical wires used
ur
for connecting components.It cannot store values by itself;
it reflects the driven value.Cannot be assigned inside
procedural blocks (always, initial).
CODE EXAMPLE:
G
wire a;
assign a = b &c; // continuous assignment driving wire 'a'
- Reg:
sic

Represents a variable that can hold a value and be assigned


inside procedural blocks.
CODE EXAMPLE:
reg q;
always @(posedge clk)
A

q <= d; // procedural assignment to reg 'q'


- Logic:
A data type that can be used as either a net or a variable,
combining capabilities of both wire and reg. It can be
driven by procedural assignments or continuous assignments.
Simplifies coding by eliminating confusion between wire and
reg types.
CODE EXAMPLE:
logic x;
always_comb
x = a &b; // procedural assignment allowed
// logic can also be used for outputs of modules
76. What is the difference between bit[7:0] sig_1; and byte
sig_2;
- bit[7:0] sig_1 is 8-bit unsigned vector while byte sig_2
is8 bit signed integer.
- bit[7:0] sig_1 can be made signed by declaring bit signed
[7:0].
- Part-select is allowed in bit[7:0] sig_1 while it is not
allowed in byte sig_2.
- bit[7:0] sig_1 is used for bit-level manipulation is needed
while byte sig_2 is used when one need a signed integer
with 8-bit width for arithmetic or memory-mapped purposes.

77. What is the difference between


1.logic data_1;

u
2.var logic data_2;
3.wire logic data_3j;
4.bit data_4;
5.var bit data_5;
- logic data_1:
ur
Here data_1 can be assigned in procedural blocks (always,
G
initial) or continuous
assignments. It is of 4-state type.
- var logic data_2:
sic

Explicit variable declaration. Usage is same as logic


data_1.
- wire logic data_3:
Net with logic data type. Assigned in continuous assignments
only.
A

- bit data_4:
Variable of 1-bit data type. It is 0f 2 – state type having
default value of 0.
- var bit data_5:
Explicit 1-bit variable declaration. Usage is same as bit
data_4

78. What is the difference between bit and logic data type?
- Bit is a 2-state SystemVerilog data type having user-defined
vector size while logic is a 4-state SystemVerilog data type
also having user-defined vector size.
- Default value for bit data type is 0 , logic data type have
default value X(unknown state).
- Bit data type simulates faster than logic data type in
SystemVerilog.
- Ex. bit a; //here a can hold 0 or 1 values
logic a; //here a can hold 0,1,X or Z values

79. What is coverage driven verification?


- Coverage Driven Verification (CDV) is a modern, systematic
approach used in hardware verification to ensure that a
design has been thoroughly tested.coverage is used as a
guide for directing verification resources by identifying
tested and untested portions of the design.
- Types of Coverage:
 Code Coverage: Automatically extracted from the RTL

u
code (e.g., lines, branches executed).
 Functional Coverage:Measures how much of the design

-
ur
specification and scenarios have been exercised.
CDV improves verification efficiency by providing feedback
to focus test generation, uncover corner cases, and reduce
G
redundant testing, thereby increasing confidence in design
quality.
- SystemVerilog offers powerful language features to easily
specify and control functional coverage, enabling automated,
sic

detailed coverage collection and analysis.

80. What are the type of coverages available in SV?


A

- type of coverages available in SV:


Code Coverage:
 Measures execution of RTL code during simulation.
 Generated automatically by the simulator/tool (e.g.,
VCS).
 Does not verify correctness of output—only that the
code was exercised.
Functional Coverage:
 Measures whether the intended functionality of the
design has been tested.
 Created by verification engineers using SystemVerilog
constructs (covergroup, coverpoint, etc.).
 Checks if correct output is produced for various
functional scenarios.
 Requires mapping testplan features to coverage models.

81. What is cross coverage?


- Cross coverage measures the combination of values between
two or more variables (or coverpoints).It ensures that all
meaningful pairs or tuples of values are exercised in
simulation.
- Cross coverage helps identify missing interactions or corner
cases.
- CODE EXAMPLE:
covergroup cg;
coverpointmode; // e.g., mode = 0,1,2
coverpointenable; // e.g., enable = 0,1

u
cross mode, enable; // Cross coverage of mode and
enable

82.
endgroup ur
Describe the difference between Code Coverage and
G
Functional Coverage Which is more important and Why we need
them.
sic

Aspect Code Coverage Functional


Coverage
Definition Measures how much of the Measures how much
RTL code is executed of the design
functionality is
tested
A

Generated Simulator/tool (e.g., Verification


by VCS, ModelSim) engineer (user-
defined)
Focus Structural coverage Functional intent
(lines, branches, and test plan
toggles) goals
Checks No – Only checks if code Yes – Ensures
correctnes was executed features produce
s expected results
Types FCBEST – FSM, FCBEST – FSM,
Conditional, Branch, Conditional,
Expression, Statements, Branch,
Toggle Expression,
Statements, Toggle
- Functional Coverage is more important because:
 It ensures the specification is verified.
 It checks if all use-cases, corner cases, and
scenarios are exercised.
 One can have 100% code coverage and still miss bugs
if functional intent isn't tested.
- Code Coverage is needed to identify untested parts of RTL
code and useful for checking that all logic paths are
exercised.

83. What are the ways to avoid race condition between


testbench and RTL using System Verilog?
- Methods to avoid race condition between testbench and RTL
using System Verilog :

u
 Program block:
Executes in the reactive region of simulation (after
RTL).Ensures
ur
Testbench never races with RTL.

 Clocking block:
G
Provides synchronized sampling and driving of signals based
on a clock.
Has input, output, and inout directions, and optional skew
sic

to sample after or before edge.

84. Explain Event regions in SV.


- In SystemVerilog, event regions define the order of
simulation execution within a single simulation time
A

step.This allows properties and checkers to sample data when


the design under test is in a stable state.
- All scheduled events at a specific time define a time
slot.Simulation proceeds by executing and removing all
events in the current simulation time slot before moving on
to the next non-empty time slot, in time order. This
procedure guarantees that the simulator never goes backwards
in time.A time slot is divided into a set of ordered
regions:
 Preponed
 Pre-active
 Active
 Inactive
 Pre-NBA
 NBA
 Post-NBA
 Observed
 Post-observed
 Reactive
 Postpone
- The purpose of dividing a time slot into these ordered
regions is to provide predictable interactions between the
design and testbench code.

85. What are the main regions inside a SystemVerilog


simulation time step
- the main regions inside a SystemVerilog simulation time
step:

u
 Preponed
 Pre-active
 Active
 Inactive
 Pre-NBA
ur
G
 NBA
 Post-NBA
 Observed
sic

 Post-observed
 Reactive
 Postpone
A

86. What is an “event” in SystemVerilog? How do we trigger an


“event” in System Verilog?
- An event in system verilog is a static object that can be
triggered(->) by one process and can be waited on
(@event_name) by another process
- SystemVerilog events enhance Verilog events by maintaining
their triggered state throughout the entire time-step and
acting as handles to synchronization queues, allowing
assignment, comparison, and task passing.
- Named events are triggered via the -> operator.Nonblocking
events are triggered using the ->> operator.
- CODE EXAMPLE:
module trigger;
event my_event;

initial begin
#5;
$display("Triggering event at time %0t", $time);
->my_event;
end
endmodule
- This code defines and triggers my_event after 5 time units.

87. Explain the difference between the edge-sensitive “@”


event control and the level-sensitive “wait” event control.
- @ event control:
 The @ event; statement blocks the process until the

u
event is triggered (->) after the @ has been executed.
 If -> happens before @, the event is missed, and the

- CODE EXAMPLE:
event done;
ur
process stays blocked.
G
initial begin
// This will miss the trigger if ->done executes first
@(done);
sic

$display("Event caught");
end

initial begin
->done; // If this executes before @(done), the event is
A

missed
end
- The waiting process never unblocks, because it started after
the trigger.
- Wait event control:
wait(event.triggered), allowing the process to always
unblock if the event was triggered in the same timestep—even
if wait executes after the ->. It prevents missed events due
to timing/race conditions.
- CODE EXAMPLE:
event blast;

initial fork
-> blast; // Triggers event
wait (blast.triggered); // Will unblock, even if this
executes after ->blast
join

88. What is the dfference between always_combo and


always@(*)?
- The SystemVerilogalways_comb procedure differs from the
Verilog-2001 always @* in the following ways:
 always_comb automatically executes once at time zero,
whereas always @* waits until a change occurs on a
signal in the inferred sensitivity list.
 always_comb is sensitive to changes within the
contents of a function, whereas always @* is only

u
sensi tive to changes to the arguments of a function.
 Variables on the left-hand side of assignments within
ur
an always_comb procedure, including variables from the
contents of a called function, shall not be written to
by any other processes, whereas always @* permits
multiple processes to write to the same variable.
G
 Statements in an always_comb shall not include those
that block, have blocking timing or event controls, or
fork...join statements.
sic

 Software tools can perform additional checks to warn


if the behavior within an always_comb procedure does
not represent combinational logic, such as if latched
behavior can be inferred.
A

89. Explain how the timescale unit and precision are taken
when a module does not have any t imescalerdeclaration in RTL.
- When a Verilog/SystemVerilog module doesn't explicitly
define a timescale, it inherits the timescale from the
enclosing module or the default tool-specific timescale. If
a module is nested, it inherits from the closest enclosing
module's timescale. If a module is not nested and doesn't
have a timescale declaration, it defaults to the tool-
specific default, which is often 1 ns / 1 ps.

90. What data structure you used to build scoreboard?


- Common Data Structures Used in a Scoreboard:
 Queues :Useful for maintaining order between expected
and actual transactions.Allows FIFO-style checking.
 Associative Arrays:Used when checking data based on a
key (e.g., address or ID). Good for out-of-order
transactions.
 Dynamic Arrays :If expected transactions are known
beforehand , a dynamic array is used.
- CODE EXAMPLE:
// Use of Queue in Scoreboard:
class scoreboard;
mailbox #(transaction) exp_mb, act_mb;
transaction exp, act;
function void compare();
forever begin

u
exp_mb.get(exp);
act_mb.get(act);
ur
if (!exp.compare(act))
$error("Mismatch: expected = %0p, actual = %0p",
exp, act);
else
G
$display("Match: %0p", act);
end
endfunction
sic

endclass

91. How parallel case and full cases problems are avoided in
SV?
A

- SystemVerilog provides the unique and priority keywords to


catch these problems at compile or runtime.
 Parallel Case Problem :Occurs when multiple case items
can match simultaneously, leading to ambiguity.
Solution: unique.
Ensures only one case item matches. Gives a warning if
more than one item matches.
CODE EXAMPLE:
bit [1:0] sel;

unique case(sel)
2'b00: $display("Option A");
2'b00: $display("Option B"); // Warning: multiple
matches
endcase

 Full Case Problem :Occurs when no case item matches


the input, possibly leading to latch inference.
Solution: unique or priority
Warns if no match is found and there's no default.
CODE EXAMPLE:
bit [1:0] mode;

priority case(mode)
2'b00: $display("IDLE");
2'b01: $display("RUN");
endcase // Warning: not full if mode = 2'b10 or 2'b11

u
92.
“casez” in System Verilog?
- case :
ur
What is the difference between “case”, “casex” and

 Strict bit-by-bit comparison.


G
 Does not ignore x or z values.
 Best for synthesizable, safe RTL.
 CODE EXAMPLE:
sic

case(sel)
2'b00: y = a;
2'b01: y = b;
default: y = d; // If sel = 2'bx1, none of the cases
match — goes to default.
A

endcase
- casex :
 Treats both x, z, and ? in both expression and case
items as wildcards.
 CODE EXAMPLE:
casex(sel)
4'b1x0z: action();
endcase
// Here, x and z are wild — even sel = 4'b1000
would match.

- casez :
 treats z and ? as wildcards (i.e., don't care).
 CODE EXAMPLE:
casez(opcode)
4'b1???: action1(); // matches any value starting
with 1
4'b01??: action2();
endcase
// Only z and ? in case items are wildcards — x is
still treated as-is in expressions

93. How SV is more random stable then Verilog?


- SystemVerilog is more random-stable than Verilog primarily
because it includes advanced features for constrained
randomization and object-oriented mechanisms that provide
better control and repeatability.

u
94. What is the need of alias in SV?
- ur
In SystemVerilog, the alias keyword is used to create
bidirectional aliases between two or more nets or variables,
so that all names refer to the same physical signal. This
ensures that any change to one alias reflects immediately in
G
the others.
- CODE EXAMPLE:
logic a, b;
sic

alias a = b;
This meansa and b are now two names for the same
wire.Changing a changes b, and vice versa.

95. What is streaming operator and what is its use?


A

- A streaming operator (<< or >>) is used in SystemVerilog to


pack or unpack bit-streams in a specified bit-order (left-
to-right or right-to-left). It is useful for serializing or
deserializing complex data structures, especially when order
and alignment matter (e.g., protocol handling).
- Use cases:
Packing: Convert variables into a packed bit-stream.
Unpacking: Extract values from a bit-stream into individual
variables.
Useful in data serialization, protocol conversion,
testbenches.
- CODE EXAMPLE:
int a = 8'hAA, b = 8'hBB;
bit [15:0] y;

// Packing a and b into y: a goes to MSB, b to LSB


y = { <<8 {a, b} }; // y = 16'hAABB
// Unpacking y into a and b (reverse order)
{ <<8 {a, b} } = y; // a = 8'hAA, b = 8'hBB

96. Write a clock generator without using always block?


- One can write a clock generator without using an always
block by using a forever loop inside an initial block.
- CODE EXAMPLE:
module clk_gen(output logic clk);

u
initial begin
clk = 0;

end
ur
forever #5 clk = ~clk; // Toggles every 5 time units
G
endmodule
sic

97. What is a DPI call?


- Direct Programming Interface (DPI) is an interface between
SystemVerilog and a foreign programming language. It
consists of two separate layers: the SystemVerilog layer and
A

a foreign language layer. Both sides of DPI are fully


isolated.A DPI call refers to calling a foreign language
function from SystemVerilog or vice versa.

98. What are the advantages of SystemVerilog DPI?


- Advantages of SystemVerilog DPI:
 Efficient & Lightweight – No simulation overhead;
faster than PLI/VPI.
 Reuses Existing C/C++ Code – Easily integrates proven
software libraries.
 Simple Syntax – Imported functions/tasks behave like
native SV code.
 Direct Data Exchange – Supports input, output, and
inout arguments.
 Bidirectional Communication – SV can call C (import)
and C can call SV (export)

99. What is the difference between “DPI import” and “DPI


export”?
- DPI import:
 Call a C function from SystemVerilog.
 CODE EXAMPLE:
import "DPI-C" function int add(int a, int b);
...
int result = add(2, 3); // DPI call to C function
- DPI export:

u
 Call a SystemVerilog task/function from C.
 CODE EXAMPLE:

100. What is bin?


ur
export "DPI-C" function void sv_func();
G
- A bin is a named bucket that counts how many times a
specific value or range of values occurs for a coverage
point.
sic

- Helps determine if all required functional scenarios or


values of a signal were exercised during simulation.
- CODE EXAMPLE:
covergroup cg;
coverpoint opcode {
A

bins add_op = {4'b0000}; // Single value bin


bins logic_ops = {[4'b0010:4'b0100]}; // Range bin
}
endgroup

101. What is layered architecture?


- Layered architecture in SystemVerilog verification
(especially in UVM and modular testbenches) refers to
organizing the testbench into multiple abstraction layers,
each with a distinct role, making the environment scalable,
reusable, and maintainable.
- Layers in Layered Architecture:
 Test Layer
 Environment Layer
 Agent Layer
 Sequence Layer
 Transaction Layer
- Layered architecture ensures code reusability, Modularity
and Scalability.

102. What are the simulation phases in your verification


environment?
- In a SystemVerilog or UVM-based verification environment,
simulation typically progresses through structured
simulation phases. These phases help manage the lifecycle of
a test and control execution order across all components.
Here are the key phases:

u
 build_phase
 connect_phase
ur
 end_of_elaboration_phase
 start_of_simulation_phase
 run_phase
G
 extract_phase
 check_phase
 report_phase
sic

 final_phase

103. What is the difference between $display, $write, $monitor


and $strobe in SystemVerilog?
A

System Description
Task
$display Display strings, variables and expressions
immediately and append newline at the end of
the message.
$write Display strings, variables and expressions
without appending the newline at the end of
the message.
$monitor Monitor signal values upon its changes and
display
$strobe Display strings, variables and expressions at
the end of the current time slot.

- CODE EXAMPLE:
module system_tasks_demo;
reg [3:0] a = 4'd5;
reg [3:0] b = 4'd10;

initial begin
$display("DISPLAY: a=%0d, b=%0d", a, b);
$write("WRITE: a=%0d, b=%0d\n", a, b);
$strobe("STROBE: a=%0d, b=%0d", a, b);
$monitor("MONITOR: a=%0d, b=%0d", a, b);

#5 a = 7;
#5 b = 12;
#5 a = 3;
end
endmodule

u
- SIMULATION OUTPUT:
Time 0:
DISPLAY: a=5, b=10
WRITE: a=5, b=10
(printed immediately
ur
(After all statements at time 0 complete)
G
STROBE: a=5, b=10 ← Printed at end of time 0
(Then due to $monitor)
Time 5: MONITOR: a=7, b=10 ← printed when a changes
sic

Time 10: MONITOR: a=7, b=12 ← printed when b changes


Time 15: MONITOR: a=3, b=12 ← printed when a changes

104. What are system tasks and functions? Give some example of
A

system tasks and functions with their purpose.


- System Tasks arespecial built-in procedures that perform
actions but do not return values while System Functions
arespecial built-in functions that return a value and are
typically used in expressions.
- They are identified by the prefix $.
- EXAMPLES OF SYSTEM TASKS:
$display :Prints a line to the console with a newline
$write :Prints text without a newline
$monitor :Continuously monitors variable changes
$strobe :Prints after all events in a time step
$finish : Ends the simulation
$stop :Pauses simulation and enters interactive mode
- EXAMPLES OF SYSTEM FUNCTIONS:
$time :Returns current simulation time
$random :Returns a pseudo-random number
$bits(expr) :Returns number of bits needed to represent expr
$clog2(val) :Returns ceiling log base 2 of a value
$size(array) :Returns the size of an array

u
ur
G
sic
A

You might also like