0% found this document useful (0 votes)
23 views47 pages

SV Interview Questions

SystemVerilog introduces various array types, including fixed, dynamic, and associative arrays, alongside features like classes, inheritance, and randomization. It enhances Verilog with advanced design and verification capabilities, making it suitable for complex verification environments. Key concepts include assertions, mailboxes, semaphores, and the Configuration Database, which facilitate communication and resource management in testbenches.

Uploaded by

siddhu4293
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)
23 views47 pages

SV Interview Questions

SystemVerilog introduces various array types, including fixed, dynamic, and associative arrays, alongside features like classes, inheritance, and randomization. It enhances Verilog with advanced design and verification capabilities, making it suitable for complex verification environments. Key concepts include assertions, mailboxes, semaphores, and the Configuration Database, which facilitate communication and resource management in testbenches.

Uploaded by

siddhu4293
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

SystemVerilog provides several kinds of arrays:

SystemVerilog Interview Q&A 1. – size known at compile time.

logic [7:0] byte_array [0:15]; // 16 elements


Below are concise, interview‑oriented answers for the given SystemVerilog
questions. 2. – size decided at run time, can be resized using
new[size].

1. What are the features of SystemVerilog (SV)? int dyn_array[];


dyn_array = new[10];

SystemVerilog is a superset of Verilog that adds powerful design and 3. – indexed by non‑integer or sparse indices
verification features: (e.g. int, string), useful for look‑up tables.

● – 2‑state and 4‑state types (bit, logic, int assoc_array[string];


byte, int, enum, struct, union, typedef, etc.). assoc_array["ID_1"] = 10;

● – class, inheritance, 4. –
polymorphism, virtual methods, dynamic objects.

● – rand / randc variables,


o Packed arrays are contiguous bits and support bit‑wise
constraint blocks, std::randomize().
operations (logic [31:0]).
o Unpacked arrays are collections of elements (logic
● – immediate and concurrent assertions, [7:0] mem [0:255];).
property/sequence constructs for protocol checking.

● Queues
– covergroup, coverpoint, cross to measure
stimulus quality. ● A is a variable‑size, ordered collection that grows and
● – dynamic arrays, associative arrays, queues, shrinks dynamically.
packed/unpacked arrays.
● Declared using $ as index: data_type queue_name[$];
● – group related signals and protocol logic
together, simplify connections.
● Supports push/pop operations at front/back:
● – inter‑process communication and
synchronization between processes.
int q[$];
● – bit‑level modeling. q.push_back(10);
● – connect with C/C++ or q.push_front(5);
int x = q.pop_front(); // x = 5
other languages. int y = q.pop_back(); // y = 10

These features make SV suitable for building complex, reusable, and Queues are very useful for modeling FIFOs and transaction lists.
constrained‑random verification environments.

4. What is inheritance?
2. What is logic data type?
● is an OOP concept where a new class (child/derived
● logic is a data type in SystemVerilog that can take class) is built from an existing class (base/parent class).
values 0, 1, X, Z. ● The child class and the properties and methods
of the base class.
● It is used to replace reg and wire in RTL and testbench code.
Example:
● Unlike reg, logic can be driven by and
(but not by multiple drivers in the same class base_packet;
scope). rand bit [7:0] addr;
rand bit [7:0] data;
function void display();
Example: $display("BASE: addr=%0h data=%0h", addr, data);
endfunction
logic clk; endclass
logic [7:0] data;
class extended_packet extends base_packet;
assign clk = tb_clk; rand bit parity;
function void display();
always_ff @(posedge clk) begin [Link]();
data <= data + 1; $display("EXT: parity=%0b", parity);
end endfunction
endclass

Here extended_packet inherits addr, data, and display() from base_packet


3. Explain arrays and queues. and adds parity plus its own behavior.

Arrays

1
5. What are constraints? end
end
endmodule
● define rules/relationships that a random variable
must satisfy during randomization.
This prints five different random alphabetic strings of length 5.
● Declared inside a class using the constraint keyword.

● Used with rand / randc variables and solved by the


SystemVerilog constraint solver. 8. For a signal A to be low for 4 clock cycles, write
Example:
assertion code.
class packet; One simple interpretation: , check that A stays low
rand bit [7:0] addr; continuously for 4 cycles.
rand bit [7:0] data;
property A_low_4_cycles;
constraint c_addr_range { addr inside {[8'h10:8'h1F]}; } @(posedge clk) !A[*4];
constraint c_data_non_zero { data != 8'h00; } endproperty
endclass
A_LOW_4: assert property (A_low_4_cycles)
When [Link]() is called, addr will always be in 0x10–0x1F and data else $error("A was not low for 4 consecutive cycles");
will never be 0.
Another interpretation: Whenever we start checking, once A goes low it
must remain low for 4 cycles:

property A_goes_low_and_stays_low_4;
6. What are the types of assertions? @(posedge clk) $fell(A) |-> (!A[*4]);
endproperty
SystemVerilog supports two main types of assertions:
assert property (A_goes_low_and_stays_low_4);

1.
Mention whichever matches the interviewer’s exact requirement.
o Checked inside procedural code.
o Typically used for single‑cycle checks or sanity
checks.
assert (a <= b) else $error("a is greater than b"); 9. Key differences between SystemVerilog and
Verilog.
2.
● : SystemVerilog = Verilog + advanced design +
o Described using property / sequence and evaluated
verification features.
over on a clock.
o Used to verify temporal relationships and protocols. ● : SystemVerilog adds logic, bit, byte, enum, struct,
union, string, new array types, etc.
property req_gnt;
@(posedge clk) req |-> ##1 gnt; ● : Verilog has no classes; SystemVerilog supports
endproperty classes, inheritance, polymorphism.
assert property (req_gnt);
● : Only in SystemVerilog.
(You may also mention cover property and assume property in formal ● : SVA and functional coverage are
verification context.) SystemVerilog features, not in Verilog.
● : Only in SystemVerilog.
● : SystemVerilog is the base for
UVM/OVM/VMM methodologies; Verilog testbenches are
7. Generate random string alphabet five times. typically directed and procedural.

Example code to generate a 5‑character random alphabetic string, 5 times: So, SystemVerilog is mainly used for and modern
class rand_string;
RTL coding, while Verilog is the older subset.
rand string s;

// Length of string = 5
constraint c_len { [Link]() == 5; }
10. What are the various data types available in
// Each character is an alphabet (a–z or A–Z) SystemVerilog? Give examples.
constraint c_alpha {
1. Net and variable types
foreach (s[i]) s[i] inside { ["a":"z"], ["A":"Z"] };
}
endclass
● logic (4‑state), bit (2‑state), wire, tri, etc.
module tb;
rand_string rs = new();
int i; logic [7:0] data;
bit [3:0] status;
initial begin
2. Integer types
repeat (5) begin
if (![Link]())
$error("Randomization failed");
else ● byte (8‑bit), shortint (16‑bit), int (32‑bit), longint (64‑bit),
$display("Random string %0d = %s", i, rs.s);
signed/unsigned.
i++;

2
int unsigned count; Mailbox
longint signed big_num;
● A is a built‑in class used for between
parallel processes.
3. Real‑number types
● It acts like a queue/FIFO of objects.
● real, shortreal, realtime. ● Key methods: put(), get(), peek(), try_get(), etc.
mailbox mbx = new();
4. User‑defined types
// Producer
● enum, struct, union, typedef. ```systemverilog typedef enum [Link](pkt);
{IDLE, READ, WRITE} state_t; state_t state;
// Consumer
[Link](pkt_rcv);
typedef struct packed { bit [7:0] addr; bit [7:0] data; } pkt_t;

pkt_t p1; ``` Semaphore


● A is used for .
5. Strings and events ● It controls access to a limited number of resources using tokens.

● string, event, chandle, virtual interface. ● Key methods: get(n), put(n), try_get(n).
semaphore sem = new(1); // 1 token -> mutex

string s = "Hello"; // Process 1


event e; [Link](1); // lock
// critical section
6. Array types [Link](1); // unlock

● Fixed arrays, dynamic arrays, associative arrays, queues.


Difference
These rich data types make models more expressive and easier to verify. ● Mailbox transfers ; semaphore only controls ,
no data transfer.
● Mailbox is for ; semaphore is for .

11. What is an interface in SystemVerilog, and


how is it used? 13. What is factory registration in SystemVerilog
● An groups related signals and protocol logic in one (UVM), and when is it used?
block.
● It simplifies connections between DUT and testbench and avoids In UVM (which is built on SystemVerilog), allows
long port lists. components and objects to be created via the uvm_factory instead of direct
new() calls.
● It can also contain tasks, functions, clocking blocks, and
assertions.
● We register a class with the factory using macros:
Example: o uvm_component_utils(class_name) for components.

interface bus_if (input logic clk); o uvm_object_utils(class_name) for objects/transactions.


logic req, gnt;
logic [7:0] addr, data; Example:
// Clocking block for testbench class my_agent extends uvm_agent;
clocking cb @(posedge clk); `uvm_component_utils(my_agent)
output req, addr, data;
input gnt; function new(string name, uvm_component parent);
endclocking [Link](name, parent);
endfunction
// Modport for DUT endclass
modport DUT (input req, addr, data, clk,
output gnt);
endinterface ● With factory registration, we can use type_id::create():
// DUT side
module dut (bus_if.DUT bus); my_agent agt_h;
// Use [Link], [Link], etc. agt_h = my_agent::type_id::create("agt_h", this);
endmodule

// Testbench When is it used?


module tb;
logic clk; ● To enable (global or instance‑based) without
bus_if bus (clk); changing the original code.
dut d1 (bus);
endmodule
● Useful for swapping implementations (e.g., different sequences,
drivers, agents) for different tests.

12. What are mailboxes and semaphores in 14. What is the Configuration Database (Config
SystemVerilog? How do they differ? DB) in SystemVerilog/UVM?
3

uvm_analysis_imp#(my_txn, my_scoreboard) imp;
In UVM, the (uvm_config_db) is a global,
hierarchical key‑value store. function new(string name, uvm_component parent);
[Link](name, parent);
● It is used to from imp = new("imp", this);
higher‑level components (like test/env) to lower‑level endfunction
components (like agents, drivers, monitors) without tight
function void write(my_txn t);
coupling.
// compare / check transaction
endfunction
Example: endclass

// In the test or env


TLM ports therefore provide a high‑level, flexible way to move transactions
my_cfg cfg = new();
uvm_config_db#(my_cfg)::set(this, "*.agent*", "cfg", cfg); around the UVM environment without directly connecting signals.

// In the agent's build_phase


if (!uvm_config_db#(my_cfg)::get(this, "", "cfg", cfg_h))
`uvm_fatal("CFG", "Config not found")
16. What is the difference between code
Benefits: - Promotes and . - Avoids passing many coverage and functional coverage in
arguments through constructors. - Supports wildcarded hierarchical paths SystemVerilog?
for flexible distribution of configuration.
- Measures which parts of the implementation code were
executed during simulation. - Types: statement, branch, condition,
expression, toggle, FSM coverage, etc. - Answers: “Did my tests execute
15. What are TLM (Transaction Level Modeling) this line/branch/state?” - Generated automatically by the simulator from
ports in SystemVerilog/UVM? RTL/testbench code.

In UVM, are used for communication between components at - Measures whether all
the instead of individual signals. have been exercised. - Defined by the verification engineer using
covergroup, coverpoint, and cross. - Answers: “Did I generate all intended
Main ideas combinations/transactions?” - Independent of implementation structure.

● Components pass through TLM In short: checks implementation execution;


ports, exports, and imp ports. checks verification plan completeness.
● This decouples components and makes the environment more
reusable.

Common UVM TLM port types 17. What are the differences between struct and
1. union in SystemVerilog?

o uvm_blocking_put_port, uvm_blocking_put_imp – send - All members exist with . - Size =


transactions (e.g., sequencer → driver). sum of the sizes of all members (for packed struct, after alignment rules). -
o uvm_blocking_get_port, uvm_blocking_get_imp – Reading a field does affect other fields.
receive transactions.
Example:
2.
o uvm_tlm_analysis_fifo, uvm_tlm_fifo – queue‑based
typedef struct packed {
bit [3:0] a;
communication. bit [3:0] b;
3. } my_struct_t; // total 8 bits

o uvm_analysis_port, uvm_analysis_imp, - All members (overlap in memory). - Size =


uvm_analysis_export – broadcast transactions (e.g., size of the member. - Writing one field the representation
monitor → scoreboard, coverage collector). of other fields.

Example (monitor to scoreboard using analysis port) Example:


class my_monitor extends uvm_monitor;
`uvm_component_utils(my_monitor) typedef union packed {
bit [7:0] byte_val;
uvm_analysis_port#(my_txn) ap; bit [3:0] nibbles[2];
} my_union_t; // total 8 bits
function new(string name, uvm_component parent);
[Link](name, parent); - Memory: struct = separate; union = shared. - Usage:
ap = new("ap", this); struct is for grouping related fields; union is for viewing same bits in
endfunction
different formats (type punning).
// After sampling a transaction
task send_txn(my_txn t);
[Link](t);
endtask
endclass
18. What is the difference between reg and wire in
SystemVerilog?
class my_scoreboard extends uvm_component;
`uvm_component_utils(my_scoreboard)
Although logic is preferred in SystemVerilog, the older Verilog types still
exist:
4
wire - Represents a physical net. - Must be driven by Here “constraint logic” usually refers to the of
(assign) or module ports. - Cannot be assigned in always / SystemVerilog:
initial blocks.
The user writes on rand / randc variables.
wire y;
assign y = a & b;
When [Link]() or std::randomize() is called, the
simulator builds a from these
reg - Represents a variable that holds its value until updated. - Assigned in constraints.
(always, initial). - Not a “register” in hardware by itself; A constraint solver (often based on SAT/SMT algorithms) finds
synthesis determines that. values that satisfy simultaneously.
If a solution exists, random values are assigned to the variables
reg y;
always @(posedge clk) y <= a & b; while respecting all constraints; otherwise randomization fails.

In pure SystemVerilog RTL/testbench code, we generally prefer logic The constraint logic supports ranges, arithmetic relations, conditional
because it can be used in both continuous and procedural assignments expressions, inside, dist, unique, etc., letting you describe complex input
(single driver per signal). spaces at a high level.

19. What are the constraints in SystemVerilog? 21. How do you write a constraint to generate a
Can you explain the different types of multiple of 5?
constraints? Example: generate a random integer x that is a multiple of 5 in the range
0–95.
A specifies rules that randomized variables must satisfy. They
are declared in a class with the constraint keyword and solved class mult_of_5;
automatically by the SystemVerilog constraint solver. rand int x;

constraint c_multiple_5 {
Types / styles of constraints: x inside {[0:95]};
x % 5 == 0; // x is a multiple of 5
● – limit a variable to a value range. }
endclass
constraint c_range { addr inside {[16'h1000:16'h1FFF]}; }
Another way using an intermediate variable:
● – specify relationships
class mult_of_5_alt;
between variables. rand int k;
int x;
constraint c_rel { len > 0; len <= 256; }
constraint c_k_range { k inside {[0:19]}; }
constraint c_expr { end_addr == start_addr + len; }
function void post_randomize();
● – use inside with sets. x = 5 * k;
endfunction
endclass
constraint c_set { opcode inside {READ, WRITE, IDLE}; }

● (dist) – control probability of values.


22. How do you write a constraint for a bit signal
constraint c_dist { that is high for 3 cycles and low for 2 cycles out of
}
burst_len dist {1 := 40, [2:8] := 60};
5?
● – ensure variables have different values. Assume we have a 5‑bit vector representing 5 consecutive clock cycles of
a signal sig. We want pattern 11100 (3 high, then 2 low).
constraint c_unique { unique {id0, id1, id2}; }
class duty_3_2;
rand bit [4:0] pattern; // pattern[4] = cycle 4, pattern[0] = cycle
● – constraints that apply only 0
when a condition is true.
constraint c_3_high_2_low {
pattern == 5'b11100; // exactly 3 highs followed by 2 lows
constraint c_imp { (opcode == WRITE) -> (wdata != 0); }
}
endclass
● (in advanced usage)
If we only care that the pattern has any 3 ones and 2 zeros (order not
o Hard constraints: default; must be satisfied. important):
o Soft constraints: may be overridden/relaxed by later
class duty_3_2_any_order;
constraints (soft keyword). rand bit [4:0] pattern;

constraint c_count_3_ones {
[Link]() with (int'(item)) == 3; // exactly three 1s
20. What is a constraint logic, and how does it }
work? endclass

5
In a real testbench, time‑based behavior is more often checked with o Bins in a cross of two or more coverpoints,
, but this shows the idea using constraints. representing combinations.

o Values/ranges to be ignored in coverage calculations.
23. Can you write a constraint to generate ignore_bins reserved = {4'hF};

numbers in descending order in a queue? ●


Example: generate a queue of 5 integers in strictly descending order. o Values/ranges that should never occur; hitting them
reports an error.
class desc_queue; illegal_bins bad = {4'hE};
rand int q[$];

constraint c_size { [Link]() == 5; }

constraint c_desc { 26. What is the start method in SystemVerilog,


foreach (q[i]) {
if (i > 0) q[i-1] > q[i]; and when is it used?
}
} One common use of start in SystemVerilog is with
endclass
.
This constraint ensures that each element is smaller than the previous one,
so the queue is strictly descending. ● A sequence can be started from procedural code using its start()
method.

● Syntax: sequence_instance.start(clock, reset, ...);


24. What is a handshaking mechanism in digital Example:
design?
sequence s1;
A is a protocol used for reliable data transfer req ##1 gnt;
endsequence
between two blocks (sender and receiver).
initial begin
Key ideas: - One side asserts a or signal when data is ready. [Link](clk); // start sequence s1 on clock 'clk'
- The other side asserts an or signal when it can end
accept the data. - A transfer occurs only when both conditions are met
(e.g., valid && ready == 1). In UVM and class‑based testbenches, start() is also widely used for
(uvm_sequence::start()) to begin stimulus generation on a
Common examples: - in asynchronous or simple sequencer. In interviews, you can mention both contexts:
synchronous interfaces. - used in AXI‑style
protocols. ● SVA sequence start() – to trigger temporal behavior from
procedural code.
Handshaking avoids data loss and ensures both sides agree on when a
transaction starts and ends. ● UVM sequence start() – to run a sequence on a given
sequencer.

25. What are the different types of bins in 27. What are weighted and non weighted codes?
SystemVerilog? Can you provide examples?
In functional coverage (covergroup), define value ranges or sets to be
This is a question rather than pure SystemVerilog.
counted. Types include:
- Each bit position has a fixed weight (value contribution).

- The numeric value is the sum of weights of bits that are 1. - Example:
o Created automatically by the tool when no explicit bins code – weights are 8,4,2,1 for a 4‑bit number. - Example:
are defined. – 4‑bit code with weights 8,4,2,1 representing decimal digits 0–9.

o User‑defined bins for specific values or ranges. - Bit positions do have simple positional weights;
the code word value is not a direct sum of bit weights. - Examples:
bins small = {[0:3]}; , , , .
bins big = {[4:15]};

In verification, these concepts help when designing encoders/decoders and



writing constraints/coverage for them.
o Create an array of bins with a pattern.
bins each_val[] = {[0:15]};

● 28. What is the difference between typedef and enum


1. Capture sequences of values over time. in SystemVerilog?
bins incr = (0 => 1 => 2);


6
typedef - Creates an alias (new name) for an existing type. - Can be used Static casting
with any data type: int, struct, union, enum, etc.
● Syntax: type'(expression) or type'(handle).
typedef int count_t;
count_t cnt; // same as 'int cnt;' ● Checked at compile time for compatibility.
bit [7:0] b;
typedef struct { int i;
int id;
byte data; i = int'(b); // cast 8 bit vector to int
} pkt_t;
pkt_t p1; state_t s;
s = state_t'(2); // cast integer 2 to enum state_t
enum - Defines an with a set of named constant values. -
Optionally, a base type and explicit encodings can be given. Dynamic casting
enum logic [1:0] {IDLE=2'b00, READ=2'b01, WRITE=2'b10} state_t;
state_t state;
● Uses $cast(dest, src); returns 1 on success, 0 on failure.
● Common for base‑to‑derived class casting.
Relationship: - enum itself defines a type; you can still alias it using typedef base_pkt b;
if desired. - typedef is generic; enum is specifically for named constant sets. read_pkt r;

b = new read_pkt();
if (!$cast(r, b))
$error("Cast failed");
29. What is polymorphism in SystemVerilog, and else
[Link]();
when do we use it?
Dynamic casting is mainly used with polymorphism when we need to
is an OOP feature where a can point to recover the specific derived type.
objects of different derived classes, and the correct overridden method is
chosen at run time (dynamic binding).

Requirements: - Inheritance (extends). - Methods declared virtual in the 31. How do you connect a monitor to a DUT
base class and overridden in derived classes.
(Design Under Test)?
Example:
In a class‑based verification environment (e.g., UVM‑style):
class base_pkt;
virtual function void display(); ● to group DUT signals.
$display("Base packet");
endfunction ● Connect the interface to the DUT in the top module.
endclass ● Pass a handle to the monitor.
class read_pkt extends base_pkt;
function void display();
Example:
$display("Read packet");
endfunction // 1) Interface\ ninterface bus_if (input logic clk);
endclass logic req, gnt;
logic [7:0] addr, data;
endinterface
class write_pkt extends base_pkt;
function void display();
$display("Write packet"); // 2) DUT and interface instantiation
endfunction module top;
endclass logic clk;
bus_if bus (clk);
base_pkt pkt;
dut u_dut (.clk(clk), .req([Link]), .gnt([Link]),
.addr([Link]), .data([Link]));
initial begin
pkt = new read_pkt();
[Link](); // prints "Read packet" // Virtual interface passed to monitor (UVM style or manual)
initial begin
monitor m = new(bus); // constructor or config_db
pkt = new write_pkt();
end
[Link](); // prints "Write packet"
endmodule
end
// 3) Monitor class (simplified)
We use polymorphism to write (e.g., drivers, scoreboards) class monitor;
that works with different specific packet/sequence types without changing virtual bus_if vif;
function new(virtual bus_if vif);
the calling code.
[Link] = vif;
endfunction

task run();
30. When do we use casting in SystemVerilog? forever begin
@(posedge [Link]);
Can you provide examples? if ([Link] && [Link])
$display("Monitor: addr=%0h data=%0h", [Link], [Link]);
end
converts one data type to another. We use it when: - Assigning endtask
between types of different sizes or signedness. - Converting between endclass
base‑class and derived‑class handles (OOP casting). - Interpreting packed
bits as different types. The monitor is : it only observes signals, converts them to
transactions, and sends them to the scoreboard/coverage.
7
o randc variables cycle through all values in their range
before repeating.
32. What is a cross functional model error in randc bit [1:0] sel; // 0,1,2,3 in random order, then
SystemVerilog? repeat

The phrase usually refers to an error detected when comparing behavior ● std::randomize()
across . In a verification context:
o Randomize variables that are not class members or
apply temporary constraints.
● We often have a and the
DUT. int x, y;
● A occurs when the combination of if (!std::randomize(x, y) with { x < y; x inside {[0:10]};
})
features or operations in the DUT does not match the expected $error("Randomization failed");
behavior of the reference model.
● This is often caught by a , which compares ●
transactions from different sources (e.g., input vs. output, o Use dist constraints to control probabilities.
multiple interfaces, or multiple models) and flags mismatches.
Together, these mechanisms let us generate complex stimulus for
Practically, you might answer in an interview: > “A cross‑functional model
coverage‑driven verification.
error is a mismatch between the DUT outputs and the reference/functional
model for a particular combination of features or coverage cross. It usually
indicates either a design bug or an error in the model or stimulus.”
35. How do you write code to generate numbers
greater than 5?
33. What are packed and unpacked arrays in
SystemVerilog? Can you give examples? Example using class‑based randomization:

class greater_than_5;
- Represent a . - Can be used in rand int x;
arithmetic and bitwise operations like a single vector. - Declared with the
range of the variable name. constraint c_gt5 { x > 5; }
endclass
logic [7:0] byte; // 8 bit packed array
logic [3:0][7:0] bus_id; // 4 elements, each 8 bits (total 32 bits module tb;
packed) initial begin
greater_than_5 obj = new();
repeat (5) begin
- Represent a collection of elements, each of which can if ([Link]())
be simple or complex types. - Declared with the range of the $display("x = %0d", obj.x); // always > 5
variable name. else
$error("Randomization failed");
logic [7:0] mem [0:255]; // 256 element unpacked array, each is end
8 bit packed end
int q [$]; // queue (unpacked) of ints endmodule

- Packed arrays are stored as a single vector → useful for Or using std::randomize() without a class:
synthesis and bit‑level modeling. - Unpacked arrays are higher‑level int x;
collections → useful for memories, FIFOs, transaction arrays. - Types can
be combined (packed dimensions first, then unpacked): logic [7:0] mem initial begin
[0:15];. repeat (5) begin
assert (std::randomize(x) with { x > 5; });
$display("x = %0d", x);
end
end
34. What are the different types of
randomization in SystemVerilog? Both approaches ensure that all generated numbers are strictly greater
than 5.

o Use rand / randc class properties and 36. Can you provide a specific example of
[Link](). constraints like 010203040506?
class pkt;
rand bit [7:0] addr; Interpretation: generate a in such as 01
endclass 02 03 04 05 06.

pkt p = new(); Example using a dynamic array of 6 elements:


[Link]();
class inc_seq;
● rand byte arr[]; // 8-bit signed; can also use bit [7:0]

o Use constraint blocks to control random values (most constraint c_size { [Link]() == 6; }
common style).
// arr = {1,2,3,4,5,6}
● randc constraint c_increasing {
foreach (arr[i]) {

8

arr[i] == i + 1; // 0->1, 1->2, ... 5->6
} [Link]() – delete all entries.
}
endclass Example:

If you want the exact 48'h010203040506: string key;


if ([Link](key)) begin
class seq_val; do begin
rand bit [47:0] val; $display("%s => %0d", key, aa[key]);
constraint c_val { val == 48'h010203040506; } end while ([Link](key));
endclass end

Or generate a pattern 0,1,0,2,0,3,0,4,0,5,0,6 in an array (like the string Queue methods


in the question):
Let int q[$]; be a queue. Common methods and operations:
class pattern_010203;
rand bit [3:0] arr[12];
[Link]() – number of elements.
constraint c_pattern { q.push_front(item) – insert at front.
foreach (arr[i]) {
if (i % 2 == 0) q.push_back(item) – insert at back.
arr[i] == 0; q.pop_front() – remove and return front element.
else
arr[i] == (i+1)/2; // 1,2,3,4,5,6 at odd indices q.pop_back() – remove and return back element.
} [Link](index, item) – insert at index.
}
endclass [Link](index) – delete element at index; [Link]() deletes
all.
q.find_index(expr), q.find_first(expr), q.find_last(expr) –
with with clause to search.
37. What are stratified queues in SystemVerilog?
Example:
A is a conceptual model used by SystemVerilog simulators
int idx[$] = q.find_index() with (item > 10);
to order events in a single simulation time unit. It is the same as the
data type queue[$].

The simulator divides each time step into multiple (strata)


to handle events in a deterministic order: 39. How do you write a function to calculate the
sum of two numbers?
● – blocking assignments, #0 delays, immediate
Simple SystemVerilog function:
assertions.
● – nonblocking assignment updates from previous function int sum_two (int a, int b);
timestep. sum_two = a + b;
endfunction
● – RHS evaluation in active,
LHS update here. Usage:
● – used by assertions,
PSL, and some verification constructs. int x = sum_two(10, 20); // x = 30

Together these form a that ensures correct ordering For synthesis‑friendly code you typically place this inside a package or
between blocking/non‑blocking assignments, signal sampling, and module.
assertion checking.

40. What is the go to reputation operator in


38. What are the inbuilt functions for associative SystemVerilog?
arrays and queues in SystemVerilog?
The question likely refers to the in SVA sequences,
Associative array methods often read as go to repetition. SystemVerilog offers several repetition
operators:
Let int aa[string]; be an associative array. Common built‑in methods:
● [*n] – exactly n repetitions.
● [Link]() – number of entries. ● [*m:n] – between m and n repetitions.
● [Link](index) – 1 if an element with the given index exists. ● [+] – one or more repetitions.
● [Link](index) – get first index in the array; returns 0 if empty. ● [*0:$] – zero or more repetitions.
● [Link](index) – get last index.
Example:
● [Link](index) – get next index after the given one.
sequence s_req_stable;
● [Link](index) – get previous index.
req[*3]; // req must stay high for 3 cycles
endsequence
● [Link](index) – delete element with key index.
9
Sometimes the ##[m:n] delay operator is also called a “go‑to repetition” ./simv -gui=verdi
because it allows variable delays:
or open saved FSDB/VCD in Verdi:
sequence s1;
req ##[1:3] gnt; // gnt 1 to 3 cycles after req verdi -ssf [Link] &
endsequence

In an interview, mention that options like +v2k, +acc, -debug_access+all, -l


logfile are commonly used depending on environment.

41. Can you write SystemVerilog code for a given


design? (You can attach the design details for
this.) 44. What is cross coverage in SystemVerilog, and
how does it differ from code and functional
Typical interview answer: - “Yes, I can translate a block diagram or truth
coverage?
table into synthesizable SystemVerilog RTL, and also write a class‑based
testbench for it. For example, for a 4‑bit up counter with synchronous reset: is a form of that tracks combinations
module up_counter #(parameter WIDTH = 4) (
of values from two or more coverpoints.
input logic clk,
input logic rst_n, Example:
input logic en,
output logic [WIDTH-1:0] count covergroup cg @(posedge clk);
); cp_addr : coverpoint addr { bins all[] = {[0:15]}; }
cp_burst: coverpoint burst_len { bins small = {[1:3]}; bins big =
always_ff @(posedge clk or negedge rst_n) begin {[4:8]}; }
if (!rst_n)
count <= '0; addr_x_burst : cross cp_addr, cp_burst;
else if (en) endgroup
count <= count + 1'b1;
end
endmodule ● addr_x_burst reports which address–burst combinations have
been seen.
I would then describe how I would write the testbench using interface,
● This helps ensure that between variables are
driver, monitor, and scoreboard. Actual code depends on the design they
adequately tested.
provide.”
- – checks which lines/branches of RTL
executed. - – checks user‑defined scenarios; cross
coverage is one specific kind of functional coverage focusing on value
42. How do you use array methods to find combinations.
numbers greater than 5 in a given array?
Given a dynamic array int a[]; you can use find, find_index, or
find_first: 45. How can you achieve 100% coverage in your
int a[] = '{1, 6, 3, 10, 8}; verification process? What does it mean if you
int greater_than_5[$];
int idx[$];
// queue of matching values
// indices of matches have 100% functional coverage but only 80%
code coverage?
// Get all values > 5
greater_than_5 = [Link]() with (item > 5);
1. Start from a derived from the
// Get indices of values > 5 spec. 2. Define (covergroups, crosses) that map to
idx = a.find_index() with (item > 5); each item in the plan. 3. Enable in the simulator. 4. Use
constrained‑random and directed tests to close coverage holes: - Analyze
foreach (idx[i]) begin
$display("a[%0d] = %0d", idx[i], a[idx[i]]); coverage reports. - Add or modify constraints and sequences. - Write
end directed tests for hard‑to‑hit scenarios. 5. Iterate until both functional and
code coverage reach targets (often 90–100%).
Array methods available: find, find_index, find_first, find_last, min, max,
sum, unique, sort, reverse, etc. - All defined functional scenarios
(coverpoints/crosses) have been hit. - However, 20% of the RTL code was
never executed: - Possibly dead/unreachable code. - Missing or incomplete
functional coverage (verification plan did not cover some behavior). -
43. What is the command used to invoke VCS and Over‑constrained stimulus not allowing some code paths.
Verdi?
In that case you must: - Review un‑covered RTL and decide if it is truly
Exact options vary, but typical basic commands are: dead code (can be waived) or if tests / coverage need to be updated.

● (Synopsys):

vcs -full64 -sverilog top_tb.sv -o simv


46. How do you write an assertion to check a
./simv clock signal?
● (debugger) from VCS simulation: Typical checks on a clock: - It toggles. - It has correct duty cycle / period. -
No glitches (no multiple edges in one cycle).
10
Example: check that clk toggles every cycle (simple 50% duty with 2‑cycle super keyword
period):
● Used inside a derived class to access methods, properties, or
property clk_toggle; constructor of the .
@(posedge clk) $fell(clk) ##1 $rose(clk);
endproperty
● Common uses:
o Call base new inside child constructor: [Link](name,
assert property (clk_toggle) parent);
else $error("Clock did not toggle correctly");
o Call base implementation of an overridden method:
More general: ensure that values on clock: [Link]();.

property clk_valid_levels;
@(posedge clk) !$isunknown(clk);
endproperty 48. What are the regions in SystemVerilog?
assert property (clk_valid_levels); Simulation is divided into ordered to control scheduling. A
simplified list:
Actual implementation depends on the clock specification (period, duty,
gating, etc.). ● – sampling for assertions.

● – evaluation of RHS of blocking assignments,


always blocks, etc.
47. What are the different processes in ● – events scheduled with #0 delays.
SystemVerilog (fork..join, fork..join_any, fork..join_none)? ● – update LHS of nonblocking
How can we achieve inheritance? What is the super assignments.
keyword? ● – evaluation of concurrent assertions
and reactive processes after NBA updates.
Parallel processes
● – for monitoring, $display in assertions, etc.,
● fork..join
after all updates.
2. Starts multiple parallel blocks and to
complete before proceeding. These regions, combined with their multiple strata, form the
.
fork
task1();
task2();
join
49. How would you design an XOR gate using a
● fork..join_any
multiplexer?
o Waits until of the parallel blocks completes,
then the others are . A 2‑input XOR can be expressed as:
fork
task1(); [ Y = A ^ B = (~A & B) | (A & ~B) ]
task2();
join_any Using a 2:1 MUX with A as select input:
// whichever finishes first ends the fork

● fork..join_none
● When A = 0, Y = B.
o Starts all blocks and ; execution ● When A = 1, Y = ~B.
continues immediately after the fork (detached
threads). SystemVerilog RTL:
fork
module xor_using_mux (
task1();
input logic A,
task2();
input logic B,
join_none
output logic Y
// both tasks run in background
);

Inheritance // 2:1 MUX: Y = (A) ? ~B : B;


assign Y = (A) ? ~B : B;
● Achieved using OOP class extension: endmodule
class base;
int id;
function void display(); This implements XOR behavior using a mux structure.
$display("Base id=%0d", id);
endfunction
endclass

class child extends base;


50. What is frequency division in digital circuits?
function void display();
[Link](); // call base version is the process of generating an output clock whose
$display("Child class"); frequency is a of the input clock frequency.
endfunction
endclass
● Commonly implemented using counters or toggle flip‑flops.

11
● A simple divide‑by‑2 uses a T‑flip‑flop or D‑flip‑flop that toggles ● Derived classes must provide implementations for pure virtual
on each clock edge: methods to be concrete.
module clk_div2 (
input logic clk_in, Syntax:
input logic rst_n,
output logic clk_out virtual class base_driver;
); virtual task drive(); // may have default body
pure virtual function void configure(); // must be implemented
always_ff @(posedge clk_in or negedge rst_n) begin endclass
if (!rst_n)
clk_out <= 1'b0; class axi_driver extends base_driver;
else function void configure();
clk_out <= ~clk_out; // toggle -> divide by 2 // implementation
end endfunction
endmodule
task drive();
For divide‑by‑N, use an N‑state counter and toggle/emit a pulse at certain // override if needed
counts. endtask
endclass

// Usage
base_driver drv; // base handle
51. What is the difference between logic and reg in axi_driver axi_drv_h = new();
drv = axi_drv_h; // polymorphism
SystemVerilog? What are the default values of
wire and reg? Virtual classes are heavily used in UVM for creating generic, reusable base
components and then extending them for specific protocols or
reg - 4‑state variable (0,1,X,Z). - Can be assigned only in configurations.
procedural blocks (always, initial). - Cannot have multiple drivers.

logic - Also a 4‑state variable; intended as a replacement


for reg. - Can be driven by or assignments (single
driver rule per scope). - Works better with strong typing and with
always_comb, always_ff.

Example:

logic a; // preferred in SV
reg b; // legacy Verilog style

- reg / logic / other 4‑state variables X in


simulation unless explicitly initialized. - wire defaults to Z
if it has no driver. If it is driven, its value is determined by the drivers.

52. What are the object oriented programming


concepts in SystemVerilog? How do virtual
classes work?
Main OOP concepts in SystemVerilog
● – blueprint for objects; can contain properties, methods,
and constraints.

● – using local, protected, and public members to


hide internal details.

● – class child extends base; allows re‑use and


extension of base behavior.

● – base‑class handles referring to derived objects


with virtual methods.
● – using classes, virtual methods, and interfaces to
model high‑level behavior.

● – created with new at runtime.

Virtual classes
● A is an that
directly.
● It may contain that have no implementation
in the base class.

12
phase.drop_objection(this);

SystemVerilog Interview Q&A – Part 2


endtask

(Misc + Constraints) How to check the bug


● Add uvm_info() messages or counters inside the suspected loop.
● Use the simulator’s / to pause and inspect call
1. Write constraint for int a, it should not stack.
generate values between 100 and 200. ● Check that sequences finish and phase.drop_objection() is
class c1; executed.
rand int a;
● Check for over‑constrained randomization causing
// a is allowed below 100 or above 200
constraint c_a_not_100_200 { while(!randomize()) loops.
!(a inside {[100:200]});
// equivalently: a < 100 || a > 200; In short: add a global timeout, instrument loops with prints/counters, and
} verify the objection is dropped.
endclass

2. 0,2,0,4,0,6,... – write constraints to generate this 4. Why do we use classes in SystemVerilog?


pattern. Classes provide features which are essential for modern
verification:
Interpretation: we want an array where the sequence is: index0=0,
index1=2, index2=0, index3=4, index4=0, index5=6, … i.e., - even indices created with new → easy to create/destroy
0,2,4,… → value 0 - odd indices 1,3,5,… → value 2,4,6,… respectively transactions.
– group data (properties) and behavior (methods)
class pattern_0_2_0_4_0_6;
rand int arr[]; together.
– reuse and extend base functionality (e.g., base
constraint c_size { [Link]() == 6; } // extend as needed
sequence, extended sequence).
constraint c_pattern { – base class handles point to different derived
foreach (arr[i]) { types; enables factories in UVM.
if (i % 2 == 0)
arr[i] == 0; // even index → 0 – rand properties and constraint
else blocks exist only in classes.
arr[i] == (i+1); // 1→2, 3→4, 5→6, ...
}
}
These features make verification environments
endclass (UVM is entirely class‑based).

You can increase [Link]() to extend the pattern.

5. What is the need of a virtual interface in


SystemVerilog?
3. Test stuck in infinite loop with objection raised
● A is a class handle to a .
– how to stop and debug?
● Classes (driver, monitor, sequences) cannot directly connect to
If a UVM test never ends, typically: - The run_phase raised an objection module ports, so they use a virtual interface to drive / sample
(phase.raise_objection(this);) but . - Or there is a DUT signals.
forever loop / fork..join_none running without an exit condition.
Example:

How to stop the simulation interface bus_if (input logic clk);


logic req, gnt;
● in the test or top: logic [7:0] addr, data;
endinterface
initial begin
class driver;
#1ms; // sim time limit
virtual bus_if vif; // virtual interface handle
`uvm_fatal("TIMEOUT", "Test timed out – possible infinite
loop")
end function new(virtual bus_if vif);
[Link] = vif;
endfunction
● Ensure every raised objection is paired with a :
task run();
forever begin
task run_phase(uvm_phase phase); @(posedge [Link]);
super.run_phase(phase); // drive signals through vif
phase.raise_objection(this); end
endtask
// your main stimulus endclass
repeat (1000) begin
// ... module top;
end logic clk;
bus_if bus (clk);

13
initial begin
8. Explain shallow copy and deep copy with
driver d = new(bus); // pass interface to class via virtual example.
handle
fork [Link](); join_none; ● – copies only the of an object; both
end variables refer to the object in memory.
endmodule
● – creates a and copies all fields so that
Virtual interfaces therefore static design world and class‑based the two objects are independent.
testbench world.
Shallow copy example
class pkt;
int addr;
6. What are semaphores? endclass

pkt p1, p2;


A is a SystemVerilog built‑in class used for
between parallel processes. initial begin
p1 = new();
[Link] = 10;
● It holds a certain number of .
● get(n) – take n tokens (blocks if not available). p2 = p1; // shallow copy (handle copy)
[Link] = 20;
● try_get(n) – attempt to take tokens without blocking.
● put(n) – return n tokens. $display("[Link] = %0d", [Link]); // prints 20 → same object
end
Example (mutex with 1 token):
Deep copy example
semaphore sem = new(1); // 1 token

// Process 1 Implement custom copy() method:


fork
begin class pkt;
[Link](1); // lock int addr;
// critical section
[Link](1); // unlock function pkt copy();
end pkt tmp = new();
begin [Link] = [Link]; // copy contents
[Link](1); return tmp;
// critical section for process 2 endfunction
[Link](1); endclass
end
join initial begin
pkt p1 = new();
[Link] = 10;
Semaphores ensure that only limited number of processes access a
shared resource (like a bus or file) at the same time. pkt p2 = [Link](); // deep copy
[Link] = 20;

$display("[Link] = %0d", [Link]); // still 10 → different objects


7. What is a mailbox? end

UVM provides copy() / clone() methods in uvm_object for deep copying.


A is a SystemVerilog built‑in class used for
between parallel processes.

● Behaves like an unbounded or bounded FIFO queue of objects.


9. Can a task be declared in a function?
● Producer calls put() to send; consumer calls get() or peek() to
receive. No. SystemVerilog syntax
does not allow nested declarations of tasks or functions inside another
Example: function.

mailbox mbx = new(); Also, a , because: - Functions must execute in


. - Tasks may contain time‑consuming statements (@, #,
// Producer
initial begin wait, fork, etc.).
packet p = new();
[Link](); However, , and a function can call another function.
[Link](p); // send packet
end

// Consumer
initial begin 10. Write tb top code.
packet rx;
[Link](rx); // wait until a packet is available
[Link]();
A typical (simplified) top‑level testbench module for a UVM‑style
end environment:

`timescale 1ns/1ps
Mailboxes are widely used (and also internally in UVM TLM FIFOs) for
synchronizing drivers, monitors, and scoreboards. import uvm_pkg::*;
`include "uvm_macros.svh"

14
end
module tb_top; endtask
endclass
// Clock & reset
logic clk; module tb_mailbox;
logic rst_n; mailbox mbx;
producer prod;
// Interface instance consumer cons;
bus_if bus (.*); // assume interface declared elsewhere with clk,
rst_n initial begin
mbx = new();
// DUT instance (example) prod = new(mbx);
dut u_dut ( cons = new(mbx);
.clk (clk),
.rst_n(rst_n), fork
.req ([Link]), [Link]();
.gnt ([Link]), [Link]();
.addr ([Link]), join
.data ([Link]) end
); endmodule

// Clock generation Here a single mailbox is shared; producer put()s packets, consumer
initial begin
clk = 0; get()s them.
forever #5 clk = ~clk;
end

// Reset generation
initial begin
12. Explain virtual class.
rst_n = 0; A is an that
#20 rst_n = 1;
end directly.

// Start UVM test It may contain (pure virtual), which have


initial begin no implementation in the base class and must be overridden in
run_test(); // or run_test("my_test"); derived classes.
end
virtual class base_driver;
virtual task drive(); // may have default body
endmodule
pure virtual function void configure(); // no body
endclass
This tb_top connects DUT, interface, clock/reset, and calls run_test() to
start the UVM test. class spi_driver extends base_driver;
function void configure();
// mandatory implementation
endfunction

11. Show mailbox connection: one class sends task drive();


// optional override
transaction, another class receives it. endtask
class packet; endclass
rand int id;
function void display(); // Usage
$display("PACKET id=%0d", id); base_driver drv; // handle of base type
endfunction spi_driver spi = new();
endclass
initial begin
class producer; drv = spi; // polymorphism
mailbox mbx; [Link]();
[Link]();
function new(mailbox mbx); end
[Link] = mbx;
endfunction Virtual classes are used to define and allow different
concrete implementations (drivers/monitors/etc.) to be plugged in using
task run();
packet p; polymorphism (heavily used in UVM).
repeat (5) begin
p = new();
assert([Link]());
$display("[PROD] sending id=%0d", [Link]);
[Link](p); // send transaction 13. Write constraint for Fibonacci series.
end
endtask Goal: generate a dynamic array fib[] such that: - fib[0] = 0 - fib[1] = 1 -
endclass
fib[i] = fib[i-1] + fib[i-2] for i >= 2
class consumer;
class fibonacci_seq;
mailbox mbx;
rand int fib[];
function new(mailbox mbx);
constraint c_size { [Link]() == 8; } // first 8 terms
[Link] = mbx;
endfunction
constraint c_fib {
fib[0] == 0;
task run();
fib[1] == 1;
packet p;
foreach (fib[i]) {
forever begin
if (i >= 2)
[Link](p); // receive transaction (blocking)
fib[i] == fib[i-1] + fib[i-2];
$display("[CONS] got id=%0d", [Link]);
15
}
} // Cross to ensure all input combos vs. outputs are observed
endclass cross_inputs_outputs : cross cp_inputs, cp_sum, cp_cout;
endgroup
This creates the sequence: 0,1,1,2,3,5,8,13.
This coverage tells us whether every possible input combination and
resulting (sum,cout) pair was exercised.

14. Constraint to generate even numbers in odd


locations and odd numbers in even locations in
17. What is 4 state data type in SV?
a dynamic array.
● 4‑state types can take values 0, 1, X, Z.
Assume index 0 = location 0 (even), index 1 = location 1 (odd), etc. - Even
index → odd value - Odd index → even value ● Examples: logic, reg, wire, integer, time, bit 2‑state
keyword (legacy types).
class even_odd_loc;
rand int data[]; ● Useful for RTL modeling where unknown (X) and high‑impedance
constraint c_size { [Link]() == 10; } (Z) values must be represented.

constraint c_pattern { Example:


foreach (data[i]) {
if (i % 2 == 0) logic [3:0] a; // 4 state
data[i] % 2 == 1; // even index → odd number
else
data[i] % 2 == 0; // odd index → even number
}
} 18. What is 2 state data type in SV?
endclass
● 2‑state types can take only 0 or 1 (no X or Z).
If your interviewer uses , state clearly: “For index 0
(location1) I treat it as odd, so I flip the condition accordingly.” ● Examples: bit, byte, shortint, int, longint, enum with 2‑state
base type.
● Helpful in testbenches for faster simulation and more
deterministic behavior.
15. Write a constraint to make diagonal elements bit [7:0] data; // 2 state
same in 2D array.
Example: 4x4 matrix m[4][4] where all diagonal elements (m[0][0],
m[1][1], m[2][2], m[3][3]) are equal. 19. Difference between packed and unpacked
class diag_same; arrays + syntax.
rand int m[4][4];
- Represent a contiguous set of bits. - Declared with range
constraint c_diag_same { of the name. - Can be used in arithmetic and bitwise operations.
foreach (m[i,j]) {
if (i == j)
logic [7:0] byte_packed; // packed
m[i][j] == m[0][0]; // all diagonal elements equal to
logic [3:0][7:0] bus_packed; // 4 elements × 8 bits (32 bit
m[0][0]
vector)
}
}
endclass - Represent separate elements stored independently. -
Declared with range of the name.
If you want a on the diagonal (e.g., 1):
logic [7:0] mem [0:15]; // unpacked, 16 elements each 8 bit
constraint c_diag_one { int da []; // dynamic array (unpacked)
foreach (m[i,j]) if (i == j) m[i][j] == 1;
} Packed first, then unpacked if both:

These constraints ensure diagonal elements are identical while logic [7:0] mem [0:15]; // packed [7:0], unpacked [0:15]
off‑diagonal elements remain unconstrained (random).

16. Explain functional coverage for full adder.


20. Difference between dynamic arrays and
For a 1‑bit full adder with inputs a,b,cin and outputs sum,cout, functional associative arrays.
coverage aims to ensure
occur. - Indexed by integer 0..size-1. - Size decided at run time;
can resize with new[size].
Example:
int da[];
covergroup cg_full_adder @(posedge clk); da = new[10];
cp_inputs : coverpoint {a,b,cin} {
bins all_comb[] = {[0:7]}; // 3 bit vector → 8 combinations
}
- Indexed by a key of arbitrary type: int, string, bit
[31:0], class handles, etc. - Size grows/shrinks automatically as keys are
cp_sum : coverpoint sum; added/deleted.
cp_cout : coverpoint cout;

16
int aa[string]; obj = null; // remove reference → eligible for garbage collection
aa["ID_1"] = 10;
To deallocate, set handles to null or reassign them to other objects.
Dynamic → good for contiguous indices; associative → good for sparse /
look‑up table style data.

25. Difference between Verilog function and


21. Difference between queue and associative SystemVerilog function.
arrays. Verilog functions: - No timing control (@, #, wait) allowed. - Execute in zero
simulation time. - Can only assign to the function name.
- Ordered collection with variable size. - Index is integer; supports
push/pop at front/back. SystemVerilog enhances functions: - Can be declared void, return by
return statement. - Can have default arguments, ref and const ref
int q[$];
q.push_back(10);
arguments. - Can be declared automatic by default. - Can be part of
q.pop_front(); classes (function methods) and be virtual.

- Indexed by arbitrary key; no inherent order. - Use Still cannot contain time‑consuming statements; that rule remains.
methods first/next/last/prev to iterate.

int aa[string];
aa["key"] = 3;
26. What is coverage?
Queue is for FIFO‑like ordered lists; associative array is for key‑value measures how thoroughly the design has been exercised by the
maps. tests.

Types: - – statements, branches, conditions, FSM, toggle. -


– user‑defined scenarios using covergroup,
22. Explain OOPs concepts in SystemVerilog. coverpoint, cross.
22. – blueprint containing properties, methods, constraints.
Coverage guides stimulus generation and indicates when verification is
23. – hide data using local/protected, expose via
complete (coverage closure).
methods.
24. – class child extends base; reuse and extend
behavior.
25. – base class handle points to derived objects; 27. SV code to generate random numbers in
virtual methods decide behavior at runtime. ascending order without using sort methods.
26. – use virtual classes/methods, interfaces to model
high‑level behavior. Use constraints between elements:

These are used heavily in UVM to create reusable verification components. class asc_rand;
rand int arr[];

constraint c_size { [Link]() == 5; }

23. Randomization concepts. // strictly ascending


constraint c_asc {
● rand / randc variables inside classes.
foreach (arr[i]) {
if (i > 0) arr[i] > arr[i-1];


}
constraint blocks specify legal value space. }
endclass
● [Link]() and std::randomize() to invoke the solver.
Randomization will generate already‑sorted numbers → no need for sort().
● randc = cyclic randomization (covers range before repeating).

● Inline constraints with with clause.

● dist for weighted distributions, inside for sets, unique for 28. What is semaphore?
uniqueness.
(Short answer – see also earlier set.)
Purpose: generate high‑quality, constrained‑random stimulus for
coverage‑driven verification. Semaphore is a built‑in class for :

semaphore sem = new(1); // 1 token


[Link](1); // lock
// critical section
24. How to deallocate memory for a class handle. [Link](1); // unlock

In SystemVerilog you class objects. Memory is freed


when anymore and the simulator’s
garbage collector reclaims it. 29. Write snippet for calling task inside function.
my_class obj = new();
...
17
Not allowed: a function since functions must not class diag_rand;
rand bit m[4][4];
consume time. Interview‑style snippet:
constraint c_only_diags {
function void f1(); foreach (m[i,j]) {
// illegal: task with timing cannot be called here if (i==j || i+j==3) begin
// my_task(); // 1 with 90%, 0 with 10%
endfunction m[i][j] dist {1 := 90, 0 := 10};
end
Correct approach: , or call task from always/initial, not }
from function. }
endclass

Other locations remain unconstrained or can be forced to 0 if needed.

30. Explain Stratified event queue in SV.


SystemVerilog simulation time is divided into to schedule
events deterministically:
33. Signal in DUT but not in interface – how to
get it into TB?
● – assertion sampling.
● Options: 1. and reconnect DUT ports. 2. If you
– evaluation of always, blocking assigns, RHS of NBA.
cannot change the existing interface, create another interface/monitor or
● – #0 events.
use hierarchical reference from TB top.
● – LHS updates of non‑blocking
assignments. Example extending interface:
● – assertions, reactive processes after NBA.
interface bus_if (input logic clk);
● – final monitoring, $display from assertions. logic req, gnt;
logic [7:0] addr, data;
Together these are called the . logic error; // new signal
endinterface

module dut (input logic clk,


input logic req,
31. How to send virtual interface data to output logic gnt,
output logic error);
DUT/Design. // ...
endmodule
Virtual interface connects class‑based TB to DUT via static interface
module top;
instance. logic clk;
bus_if bus(clk);
interface bus_if (input logic clk); dut d0 (.clk(clk), .req([Link]), .gnt([Link]),
logic req, gnt; .error([Link]));
logic [7:0] addr, data; endmodule
endinterface

module dut (bus_if bus); Monitor then uses virtual bus_if to read error.
// use [Link], [Link], ...
endmodule If interviewer forbids RTL change: use bind or hierarchical reference:
[Link] in TB.
class driver;
virtual bus_if vif;
function new(virtual bus_if vif); [Link] = vif; endfunction
task run();
forever begin
@(posedge [Link]);
34. Write chess constraints.
[Link] <= 1;
[Link] <= 8'hAA; Interpretation: 8×8 board, one queen per row/column and no two queens
end on same diagonal (like N‑Queens) – a common constraint example.
endtask
endclass class chess_queens;
rand int q_col[8]; // q_col[row] = column of queen in that row
module top; (0..7)
logic clk; bus_if bus(clk);
dut d0(bus); // each column 0..7
initial begin constraint c_range {
driver drv = new(bus); // pass interface to class foreach (q_col[i]) q_col[i] inside {[0:7]};
fork [Link](); join_none; }
end
endmodule // no two queens in same column
constraint c_unique {
unique { q_col };
}

32. Randomize 4×4 matrix where two diagonals // no two queens on same diagonal
stored with 1 and probability of 1 is 90% (ignore constraint c_diag {
foreach (q_col[i]) foreach (q_col[j])
others). if (i < j)
(q_col[i] - q_col[j]) != (i - j) &&
(q_col[i] - q_col[j]) != (j - i);
We only care about diagonal elements: (i==j) or (i+j==3); random 1 with
}
90% probability. endclass

18
class pkt; int id; endclass

pkt p1 = new();
35. Constraint to fill array size 1024 (32 bit) with pkt p2;
even number in each nibble. p2 = p1; // shallow → both handles use same allocated object

Each 4‑bit nibble must be even → LSB of each nibble = 0. pkt p3 = new();
[Link] = [Link]; // deep (manual) → separate object, separate memory
class even_nibbles;
rand bit [31:0] arr[1024];
UVM clone() allocates new memory for deep copied object.
constraint c_even_nibs {
foreach (arr[i]) begin
foreach (arr[i][nibble]) with (nibble) ; // explanation below

}
end
38. SV code to sum 2 numbers with help from a
endclass function.
function int add2 (int a, int b);
Simpler: force all LSBs of each nibble to 0 using mask: return a + b;
endfunction
class even_nibbles2;
rand bit [31:0] arr[1024]; module tb;
int x = 10, y = 20, z;
constraint c_even_nibs { initial begin
foreach (arr[i]) z = add2(x, y);
(arr[i] & 32'h1111_1111) == 32'h0000_0000; // all nibble LSBs = $display("z = %0d", z);
0 end
} endmodule
endclass

Any 32‑bit value whose bit0,4,8,…,28 are 0 has even number in each
nibble.
39. What is event scheduling in SV? INC and
WRAP memories?
36. Constraint to count number of 0s in a Event scheduling = how simulator orders events in time using
(preponed, active, inactive, NBA, observed, postponed). See Q30.
number; SV code for two signals with 500 ns
relation. types usually refer to address counters in memories: -
– after each access, address increments until max and
Count 0s in 32‑bit number then stops. - – address increments and wraps around to 0 after
class count_zeros; max. Used in circular buffers and some SRAM/DDR burst modes.
rand bit [31:0] val;
int zeros;

function void post_randomize();


zeros = 32 - [Link]() with (int'(item)); 40. Data types in Verilog and SystemVerilog.
endfunction
endclass Verilog: - Nets: wire, tri, wand, wor, etc. - Regs: reg, integer, time.

Signal sig1 goes high; after 500 ns, sig2 must go low SystemVerilog adds: - 2‑state: bit, byte, shortint, int, longint. - 4‑state:
logic, integer, time. - User‑defined: enum, struct, union, typedef. - Special:
initial begin
sig1 = 0; sig2 = 1; string, event, chandle, class, mailbox, semaphore, arrays (dynamic,
@(posedge start_event); associative, queue).
sig1 <= 1;
#500ns sig2 <= 0;
end

Or assertion: 41. Difference between logic, net, wire and reg.


property p_500ns_delay; ● wire (net): 4‑state, represents physical connection; driven by
@(posedge sig1) ##[500ns] (!sig2); continuous assigns/ports; can have multiple drivers.
endproperty
assert property (p_500ns_delay);
● reg: 4‑state variable; assigned in procedural blocks; single driver;
legacy.
(Note: tool‑specific syntax may require clocking rather than time units in
SVA.) ● logic: 4‑state variable, preferred in SV; can be used in
continuous or procedural assignments (single driver per scope).

● Generic keyword in SV: nettype or logic with modifiers is


37. How is memory allocated for shallow and more common.
deep copy?
● – new handle points to the ; no new
memory allocated for object data.
42. Importance of randomization in verification.
● – new object is allocated with its ; all Quickly explores large state space beyond what directed tests
fields copied. can cover.

19
Helps find corner‑case bugs not thought of initially. Same idea as Q27 but more generic:
Works together with functional coverage for
constraint c_asc {
. foreach (arr[i]) if (i>0) arr[i] >= arr[i-1];
Enables reusability: same environment can run many tests with }
different seeds/constraints.
No sort() or reverse() used.

43. Hard and soft constraints.


● – default; must be satisfied. If solver cannot find 48. Constraint for 1 bit variable that should be 1
solution → randomization fails. for 3 times.
● – declared with soft keyword; they provide
If we model 5 cycles as bit [4:0] sig; and want exactly three 1s:
but can be overridden by stronger constraints.
constraint c_default { soft size == 8; } class three_ones;
constraint c_override { size == 16; } // overrides soft rand bit [4:0] sig;
constraint c_three { [Link]() with (int'(item)) == 3; }
endclass

44. Assertion for FIFO full and empty.


Assume signals full, empty, wr_en, rd_en, count. 49. Global factory overriding syntax (UVM).
// Replace all instances of base_class with derived_class
// full when count == DEPTH factory.set_type_override_by_type(base_class::get_type(),
property p_full_flag; derived_class::get_type());
@(posedge clk) (count == DEPTH) |-> full;
endproperty // or using macro
assert property (p_full_flag); `uvm_set_type_override(base_class, derived_class)

// empty when count == 0


property p_empty_flag;
Instance override:
@(posedge clk) (count == 0) |-> empty;
endproperty `uvm_set_inst_override(base_class, derived_class, "*.[Link]*")
assert property (p_empty_flag);

// cannot write when full


assert property (@(posedge clk) full & wr_en |-> $error("Write when
full")); 50. Assertion: a high after 2 cycles, b high 1–3
// cannot read when empty
cycles after c asserted.
assert property (@(posedge clk) empty & rd_en |-> $error("Read when // a should go high exactly 2 cycles after c
empty")); property p_a_after_2;
@(posedge clk) c |-> ##2 a;
endproperty
assert property (p_a_after_2);

45. Declare a 16 bit associative array. // b should be high between 1 and 3 cycles after c
property p_b_1_to_3;
bit [15:0] aa[int]; // key: int, value: 16 bit @(posedge clk) c |-> ##[1:3] b;
bit [15:0] aa_str[string]; // key: string endproperty
assert property (p_b_1_to_3);

46. Constraint for 16 bit associative array: even


numbers at odd locations and odd at even. 51. Difference between rand and $random.
Assume key is int index.
● rand is a used with SystemVerilog built‑in
randomization and constraints ([Link]()).


class arr16;
rand bit [15:0] aa[int]; $random is a that returns a
pseudo‑random 32‑bit number.
constraint c_size { [Link]() == 8; } // example

constraint c_even_odd {
Key differences: - rand works with constraint solver; $random does not. -
foreach (aa[i]) { rand gives repeatability via seeds plus randomize(); $random sequencing is
if (i % 2 == 0) simpler and often less controllable. - randc provides cyclic behavior;
aa[i][0] == 1'b1; // even index → odd value (LSB=1)
$random cannot.
else
aa[i][0] == 1'b0; // odd index → even value (LSB=0)
}
}
endclass
52. Assertion to find a glitch + circuit.
signal y should follow x without glitches when passing through
combinational logic.
47. Constraint to generate ascending order
without array methods. Glitch definition: y toggles more than once within one clock period.

20
Assertion (no double toggle between clocks): 57. Snippets for deep copy and shallow copy.
property no_glitch; class pkt;
@(posedge clk) int id;
!$rose(y) throughout (##[1:$] !$fell(y)) or function pkt copy(); // deep copy
!$fell(y) throughout (##[1:$] !$rose(y)); pkt p = new();
endproperty [Link] = [Link];
return p;
// Simpler check: no change between two consecutive clocks endfunction
property stable_between_clks; endclass
@(posedge clk) $stable(y);
endproperty pkt p1 = new();
assert property (stable_between_clks); pkt p2 = p1; // shallow copy
pkt p3 = [Link](); // deep copy
(Exact form may vary; interviewer mainly wants idea of using $stable,
$rose, $fell.)

58. Snippet on how to override classes (UVM


factory).
53. Difference between bit–reg, int–integer. class base_driver extends uvm_driver;


`uvm_component_utils(base_driver)
bit – 2‑state (0/1) vector type, synthesizable. endclass

● reg – 4‑state (0/1/X/Z) variable from Verilog; replaced by logic in class my_driver extends base_driver;
SV. `uvm_component_utils(my_driver)
endclass
● int – 32‑bit, 2‑state signed in SV.
// In test build_phase
● integer – at least 32‑bit, 4‑state signed
function void build_phase(uvm_phase phase);
super.build_phase(phase);
(implementation‑dependent size). factory.set_type_override_by_type(base_driver::get_type(),
my_driver::get_type());
Use bit/int for 2‑state TB and synthesis; reg/integer are older 4‑state endfunction

types.

59. What is a singleton class?


54. Tasks and functions in Verilog & SV
A allows only of a class in the whole program.
enhancements.
class singleton;
Common rules (both): - : executes in zero time, no timing control, static singleton m_inst;
int data;
can be used in expressions. - : may contain timing control, can have
multiple outputs, called via statement. // private constructor
function new(); endfunction
SV enhancements: - Default automatic for functions/tasks in classes. -
Allows void functions, ref/const ref arguments. - Methods inside classes static function singleton get();
if (m_inst == null)
can be virtual. m_inst = new();
return m_inst;
endfunction
endclass
55. Constraint for even in odd location and odd in // Usage
even location. singleton s1 = singleton::get();
singleton s2 = singleton::get(); // s1 and s2 point to same object

Same as Q14/46; using dynamic array:

constraint c_even_odd {
foreach (data[i]) {
if (i % 2 == 0)
60. Constraint for int a not generating values
data[i] % 2 == 1; // even index → odd value between 100 and 200.
else
data[i] % 2 == 0; // odd index → even value
(Already answered as Q1 in previous part.)
}
}
constraint c_a_not_100_200 { a < 100 || a > 200; }

56. Constraint for two arrays being equal. 61. Constraint for pattern 0,2,0,4,0,6,…
class two_arrays;
rand int a[10];
(See earlier.)
rand int b[10];
constraint c_pattern {
constraint c_equal {
foreach (arr[i]) {
foreach (a[i]) b[i] == a[i];
if (i % 2 == 0)
}
arr[i] == 0;
endclass
else
arr[i] == (i+1); // 1→2,3→4,...

21
}
}

62. Test running in infinite loop with objection –


how to stop & debug?
● Add thread in TB with #TIMEOUT then uvm_fatal.

● Ensure every raise_objection() has matching drop_objection().


● Instrument loops with counters/prints to see progress.

● Use debugger / $stop to break and inspect call stack.

(See Part‑4 Q3 for detailed explanation.)

63. Assertion: signal A high for 100 consecutive


clock cycles.
property p_A_100_high;
@(posedge clk) A |-> A[*100];
endproperty
assert property (p_A_100_high);

Or to check whenever A goes high it stays high for 100 cycles:

property p_A_100_after_rise;
@(posedge clk) $rose(A) |-> A[*100];
endproperty
assert property (p_A_100_after_rise);

64. Implication operator; difference between |->


and |=>.
In SVA: - |-> = . Consequent starts in the
as antecedent. - |=> = . Consequent starts
in the after antecedent.

Example:

@(posedge clk) req |-> ##1 gnt; // gnt 1 cycle after req, but
sequence overlaps
@(posedge clk) req |=> gnt; // gnt in next cycle directly

65. Why do we use class in SystemVerilog?


Same as Q4 earlier: - For OOP (encapsulation, inheritance,
polymorphism). - For dynamic objects (transactions) with randomization
and constraints. - To build reusable, configurable verification components
(UVM).

66. What is the need of virtual interface in


SystemVerilog?
Same as Q5 earlier: - Classes cannot directly connect to module ports. -
Virtual interface provides a handle to an interface instance so
drivers/monitors can access DUT signals. - Enables reusability: same TB
code can work with different interface instances.

virtual bus_if vif;

22
endclass

SystemVerilog Interview Q&A – Set 6


class B extends A; // derived class
int extra;
function void print();
(Q1–80, Expanded Version) [Link]();
$display("B extra=%0d", extra);
endfunction
This version is intentionally more detailed for preparation.
endclass
Explanations, notes, and code comments have been
expanded to make the content roughly 50% longer and easier Inheritance improves code reuse and is the base for polymorphism in
to revise from. SystemVerilog.

1. How to access the parent method in child


4. Difference between dynamic and associative
class?
array?
You access the parent (base) class method inside the child class using the
super keyword. This is especially useful when the child overrides a method Dynamic array
but still wants to reuse some or all of the base behavior. Indexed by integer from 0 to size-1.
class parent; Size is and can be changed using new[size].
function void display(); Good when you know the number of elements but only at
$display("parent display");
endfunction
runtime, and indices are dense.
endclass int da[]; // declaration

class child extends parent; da = new[10]; // runtime allocation


function void display();
[Link](); // call parent method first // resize
$display("child display"); int new_size = 20;
endfunction da = new[new_size](da); // copy old contents
endclass
Associative array
Here child::display() first calls parent::display() using [Link]()
and then adds its own message. ● Indexed by an (int, string, packed array,
class handle, etc.).
● Grows automatically as new keys are used; elements can be
2. What is an abstract class? sparse.

● Supports search/iteration methods like first, next, exists.


● In SystemVerilog, an is declared as a virtual int aa[string];
class and directly. aa["ID1"] = 5;
● It usually provides a and may contain aa["ID2"] = 10;
, which have no implementation in the base string key;
class. if ([Link](key)) do
● Concrete derived classes must implement the pure virtual $display("%s -> %0d", key, aa[key]);
while ([Link](key));
methods.
virtual class base_driver;
Dynamic arrays are like resizable vectors; associative arrays behave like
// pure virtual method – no body, must be implemented in child
pure virtual task drive(); hash maps.

// normal method with body (optional)


virtual function void configure();
$display("base configure");
endfunction 5. What is polymorphism?
endclass
Polymorphism allows to refer to objects of
Any class that extends base_driver must implement drive(). Abstract , and when a virtual method is called, the
classes are heavily used in UVM to define generic drivers, monitors, and is chosen based on the actual object type at runtime.
sequences.
class base;
virtual function void run();
$display("base");
endfunction
3. What is inheritance? endclass

● Inheritance is an OOP concept where a is


class A extends base;
function void run(); $display("A"); endfunction
built from an existing using extends. endclass
● The child automatically gets all properties and methods of the
class B extends base;
parent and can or . function void run(); $display("B"); endfunction
class A; // base class endclass
int id;
function void print(); base h;
$display("A id=%0d", id); initial begin
endfunction h = new A(); [Link](); // prints A (A::run)

23
h = new B(); [Link](); // prints B (B::run) endfunction
end endclass

This is fundamental in UVM: components are referred to via base types class child extends parent;
function void display();
(like uvm_component) but their behavior comes from the specific derived $display("child"); // overrides parent implementation
type. endfunction
endclass

If a parent handle points to a child object, calling display() will execute


6. What are callbacks in SV? the child’s method.

● A is a mechanism to insert user‑defined, optional


behavior into a class .
● In UVM, callback classes are registered and then invoked at 9. What is semaphore?
specific hook points (e.g., before/after a driver sends a
A is a built‑in SystemVerilog class used to control
transaction).
access to a shared resource among multiple parallel processes.
● This allows test-specific behavior, monitors, or logging to be
added non‑intrusively. It maintains a count of . get() takes tokens
(blocking until available); put() returns them.
Conceptual example: semaphore sem = new(1); // 1 token => acts like a mutex

virtual class drv_cb; // Process 1


virtual task pre_drive(txn t); endtask fork
virtual task post_drive(txn t); endtask begin
endclass [Link](1); // lock
// critical section using a shared resource
class my_driver extends uvm_driver #(txn); [Link](1); // unlock
`uvm_register_cb(my_driver, drv_cb) end

task run_phase(uvm_phase phase); // Process 2


txn t; begin
forever begin [Link](1); // will block until process 1 puts token back
seq_item_port.get_next_item(t); // critical section
`uvm_do_callbacks(my_driver, drv_cb, pre_drive(t)) [Link](1);
// main driving to interface here end
`uvm_do_callbacks(my_driver, drv_cb, post_drive(t)) join
seq_item_port.item_done();
end
endtask
Semaphores prevent race conditions on shared resources such as files,
endclass buses, or mailboxes.

Different tests can register different callback objects to modify or observe


the driver’s behavior.
10. What is shallow and deep copy? Write syntax.
● : copies only the of an object; both handles
reference the in memory.
7. What are inline constraints? pkt p1 = new();


[Link] = 10;
are constraints written directly at the
randomize() call site using the with clause, instead of inside the pkt p2 = p1; // shallow copy – p1 and p2 point to same object
[Link] = 20;
class. $display("[Link]=%0d", [Link]); // prints 20
● They are typically used for or for
tightening a constraint temporarily. ● : creates a and copies over the data fields,
int x, y; so future changes are independent.
class pkt;
// randomize both x and y such that x<y and x is between 0 and 10 int id;
std::randomize(x, y) with { x inside {[0:10]}; x < y; }; function pkt copy();
pkt tmp = new();
You can also combine inline constraints with class randomization: [Link] = [Link];
return tmp;
pkt p = new(); endfunction
[Link]() with { addr == 8'hAA; }; // overrides normal addr range endclass

pkt p3 = [Link](); // deep copy – different object


[Link] = 30;
$display("[Link]=%0d", [Link]); // still 20
8. How can you override a method in parent
Deep copies are essential when you store transactions in scoreboards or
class? queues but do not want later modifications to affect already stored copies.
● In the child class, define a method with
as in the parent.

● The parent method should be declared virtual if you want 11. What is super keyword?
polymorphic behavior.
class parent; ● super is used within a derived class to access
virtual function void display();
$display("parent"); :
24
o Call the base class constructor: [Link](...). 15. What is a virtual interface?
o Call overridden methods: [Link](). ● A is essentially a to an
o Access base-class fields if not hidden. interface instance.
class parent;
function new(string name); ● Classes cannot directly connect to module ports, so they use a
$display("parent new: %s", name); virtual interface to read and drive DUT signals.
endfunction interface bus_if (input logic clk);
endclass logic req, gnt;
endinterface
class child extends parent;
function new(string name); class driver;
[Link](name); // call parent's constructor virtual bus_if vif; // virtual interface handle
$display("child new: %s", name);
endfunction function new(virtual bus_if vif);
endclass [Link] = vif;
endfunction
super helps you reuse parent behavior while still customizing the child.
task run();
forever begin
@(posedge [Link]);
[Link] <= 1'b1;
12. What is functional coverage? end
endtask
● is a user‑defined metric that checks endclass
whether the described in the verification plan
have been exercised. Virtual interfaces are usually passed via constructors or UVM config_db
from tb_top.
● It is implemented using covergroup, coverpoint, cross, and
optionally bins with ranges or named bins.
covergroup cg @(posedge clk);
// cover all 8 opcodes
coverpoint opcode { bins all[] = {[0:7]}; }
16. What is interface?
// cover packet length ranges ● An interface bundles related signals, clocking blocks, tasks,
coverpoint length { functions, and assertions into a single reusable unit.
bins small = {[0:63]};
bins big = {[64:255]}; ● It simplifies DUT port connections and keeps the protocol
} description in one place.
interface bus_if(input logic clk);
// cross coverage of opcode vs length logic req, gnt;
cross opcode, length; logic [7:0] addr, data;
endgroup
// Optional task to drive a transaction
Functional coverage tells you how much of the intended behavior has task drive(input logic [7:0] a, d);
actually been tested, not just which lines of RTL executed. addr <= a;
data <= d;
req <= 1;
@(posedge clk);
req <= 0;
13. What is setup and hold time? endtask
endinterface

For a flip‑flop:
The same interface instance is connected to both the DUT and the
testbench via virtual interfaces.
● : minimum time that data input D must be
stable the active clock edge (e.g., rising edge).
● : minimum time that data must remain stable
the clock edge. 17. What are different types of assertions?

If these conditions are violated, the flip‑flop can go into ,
o Checked at the moment they are executed in
leading to unpredictable output. In RTL, we normally assume correct
procedural code.
setup/hold, but in back‑annotated timing simulations and STA these
constraints are critical. o Useful for single‑cycle conditions.
assert (a <= b)
else $error("a is greater than b");

14. Difference between dynamic and associative ●


arrays? o Describe temporal properties across multiple cycles
using sequence and property.
(Same concept as in Q4.)
o Evaluated in the assertion (observed/postponed)
regions of the event schedule.
● Dynamic: contiguous integer indices; sized with new[size]; good
property p_req_gnt;
for vectors. @(posedge clk) req |-> ##1 gnt; // if req, then gnt next
● Associative: sparse or non‑integer keys; auto‑growing map cycle
endproperty
suitable for look‑up tables.
assert property (p_req_gnt);

25
You can also talk about and properties used mainly in formal
● Constraints are solved by the internal when you
verification.
call randomize().
class packet;
rand bit [7:0] addr;
rand bit [7:0] len;
18. How is read and write operation executed at
same time in dual port RAM? // address range 0x10–0x1F and length between 1 and 32
constraint c_addr { addr inside {[8'h10:8'h1F]}; }
constraint c_len { len inside {[1:32]}; }
● A has two independent ports (Port A and endclass
Port B), each with its own address, data, and control signals.
● In a given clock cycle: Constraints enable stimulus
o Port A can perform a read while Port B performs a generation.
write, or vice‑versa.
o Both ports can even perform writes (to different
addresses) simultaneously.
23. What is casting? What is static casting?
● If both ports access the , the
behavior depends on memory configuration (write‑first, read‑first, What are the components in verification?
or no‑change). The verification environment must account for
this according to spec. Casting
● Casting is converting a value or handle from one type to another.

19. What is semaphore? – checked by the compiler:

state_t s = state_t'(2); // convert int 2 to enum state_t


(Same as Q9 – resource sharing using get/put.) int i = int'(byte_var); // extend byte to int

– runtime type check, mainly for class handles:

20. How does a child class point to a parent base b; child c;


// ... b may actually refer to a child object
class? if (!$cast(c, b))
$error("Cast failed");
● When you write class child extends parent;, the child inherits
from the parent. Main verification components (UVM style)
● You can then use a to refer to a child object ● – creates sequence items / transactions.
(up‑casting).
● – converts transactions to pin‑level activity on interface.
parent p;
child c = new(); ● – observes DUT signals and converts them back into
transactions.
p = c; // up casting – allowed
[Link](); // if display is virtual, child’s version will run ● – compares expected vs actual
outputs.
This is the basis for polymorphism in SV. ● – collects functional coverage.
● – top‑level containers configuring all
components.

21. Why are we going for SystemVerilog? What


are disadvantages of Verilog? 24. Difference between task and function in SV?
- Verilog was mainly a language. - Executes in . - Cannot contain timing
Complex SoCs need powerful capabilities. - SystemVerilog controls (@, #, wait, fork / join). - Can be called from expressions and used
adds: - Classes and OOP - Constrained randomization - Assertions (SVA) - on RHS of assignments. - Returns a single value (or can be void).
Functional coverage - Interfaces, clocking blocks, advanced data types -
Standard methodologies like UVM - May contain and can span over many cycles. -
Cannot be used in expressions; invoked as a statement. - Can have
- No classes / objects → cumbersome to build multiple output arguments.
reusable testbenches. - No randomization or constraints → relies only on
directed tests. - No built‑in functional coverage or assertions. - Hard to function int add(int a, b);
manage large, modular environments. return a + b;
endfunction

SystemVerilog keeps backward compatibility while dramatically improving task delay_and_print(int v);
verification productivity. #10ns;
$display("v=%0d", v);
endtask

22. What are constraints?


● are declarative rules applied to rand / randc variables 25. What is virtual interface in SV and why do we
that restrict the set of values they can take during randomization. use it?

26
(Concept already explained in Q15.) 29. Explain polymorphism with code.
class base_seq;
We use a virtual interface to: - class‑based testbench and DUT
virtual task body();
signals. - Keep classes independent of a specific interface instance, $display("base body");
enabling reuse across different top‑level modules. - Pass connections endtask
through uvm_config_db or constructors without hard‑coding hierarchical endclass

paths. class read_seq extends base_seq;


task body(); $display("read seq"); endtask
endclass

26. What are the different data types in SV? class write_seq extends base_seq;
task body(); $display("write seq"); endtask
endclass
Some important categories:
base_seq seq;


initial begin
: bit, byte, shortint, int, longint. seq = new read_seq(); [Link](); // dynamic call ->
read_seq::body
● : logic, reg, integer, time. seq = new write_seq(); [Link](); // dynamic call ->
write_seq::body
● : typedef, enum, struct, union. end

● : string, event, chandle, class types, mailbox, The same base handle seq can refer to different sequence types; the
semaphore. correct body() is picked at runtime.
● : fixed‑size, dynamic, associative, queues; each can be
packed/unpacked.

These powerful data types make modeling complex protocols easier 30. Explain the difference between shallow copy
compared to classic Verilog. and deep copy with code and diagram.
(Concept already in Q10.)

27. Why do we use logic data type? ● : two handles → object.


● : two handles → but identical objects.
logic is a 4‑state type (0,1,X,Z) intended to most uses of
reg and wire. In diagrams you can draw:
It can be used for both signals and
supports continuous assignments, provided there is only one ● Shallow: p1 ─ ObjA ─ p2
active driver.
● Deep: p1 ─ ObjA and p3 ─ ObjB (where ObjA and ObjB hold
It integrates nicely with always_comb, always_ff, and same field values).
always_latch for clearer coding style.
logic clk, rst_n; Deep copies are generally preferred for scoreboards and mailboxes to
logic [7:0] data;
avoid unintended side effects.

28. Explain inheritance with code. 31. What is the difference between functional
class base_packet;
rand bit [7:0] addr;
and code coverage?
function void display(); ● answers: “How much of the RTL code structure
$display("[BASE] addr=%0h", addr);
endfunction did we execute?” (statements, branches, conditions, FSM states,
endclass toggles).
● answers: “How much of the intended
class read_packet extends base_packet;
rand bit [7:0] data; functionality or scenarios from the spec did we exercise?”
function void display();
[Link](); It’s possible to have 100% code coverage but poor functional coverage if
$display("[READ] data=%0h", data); you did not plan the right scenarios, and vice versa if some dead code
endfunction
endclass remains unexecuted.

class write_packet extends base_packet;


rand bit [7:0] data;
function void display();
[Link](); 32. What is the default value of reg, real, logic?
$display("[WRITE] data=%0h", data);
endfunction ● reg and logic (4‑state types) start as X in simulation unless
endclass
explicitly initialized.

Both read_packet and write_packet reuse addr and display() from ● real variables default to 0.0.
base_packet but customize the print message.
In synthesizable RTL you typically reset registers to a known value using
an explicit reset signal.

27
33. What is the difference between structure and 37. Difference between conditional and branch
class? bins?
struct) - Collection of fields grouped together. - No inherent ● : Tracks whether each possible
methods, although you can write functions that take structs as arguments. - branch of a decision (e.g., if, else if, else, case item) has been
Typically allocated statically or as part of another variable (no new taken.
required). ● : Looks inside a compound
decision, tracking each boolean sub‑expression.
typedef struct packed {
bit [7:0] addr;
bit [7:0] data; Example:
} pkt_s;
if (a && b) begin ... end
- Reference type; instantiated dynamically using new. - Can contain
, , and . - Supports and ● Branch: expression (a && b) true vs false.
; suitable for verification objects.
● Condition: four combinations of a and b (00, 01, 10, 11).
class pkt_c;
rand bit [7:0] addr, data;
function void print();
$display("addr=%0h data=%0h", addr, data);
endfunction
38. What is the use of clocking block?
endclass ● Clocking blocks give the testbench a
and specify when signals should be sampled or
driven relative to that clock.
● They help avoid race conditions between DUT and TB.
34. How to disable constraints? clocking cb @(posedge clk);
default input #1step output #1ns; // input sampling, output driving
You can disable individual constraints or all constraints for an object using skew
constraint_mode(). input data_out;
output data_in;
class pkt; endclocking
rand int addr;
constraint c_range { addr inside {[0:255]}; } Inside TB, you can write cb.data_in <= value; and @(cb); for clean timing
endclass
semantics.
pkt p = new();

initial begin
// disable single constraint
p.c_range.constraint_mode(0);
39. Where do we define clocking block?
[Link](); ● Typically , because the interface already
contains the clock and related signals.
// re enable later if needed
p.c_range.constraint_mode(1); ● This keeps the timing information local to the bus definition and
end reusable across multiple modules.
interface bus_if(input logic clk);
You can also override constraints in a derived class instead of disabling logic req, gnt;
them (see Q47).
clocking cb @(posedge clk);
output req;
input gnt;
endclocking
35. What is a wildcard bin? endinterface

● A allows x and z as when defining a


bin value.
● Useful for grouping ranges that share the same bit pattern. 40. What is the use of interfaces?
coverpoint addr {
wildcard bins upper_half = {8'b1xxx_xxxx}; // any value with MSB=1 Interfaces are used to: - related signals belonging to a common
} protocol. - Reduce the number of top‑level DUT ports. - Encapsulate
protocol tasks, functions, clocking blocks, and assertions. - Make
All addresses from 8'h80 to 8'hFF hit the same bin upper_half. verification components more reusable, since they only need a virtual
interface handle.

36. What are code coverage bins?


● Code coverage bins are internal counters created by the 41. How is setup and hold time in clocking block
simulator for each relevant RTL construct: statements, branches, different from normal setup and hold time?
case items, expressions, bits, etc.
● In a , you specify input and output (e.g.,
● You do not define these bins manually; they are generated input #1step, output #2ns). These determine when TB samples
automatically when you enable code coverage (-cm inputs and drives outputs relative to the reference clock edge.
line+branch+cond+fsm+tgl in VCS, for example).
● This is purely a to avoid races; it does not
correspond directly to physical cell setup/hold times.
28
Hardware setup/hold times are physical device requirements checked by ● are the of a class (variables, fields).
STA, not by the clocking block. ● are inside a class that operate on
these properties.
class pkt;
int addr; // property
42. What are the types of arrays in SV? int data; // property

● – like traditional Verilog vectors and function void print(); // method


multi‑dimensional arrays. $display("addr=%0d data=%0d", addr, data);
endfunction
● – size decided at runtime. endclass
● – indexed by key types.

● [$]) – ordered collection supporting push/pop.


● Each of these can be or depending on 47. How to override the constraints?
declaration.
You can override constraints by redefining a constraint with the
in a derived class, or by using different classes with different
43. Difference between @ev and wait([Link]). constraint sets.

class base_pkt;
Assume event ev; rand int addr;
constraint c_addr { addr inside {[0:255]}; }
● @ev; – blocks until ev is triggered once.
endclass


class small_addr_pkt extends base_pkt;
wait([Link]); – waits until event’s triggered property // overrides c_addr from base
becomes non‑zero (can be used with additional conditions): constraint c_addr { addr inside {[0:15]}; }
endclass
wait([Link] && ready);

When you randomize a small_addr_pkt object, only the new definition of


For simple synchronization they behave similarly; wait is more flexible
c_addr is applied.
inside complex expressions.

44. What is SystemVerilog event schedule? 48. What is semaphore and how is it used in a
program?
SystemVerilog divides each simulation time step into (the
stratified event queue): (See Q9.) In summary: semaphores are used with get/try_get/put to
implement blocking and non‑blocking access to shared resources.
1. – sampling for assertions, etc.
2. – evaluation of always blocks, blocking assignments.
3. – #0 events. 49. How does semaphore implement blocking
4. – LHS updates of non‑blocking methods?
assignments.
5. – assertion evaluation after NBAs. ● get(n) is a : if fewer than n tokens are available, the
process waits in the semaphore queue until enough tokens are
6. – final $display and monitoring.
returned.
This ordering ensures consistent interaction between blocking/non‑blocking ● try_get(n) is : it returns 1 on success, 0 on failure,
assignments and assertions. and never blocks.
if (!sem.try_get(1)) begin
$display("resource busy, skipping");
end
45. How do we inherit properties and methods? else begin
// exclusive access here
[Link](1);
By using extends when declaring a class: end

class parent;
int id;
function void show();
$display("id=%0d", id); 50. What is the coverpoint?
endfunction
endclass
A is part of a covergroup that specifies the
class child extends parent; whose values you want to track for functional coverage.
int extra;
endclass covergroup cg @(posedge clk);
coverpoint addr { bins all[] = {[0:15]}; }
endgroup
child now has both id and extra, plus the show() method.

Each time the covergroup is sampled, the current value of addr is recorded
in the appropriate bin.
46. What are properties and methods?
29
51. What is polymorphism and how is it
implemented? 57. Explain code coverage and functional
(Already explained in Q5 and Q29.) In short: - Implemented via coverage with example.
. - Base handle points to derived object;
when calling a virtual method, the derived implementation runs. Code coverage example: enabling tool options to measure how many
statements and branches of a FIFO RTL module were executed.

Functional coverage example (packet fields):


52. Let a and b are variables where b = a + 4, write a covergroup cg_pkt;
constraint for a which is an even number. coverpoint length { bins small = {[0:63]}; bins big = {[64:255]}; }
coverpoint pkt_type { bins all[] = {[0:3]}; }
class ex; cross length, pkt_type;
rand int a, b; endgroup
constraint c_rel { b == a + 4; } // relationship between a and b
constraint c_even { a % 2 == 0; } // a must be even
endclass Together they give a more complete picture of verification progress.

You may optionally bound a to a range if needed.

58. What if functional coverage is not 100% and


what will you do if it is not 100%?
53. How to override constraint?
● Inspect coverage report to identify .
Same as Q47 – via derived classes or constraint_mode() to enable/disable ● Determine if these bins correspond to :
specific constraints. o If yes → adjust constraints, add directed or targeted
random tests, and maybe relax over‑constraints.
o If no (dead code or unrealistic scenarios) → document
and them with justification.
54. What is OOP?
Coverage closure is an iterative loop between stimulus, constraints, and
is a programming paradigm based coverage analysis.
on and . Key pillars:

● – bundling data and methods together.


● – deriving new classes from existing ones. 59. Difference between task and functions.
● – same interface, different underlying behavior.
● – hiding implementation details and showing only the (Refer back to Q24 – same differences.)
necessary interface.

SystemVerilog classes fully support OOP and UVM builds on this model.
60. Difference between fork join_any and fork join_none .
● join_any: parent waits for first child to complete, then remaining
55. Explain fork..join, join_any, join_none. children are killed.
fork ● join_none: parent does not wait at all; children run concurrently
task1();
task2(); while parent continues.
join
// Parent thread waits until BOTH task1 and task2 finish. This affects how long the testbench thread stays alive and how timeouts
must be handled.
fork
task1();
task2();
join_any
// Parent waits until ANY ONE finishes, then remaining threads are
terminated.
61. What is Assertion?
● An is a statement that checks that a given property
fork holds during simulation (or formal analysis).
task1();
task2(); ● They help and document the
join_none intended behavior.
// Parent does NOT wait; both tasks continue in background.
Types: immediate (single‑cycle) and concurrent (multi‑cycle temporal
Used for parallelism in testbenches and some RTL models. properties).

56. What are constraints and why are they used? 62. What is modport?
(See Q22.) They are used to: - Constrain random values to ranges. - ● A is a named view of an interface that defines which
Model dependency relations between fields. - Improve coverage closure by signals are for a given user (DUT, TB,
focusing on interesting cases instead of fully random noise. etc.).

30
interface bus_if(input logic clk); (As earlier.)
logic req, gnt;
modport DUT (input req, clk, output gnt); class fib_seq;
modport TB (output req, input gnt, clk); rand int f[];
endinterface constraint c_size { [Link]() == 8; }
constraint c_fib {
The DUT and testbench modules use different modports, enforcing correct f[0] == 0;
direction usage. f[1] == 1;
foreach (f[i]) if (i>=2) f[i] == f[i-1] + f[i-2];
}
endclass

63. How many bins will be created for the This generates the first 8 Fibonacci numbers: 0,1,1,2,3,5,8,13.
covergroup shown?
module top;
bit [6:0] a;
int b; 67. Write a constraint to generate sequence of
covergroup vk_coverage;
coverpoint a;
prime numbers.
coverpoint b {
bins b_bin1 = {1,2,3,4,5}; Pure declarative prime constraints are complex, so a practical answer
bins b_bin2 = default; mixes randomization with procedural checks.
}
endgroup class prime_seq;
endmodule rand int p[];
constraint c_size { [Link]() == 5; }
● coverpoint a on a 7‑bit variable creates ; most tools function bit is_prime(int n);
create 128 bins (one per value). int i;
if (n < 2) return 0;
● coverpoint b has 2 explicit bins: b_bin1 and a default bin for (i = 2; i*i <= n; i++)
b_bin2. if (n % i == 0) return 0;
return 1;
● So total ≈ . Mention that the exact number for a can endfunction

depend on tool settings. function void post_randomize();


foreach (p[i]) begin
do p[i] = $urandom_range(2,100); while (!is_prime(p[i]));
end
64. What is difference between logic and byte? endfunction
endclass
● logic is a generic type; default size is 1 bit but can be
ranged. Explain that interviewers usually accept this procedural approach.

● byte is a signed integer.


logic flag; // 0,1,X,Z
byte data8; // range -128 .. +127, only 0/1 bits 68. Write assertion for JK flip flop.
logic is more appropriate for RTL signals; byte is convenient for modeling For a synchronous JK FF with async reset:
data bytes in testbench code.
property jk_ff_prop;
@(posedge clk)
disable iff (!rst_n)
case ({j,k})
65. Where is pre_randomize() and post_randomize() used? 2'b00: q == $past(q);
2'b01: q == 1'b0;
● These are around randomization. You override 2'b10: q == 1'b1;
them in your class (especially UVM objects) to perform actions 2'b11: q == ~$past(q);
and the constraint solver runs. endcase;
endproperty
class pkt extends uvm_object;
rand int addr;
assert property (jk_ff_prop);
function void pre_randomize();
// e.g., disable some constraints based on config This property checks that q follows the truth table for all four JK
endfunction combinations.

function void post_randomize();


// e.g., compute checksum based on randomized fields
endfunction
endclass 69. Explain assertion and its types.
For non‑UVM classes you can define methods with these names and call (See Q17 and Q61.)
them manually.
● Assertions are embedded in the design
or testbench.
● Two main categories: and .
66. Write a constraint to generate Fibonacci
series. ● In formal verification, you also use assume and cover properties to
constrain inputs and observe reachability.

31
70. What are types of constraints? if (!rst_n)
q <= 1'b0; // initialization
else
Common constraint patterns: q <= d;
end

● : a inside {[0:10]};

● : a < b;
76. What is modport?
● : opcode inside {READ, WRITE};
(Same as Q62.) Modports help partition interface signals by direction for
● : a dist {0 := 80, 1 := 20}; different users.
● : unique {a, b, c};

● : (mode == BURST) -> len > 1;


77. How many bins will be created for the
● vs .
covergroup shown?
● using with.
(Same as Q63; answer ≈ 130 bins.)

71. Why do we need constraints?


We need constraints because unrestricted randomization would: - Produce 78. How static interface is connected to local
many scenarios. - Make simulations inefficient and interface of driver?
coverage closure slow.
● Static interface is instantiated in tb_top.
Constraints focus the randomization on stimulus that
thoroughly exercises the design within reasonable simulation time. ● A in the driver is bound to this static
instance via constructor or config_db.
interface bus_if(input logic clk);
logic req, gnt;
endinterface
72. Explain code coverage and functional
coverage with example. class driver;
virtual bus_if vif;
function new(virtual bus_if vif); [Link] = vif; endfunction
(Already covered – you can reiterate that both are complementary; neither endclass
alone is sufficient.)
module top;
logic clk; bus_if bus(clk);
initial begin
driver d = new(bus); // connection done here
73. What if functional coverage is not 100% and end
endmodule
what will you do?
(See Q58.) Typically, you will: analyze, adjust constraints/tests, and justify
any unreachable bins.
79. What is Input and Output Skew?
In a :- – amount of time after (or before) the
reference clock edge when inputs are sampled. - – amount of
74. How are sequential circuits realised? time after (or before) the clock when outputs are driven.
● Sequential circuits use (flip‑flops / latches) to
clocking cb @(posedge clk);
store state.
default input #1step output #2ns;
● RTL coding style: endclocking
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) Here inputs are sampled one simulator time step after clock edge; outputs
state <= IDLE;
else
are driven 2 ns later, avoiding race with DUT logic.
state <= next_state;
end

Combinational logic computes next_state from state and inputs. 80. What is the main advantage of
SystemVerilog?
● SystemVerilog unifies
75. How flip flops are initialized in sequential into a single language.
circuits? ● It provides:

● Flip‑flops are initialized using (synchronous or o Modern RTL constructs (always_ff, interfaces, rich
asynchronous). types).
● You drive reset at TB top for some cycles; RTL sets registers to o Powerful verification features (classes, constraints,
known values when reset is asserted. coverage, SVA).
always_ff @(posedge clk or negedge rst_n) begin

32
o Ecosystem support through methodologies like ,
which standardize how verification environments are
built.

The main advantage is : you can build scalable,


configurable, and reusable verification environments that significantly
reduce overall verification effort.

(End of Expanded Set 6)

33
4. Explain threads.
SystemVerilog Interview Q&A – Set 7 In SV, a is an independent process that can run in parallel with
(Q1–43) others.

● Created by initial, always, or fork...join* blocks.


● Each thread has its own execution flow, but all advance
1. Explain SV TB (SystemVerilog Testbench) according to the same simulation time.
architecture.
Example:
A typical is class based and modular.
Main blocks: initial $display("Thread 1");

initial begin
● – groups DUT signals and connects #10; $display("Thread 2 after 10 time units");
TB classes to DUT. end
● – class that models one stimulus
item (e.g., bus read/write). Both initial blocks are separate threads executing concurrently.
● – creates a stream of transactions (often
constrained‑random).
● – converts transactions into pin‑level activity on the 5. Explain events.
interface.
● – passively samples DUT signals and converts them An is a simple synchronization object.
back to transactions.
● – checks DUT outputs vs Declared as event ev;.
expected results. Triggered with -> ev; or ->> ev; (non‑blocking trigger).
● – functional coverage using covergroups. Waited on with @ev; or wait([Link]);.
● – containers that build, connect, and
Example:
configure the above.
● – top‑level class selecting configuration, sequences, and event done;
running the simulation.
initial begin
#5; -> done; // trigger
Data flow: . end

initial begin
@done; // wait
2. Difference between mailbox and queue. $display("Received event at %0t", $time);
end

(class‑based IPC) - Built‑in TLM FIFO between processes /


classes. - Methods: new(), put(), get(), try_put(), try_get(), peek(),
num(). - put() and get() are blocking (can wait if empty/full). - Used for
6. Write constraints to generate even numbers.
synchronization and communication between parallel threads (e.g., driver
class even_num;
and generator).
rand int x;
constraint c_even { x % 2 == 0; } // x is even
([$]) - Variable‑size array with push/pop operations in a single endclass
process. - Methods: push_front, push_back, pop_front, pop_back, insert,
delete, etc. - No built‑in blocking; just a data structure, not a You can also restrict a range:
synchronization primitive.
constraint c_range { x inside {[0:100]}; x % 2 == 0; }
So ,
.

7. Write assertion to verify clock signal.


3. Difference between Verilog vs SystemVerilog. Property: the clock should toggle every cycle (simple checker example).

property p_clk_toggles;
- Primarily a hardware description language for RTL and gate‑level @(posedge clk) $changed(clk);
design. - Limited data types (reg, wire, integer, real). - No classes, no endproperty
constrained randomization, no functional coverage. - Basic tasks/functions
// Better: check that period is within range using a reference time
and simple testbenches.
property p_clk_period;
time t1, t2;
- Superset of Verilog (backward compatible). - Adds @(posedge clk)
powerful : classes & OOP, rand/randc, constraints, (t1 = $time), ##1 (t2 = $time,
(t2 - t1) inside {[9:11]}); // 10 time units ±1
covergroups, assertions (SVA), mailboxes, semaphores, queues, dynamic endproperty
& associative arrays. - Adds : logic, always_ff,
always_comb, interfaces, packed structs/unions, enums, unique/priority, etc. assert property (p_clk_period);
- Enables standard methodologies like .
Even simpler form used in labs:

34
// Clock must not stop toggling module tb_top;
property p_clk_not_stuck; logic clk; bus_if bus(clk);
@(posedge clk) 1 |-> ##1 $rose(clk) or $fell(clk); driver d;
endproperty initial begin
assert property (p_clk_not_stuck); d = new(bus); // pass interface to class
end
endmodule

8. Write constraints for Fibonacci series.


Generate N elements of Fibonacci sequence in an array. 11. Explain memories.
class fib_seq; In verification/design, are storage arrays:
rand int f[];
constraint c_size { [Link]() == 8; } ● can be modeled as arrays.
constraint c_fib {
f[0] == 0;
f[1] == 1; ● 1D memory example:
foreach (f[i]) if (i >= 2)
f[i] == f[i-1] + f[i-2]; logic [7:0] mem [0:255]; // 256 x 8 bit memory
}
endclass
● 2D memory (e.g., 32x32):

logic [31:0] mem [0:31]; // 32 words, each 32 bits

9. What is polymorphism? Access:

Polymorphism = . mem[addr] <= wdata; // write


rdata = mem[addr]; // read
● Implemented via
. In TB you often wrap memories in classes or interfaces to model RAM,
● A base class handle can point to objects of derived classes; ROM, FIFOs, etc.
calling a virtual method executes the derived implementation.
class base;
virtual function void run();
$display("base run"); 12. Constraint: 1st randomization ascending, 2nd
endfunction
endclass randomization descending (vice versa).
class child1 extends base; Idea: use a that flips after each randomize() and constrains
function void run(); $display("child1 run"); endfunction
ordering based on the toggle.
endclass
class order_arr;
class child2 extends base;
rand int a[];
function void run(); $display("child2 run"); endfunction
static bit asc = 1; // class static: shared toggle
endclass
constraint c_size { [Link]() == 5; }
base h;
initial begin
h = new child1(); [Link](); // child1 run constraint c_order {
h = new child2(); [Link](); // child2 run foreach (a[i]) if (i>0) {
end if (asc)
a[i-1] <= a[i]; // ascending
else
a[i-1] >= a[i]; // descending
}
10. What is virtual interface? }

function void post_randomize();


A is a handle (pointer) to an actual interface instance. asc = ~asc; // flip for next randomize()
Classes can’t directly connect to DUT ports, so they use a virtual interface endfunction
endclass
to access the signals.

interface bus_if(input logic clk); Call [Link]() repeatedly; order alternates between ascending and
logic req, gnt; descending.
endinterface

class driver;
virtual bus_if vif; // virtual interface handle
13. Tasks t1, t2, t3 executed in parallel but must
function new(virtual bus_if vif);
[Link] = vif; finish in order t3, then t2, then t1.
endfunction
We can run them in parallel using fork...join_none and use events /
task run(); semaphores to enforce completion order.
forever begin
@(posedge [Link]);
task t1(); #20; $display("t1 done"); ->ev1; endtask
[Link] <= 1'b1;
task t2(); #10; $display("t2 done"); ->ev2; endtask
end
task t3(); #5; $display("t3 done"); ->ev3; endtask
endtask
endclass
event ev1, ev2, ev3;

35
$display("Thread B start");
initial begin #5; $display("Thread B end");
fork end
t1();
t2(); A and B run concurrently. You can also spawn threads inside a procedural
t3();
join_none // start all three in parallel block:

@ev3; // wait till t3 completes initial begin


@ev2; // then t2 fork
@ev1; // then t1 task1();
$display("Order enforced: t3, t2, t1"); task2();
end join
end

Another way is to use a semaphore with proper token ordering, but events
are simpler.

17. Write constraint to generate odd number.


class odd_num;
14. Explain semaphore. rand int x;
constraint c_odd { x % 2 == 1; }
endclass
A is a built‑in class for managing access to shared resources.
With range:
● Created as semaphore sem = new(N); where N = initial tokens.
constraint c_range { x inside {[1:99]}; x % 2 == 1; }
● get(k) – blocks until k tokens are available, then removes them.

● try_get(k) – non‑blocking; returns 1 on success, 0 on failure.

● 18. How to run 3 tasks t1, t2, t3 parallelly and


put(k) – returns k tokens.
must execute t3, t2, t1 in an order.
Used for mutual exclusion (mutex) when N=1, or for limiting the number of
parallel users for a resource when N>1. This is same requirement as Q13; here is an idiomatic solution using
events:

event e1, e2, e3;

15. Explain arrays and types. task t1(); ... ->e1; endtask
task t2(); ... ->e2; endtask
SystemVerilog arrays types: task t3(); ... ->e3; endtask

initial begin
● – bits laid out contiguously; useful for arithmetic fork
and slicing. t1();
t2();
logic [7:0] byte_packed; // packed t3();
join_none

● – separate elements; like C arrays. @e3; // wait t3 complete


@e2; // then t2
int a [0:15]; // fixed size unpacked @e1; // then t1
end

● – size decided at runtime, changeable with All three run in parallel, but the checking/printing or follow‑up logic waits for
new[]. completion in order t3 → t2 → t1.

int da[]; da = new[10];

● – indexed by key type (int, string, etc.). 19. How the semaphore is worked?
int aa[string]; aa["ID"] = 5; Operational explanation:

● – variable‑size array with push/pop at ends. A semaphore has a of available tokens.

int q[$]; q.push_back(10); get(k):


o If counter >= k → decrement counter by k and
proceed.
o Else → process is and put into a wait queue
16. Explain Threads with example. until enough tokens are returned.
Threads are parallel processes created by initial, always, or fork...join. put(k):

initial begin o Increment counter by k.


$display("Thread A start");
#10; $display("Thread A end");
o If blocked processes are waiting and now enough
end tokens exist, one or more are woken up.

initial begin

36
This mechanism ensures only a limited number of threads can enter the output gnt);
modport TB (output req,
critical section.
input gnt, clk);
endinterface

Modules connect using a specific modport, which enforces correct signal


20. Define semaphore and its syntax. directions.

SystemVerilog semaphore is a class for resource‑sharing


synchronization based on counting tokens.
24. Define interfaces.
semaphore sem; // declaration
An is a construct that bundles related signals and optional code
sem = new(1); // create with 1 token (tasks, functions, clocking blocks, assertions) into one reusable unit.
[Link](1); // acquire
// critical section Benefits: - Reduces number of ports on modules. - Keeps protocol
[Link](1); // release
definition in one place. - Connects cleanly to classes via virtual interfaces.

Example:

21. What is mailbox? And its different methods. interface axi_if(input logic aclk);
logic valid, ready;
logic [31:0] addr, data;
A is a class‑based message queue used for communication
between threads or components. // protocol task
task send(input logic [31:0] a, d);
Declaration and creation: addr <= a;
data <= d;
mailbox mbx; // unbounded valid <= 1;
mailbox #(packet) mbx_p; // parameterized @(posedge aclk);
initial mbx = new(); wait (ready);
valid <= 0;
endtask
Common methods: - put(item) – blocking put, waits if mailbox is full (for endinterface
bounded mailbox). - get(item) – blocking get, waits until an item is
available. - try_put(item) – non‑blocking; returns 1 on success, 0 if full. -
try_get(item) – non‑blocking; returns 1 on success, 0 if empty. -
peek(item) – read item without removing it. - num() – returns current 25. Define clocking block.
number of items.
A defines a clock domain and specifies when signals are
sampled and driven relative to that clock, avoiding race conditions.

22. Define different threads of fork_join and give interface bus_if(input logic clk);
logic req, gnt;
example for fork...join_none with code snippet.
clocking cb @(posedge clk);
fork...join has three variants: default input #1step output #2ns; // skews
output req;
input gnt;
● fork...join – parent waits for child threads to finish. endclocking
endinterface
● fork...join_any – parent waits until child finishes;
remaining threads are killed. Inside TB you use [Link] and @(cb) for timing‑safe operations.

● fork...join_none – parent does ; children continue in


background.
26. What is difference between $rose and posedge?
Example for fork...join_none:
Both detect Rising edges, but usage differs:
initial begin
fork
task1(); ● posedge – used in sensitivity lists and event controls.
task2();
join_none
$display("Parent continues immediately at %0t", $time); always @(posedge clk) ...
// task1 and task2 still running @(posedge clk);
end

● $rose(expr) – a SystemVerilog function returning 1 for one


simulation cycle when expr transitions 0→1. Used in procedural
23. Define modports. code or assertions.

A is a named view of an interface that specifies the if ($rose(sig)) $display("sig rose");


(input/output/inout) of signals for a particular user (DUT, TB, etc.).
property p; @(posedge clk) $rose(req) |-> gnt; endproperty
interface bus_if(input logic clk);
logic req, gnt;
modport DUT (input req, clk,

37
$rose can be used on any boolean expression; posedge is tied to event
control.
31. Write functional coverage for 32x32 memory
array.
27. What is immediate and concurrent assertion? Example: cover all addresses and read/write operations for a 32x32
Explain. memory.

- Checked at the time they are executed in covergroup mem32x32_cg @(posedge clk);
coverpoint addr { bins all_addr[] = {[0:31]}; }
procedural code. - Used for single‑cycle conditions. coverpoint we { bins read = {0};
bins write = {1}; }
assert (a <= b) cross addr, we;
else $error("a > b"); endgroup

- Describe temporal properties over multiple clock You can also add data value bins if required.
cycles using sequence and property. - Sampled and evaluated in the
assertion regions of the event schedule.

property p_req_gnt;
@(posedge clk) req |-> ##1 gnt; // if req, gnt must be high next 32. What is functionality of bins?
cycle
endproperty In a covergroup, define which values or value ranges to track. Each
assert property (p_req_gnt); time the covergroup is sampled, the current value falls into one bin, and
that bin’s hit count is incremented.

Functions of bins: - Partition value space into regions of interest. - Allow


28. What is inheritance? coverage tools to report which scenarios occurred and how often. - Special
bins (ignore_bins, illegal_bins) control which values are ignored or
Inheritance is an OOP concept where a is created from a flagged as errors.
using extends. The child gets all fields and methods of the parent and
can add/override members.

class base_pkt;
int id; 33. Write constraint to generate unique values
function void print();
$display("base id=%0d", id);
for array of 16 elements.
endfunction class unique_arr;
endclass rand int a[];
constraint c_size { [Link]() == 16; }
class read_pkt extends base_pkt; constraint c_unique { unique { a }; }
int data; endclass
function void print();
[Link](); unique {a} ensures all elements in array a have different values.
$display("read data=%0d", data);
endfunction
endclass

34. Static timing verification is used to verify


delay of circuit of ____ level simulation.
29. What is code coverage?
Answer: (and also post‑layout) simulation.
measures how much of the RTL (or TB) code has been
executed during simulation. So: Static timing verification is used to verify delay of circuit of gate level
simulation.
Types: - Statement coverage - Branch / decision coverage - Condition /
expression coverage - Toggle coverage - FSM state and transition
coverage
35. Write code for cross coverage of user defined
High code coverage indicates that tests have exercised most of the
bin using bin selection expression.
implementation, but it does not guarantee functional completeness.
Example: address and burst length cross, but only for selected bins.

covergroup cg @(posedge clk);


30. What is functional coverage? coverpoint addr {
bins low = {[0:7]};
bins high = {[24:31]};
measures whether all required }
from the spec or verification plan have been hit.
coverpoint burst_len {
Implemented using covergroup, coverpoint, and cross. bins small = {[1:4]};
bins big = {[5:8]};
}
covergroup mem_cov @(posedge clk);
coverpoint addr { bins all[] = {[0:31]}; }
coverpoint rw { bins read = {0}; bins write = {1}; } // cross only selected bins using bin selection
cross addr, rw; cross addr, burst_len {
endgroup bins low_small = binsof([Link]) && binsof(burst_len.small);
bins high_big = binsof([Link]) && binsof(burst_len.big);

38
} After shallow copy, changing p2.a changes p1.a; after deep copy, they are
endgroup
independent.

36. What is constraint and types? 40. What is clocking block and modport?
A restricts the set of values that rand/randc variables can take ● – defines timing (sampling/driving) for signals
during randomization. relative to a clock; used inside interfaces.
● – defines a specific view of interface signal directions for
Common types / styles: - Range constraints – a inside {[0:10]}; - a user (DUT, TB, monitor, etc.).
Relational constraints – a < b; - Set/inside constraints – opcode inside
{READ, WRITE}; - Distribution constraints – a dist {0 := 50, 1 := 50}; - Example:
Uniqueness constraints – unique {id0, id1}; - Conditional/implication
constraints – (mode==BURST) -> len>1; - Soft vs hard constraints – soft interface bus_if(input logic clk);
logic req, gnt;
keyword for overridable defaults.
clocking cb @(posedge clk);
default input #1step output #2ns;
output req;
37. Write code for blocking and non-blocking. input gnt;
endclocking
// Blocking assignment (=)
always @(posedge clk) begin modport DUT (input clk, req, output gnt);
a = b; // RHS evaluated and assigned immediately modport TB (clocking cb);
end endinterface

// Non blocking assignment (<=)


always @(posedge clk) begin
a <= b; // RHS evaluated, update scheduled for NBA region
end 41. What is Interface?
Blocking is executed sequentially within the same time step; non‑blocking (Repeat of Q24 in short.)
updates all targets together at end of time step, which is preferred for
sequential logic. An bundles related signals and optional behavioral code. It
simplifies connectivity and supports virtual interfaces, clocking blocks,
modports, and assertions.

38. Difference between rand and randc.


● rand – normal random variable; each randomize() call can 42. What are constraints (inside)?
produce any value satisfying constraints (repeats allowed).
The inside operator is used in constraints to specify that a value must
● randc – cyclic random; iterates through all values in its range in a belong to a .
random order before repeating a value.
class ex; rand int addr;
rand bit [1:0] a; // rand: 0,1,2,3 any time constraint c { addr inside {[16'h0000:16'h0FFF], 16'hFF00, 16'hFF10};
randc bit [1:0] b; // randc: generates 0,1,2,3 in random perm, }
then repeats
endclass Here addr can be any value in 0x0000–0x0FFF, or exactly 0xFF00 or
0xFF10.
randc is useful when you want to cover all values uniformly without repeats
until the cycle completes.

43. What are ignore bins?


39. Difference between shallow copy and deep ignore_bins are bins whose hits are toward coverage.
copy.
● Used when some values are legal but not important for
● – copies only the handle; both handles point to the coverage.
same object.
● Hitting an ignore bin does decrease coverage or raise an
error.
pkt p1 = new(); coverpoint opcode {
pkt p2 = p1; // shallow bins all_ops[] = {[0:15]};
ignore_bins reserved = {4'hE, 4'hF};
● – creates a new object and copies field values. }

Values 0–13 contribute to coverage; 14 and 15 are ignored.


class pkt;
int a;
function pkt copy();
pkt t = new();
t.a = this.a; (End of Set 7)
return t;
endfunction
endclass
pkt p3 = [Link](); // deep

39
Good controllability and observability are essential for
.
SystemVerilog Interview Q&A – Set
8A (Q1–30)
5. What is Thread and explain the different
thread synchronization techniques.
1. What is $write? In SystemVerilog, a is an independently executing process created
by:
$write is a SystemVerilog system task used to
.
● initial / always blocks
$write("Time = %0t value = %0d ", $time, data);
● fork...join* blocks
● Use $write when you want to ● process class
and control where line breaks occur (usually by printing "\n"
yourself or by a later $display).

14. – event ev; -> ev; @ev; wait([Link]);


2. What is $display? 15. – control access to shared resources using tokens
(get, try_get, put).
$display is a system task used to
at the end. 16. – blocking put/get for inter‑thread communication.

$display("Time = %0t value = %0d", $time, data); 17. fork...join, join_any, join_none – specify how parent thread
waits for child threads.
● Every $display call starts on a new line in the transcript. 18. – synchronize TB actions to clock edges.

● Same formatting rules as $write with %0d, %0h, %0b, %0s, etc.
6. What is blocking and non blocking
assignment?
3. How to improve the Test Coverage.
● =)
To improve overall coverage (code and functional):
o Executes immediately and the execution of
– identify unhit / low‑hit areas. following statements until assignment completes.
33.
– remove over‑constraining that o Used mainly in or testbench
34.
prevents some scenarios. procedural code.

35. – directed or constrained‑random a = b; // RHS evaluated and assigned before next


sequences targeting uncovered bins. statement
c = a; // sees the updated value of a
36. – ensure combinations of conditions are
tried.
– to catch protocol violations and exercise corner
● <=)
37.
cases. o RHS is evaluated immediately, but update to LHS
happens in at end of
38. – run multiple seeds to explore random
time step.
space.
39. – avoid unrealistic assumptions that o Used for (always_ff @(posedge clk)).
forbid legal scenarios. always_ff @(posedge clk) begin
a <= b; // all flops updated together at clock edge
Coverage closure is an between stimulus, constraints, and end
coverage analysis.
Non‑blocking assignments avoid race conditions in clocked logic.

4. Define Controllability and Observability.


● : The ease with which an internal signal or node
7. What is Assertion and explain the need of
can be from the primary inputs or testbench Assertions.
stimulus.
An is a statement that checks that a given holds during
o High controllability → easy to force signal to required
simulation (or formal verification).
values for testing.
● : The ease with which the effect of an internal signal Need / benefits:
can be .
o High observability → changes on that node can be ● Capture close to the RTL.
seen at some observation point. ● Automatically detect protocol violations and corner‑case bugs.

40
● Improve – failures point directly to violated 12. Differentiate between Mailbox and Queue.
property.
● Can be reused in formal tools for exhaustive checking. - Class‑based communication channel between
threads/components. - Methods: put, get, try_put, try_get, peek, num. -
Types: (single‑cycle, procedural) and (temporal, put/get can be ; used for synchronization + data transfer.
multi‑cycle SVA).
[$]) - Built‑in dynamic container inside one process. - Methods:
push_front, push_back, pop_front, pop_back, insert, delete. - No blocking
semantics; just stores data.
8. Differentiate between fork-join, fork-join_none and
So:
fork-join_any.
,
.
Assume:

fork
task1(); 13. Differentiate between Task and Function.
task2();
join // or join_any / join_none
- Executes in (no @, #, wait, fork). - Can be
used in expressions and RHS of assignments. - Returns a single value or
● fork...join – Parent waits until child threads finish. void.

● fork...join_any – Parent waits until child finishes; - May contain and can run for multiple cycles. -
remaining threads are . Cannot be used in expressions; called as a statement. - Can have multiple
input/output/inout arguments.
● fork...join_none – Parent ; child threads continue
in background while parent proceeds. Example:

function int add(int a, b); return a + b; endfunction


9. Write a constraint to generate Odd Numbers task delay_print(int v); #10 $display("v=%0d", v); endtask
for a rand variable.
class odd_num;
rand int x;
constraint c_odd { x % 2 == 1; }
endclass
// x is odd 14. Explain TB Architecture in SystemVerilog.
A typical (often UVM‑style) has:
You can also restrict range:

constraint c_range { x inside {[1:99]}; x % 2 == 1; }


● – connects TB classes to DUT pins.
● – class representing one operation.
● – creates a stream of transactions, often
randomized.
10. Write a constraint to generate a number ● – converts transactions to pin‑level activity on
between 34 to 57. interface.
class range_34_57; ● – passively samples interface signals and reconstructs
rand int x; transactions.
constraint c_range { x inside {[34:57]}; }
endclass ● – predicts expected results and
compares with DUT output.
● – covergroups to measure functional
coverage.
11. Write a snippet to assign the values and print ● – hierarchically builds and connects these
it with two methods i.e., assign and $display. components.
● – configures environment, sets up sequences, and controls
Example using and printing: simulation.
module top;
logic a, b, y; Data flow: .

assign y = a & b; // assign statement

initial begin
a = 1; b = 0; #1;
15. What is the difference between global
$display("y = %0b", y); // $display prints with newline declaration and local declaration of variables?
a = 1; b = 1; #1; ●
$write("y = %0b ", y); // $write without newline o Visible in a wider scope (e.g., package, module, or
$display("(using display again)");
end class level).
endmodule o Can be accessed from many blocks; easier to share
but can create coupling.

41
o Declared inside a ; visible ● Works well with to measure progress.
only within that scope.
o Helps encapsulation and avoids name clashes. Example:

class pkt;
Within classes you can also use local / protected keywords to restrict rand bit [7:0] addr, data;
access from outside the class or derived classes. constraint c { addr inside {[0:15]}; }
endclass

pkt p = new();
repeat (10) begin
16. Define assertions and need of assertions in assert([Link]());
verification. $display("addr=%0h data=%0h", [Link], [Link]);
end

: Assertions are that must hold


true at specific times during simulation.
19. Explain Functional Coverage with an example.
Functional coverage measures whether from the spec
● Ensure that the DUT obeys protocols and timing relationships.
have occurred.
● Quickly flag illegal states or unexpected behavior.
● Help document the design specification. Example: 4‑bit opcode and packet length.
● Enable reuse in formal tools for exhaustive proofs.
covergroup cg @(posedge clk);
coverpoint opcode { bins all_ops[] = {[0:15]}; }
Example concurrent assertion: coverpoint length {
bins small = {[0:63]};
property p_req_gnt; bins big = {[64:255]};
@(posedge clk) req |-> ##1 gnt; }
endproperty cross opcode, length;
assert property (p_req_gnt); endgroup

cg cov = new();

Coverage report tells how many opcodes and length ranges have been
17. Explain fork-join, fork-join_any and fork-join_none
exercised and which combinations are missing.
techniques.
Already summarized in Q8; here with a bit more detail:

fork 20. What is the difference between compilation,


t1();
t2();
elaboration and runtime?
t3(); ●
join
// Parent waits for t1,t2,t3 to finish. o Source code is parsed, syntax checked, and compiled
into an intermediate simulation model.
fork ●
t1(); t2(); t3();
join_any o The compiled design hierarchy is built: modules are
// Parent waits until any one task finishes, then remaining tasks are instantiated, parameters resolved, generate blocks
killed.
expanded, and initial values set.
fork ●
t1(); t2(); t3();
o The simulator executes the model: processes run,
join_none
// Parent does not wait; all three continue; parent executes next events are scheduled, time advances, and signals
statement immediately. change according to the event schedule.

Use join when you need all results, join_any for “first response wins” Many errors (like range mismatches, missing connections) are detected at
behavior, and join_none for background threads. elaboration; dynamic behavior issues appear at runtime.

18. Explain Randomization and need of 21. What is self checking testbench?
randomization in design verification.
A automatically compares DUT outputs against
in SystemVerilog means using rand/randc variables and expected values and .
constraints with randomize() to automatically generate input stimulus.
Typically includes:
Need / advantages:
● (sequences)
● Quickly explore a of input combinations. ● to sample DUT outputs
● Find corner‑case bugs that are hard to think of manually. ●
● Together with , ensures only scenarios are ● that compares actual vs expected and logs
generated. mismatches

42
● for temporal checks
da = new[10]; // allocate 10 elements
Self‑checking is essential for regressions where manual waveform
// resize to 20 and keep old values
inspection is impossible. int tmp[];
tmp = new[20];
for (int i = 0; i < [Link](); i++)
tmp[i] = da[i];
da = tmp;
22. Define assertions and need of assertions.
Dynamic arrays are useful when the number of elements is not known at
Same as Q7/Q16, but short:
compile time but indices are dense (0..N-1).
● Assertions: executable properties that the design must satisfy.
● Needed to detect protocol violations, illegal states, and to
formalize the spec. 27. Write a Code to Randomize a Dynamic Array
of size 10 and should have Even Numbers.
23. What is Constraints? class even_da;
rand int da[];

In SystemVerilog, are declarative rules on rand/randc variables constraint c_size { [Link]() == 10; }
written inside classes with the constraint keyword. They guide the constraint c_even {
foreach (da[i]) da[i] % 2 == 0;
during randomize() so that only are }
generated. endclass

Example: initial begin


even_da e = new();
class pkt; assert([Link]());
rand bit [7:0] addr; $display("da = %p", [Link]);
rand bit wr; end
constraint c_addr { addr inside {[8'h10:8'h1F]}; }
constraint c_wr { wr == 1'b1; }
endclass

28. Write a Constraint to generate an array of


size between 10 to 20 and also generate: first
24. Explain SV Test bench Architecture. half Even Numbers and next half Odd Numbers.
class half_even_odd;
Same as Q14: class‑based architecture with rand int a[];
, grouped in , controlled
by . Mention that UVM standardizes this architecture. constraint c_size { [Link]() inside {[10:20]}; }

constraint c_pattern {
foreach (a[i]) {
if (i < [Link]()/2)
25. What is difference between Shallow Copy and a[i] % 2 == 0; // first half even
else
Deep Copy? a[i] % 2 == 1; // second half odd
}
● : copies only the handle → both handles point to the }
. Modifying through one handle affects the other. endclass

pkt p1 = new();
pkt p2 = p1; // shallow
29. What is Functional Coverage?
● : creates a and copies over contents.
(See Q19.) Short answer:
class pkt;
● User‑defined metric using covergroups that checks how much of
int a;
function pkt copy(); the has been exercised.
pkt t = new(); ● Complementary to code coverage.
t.a = this.a;
return t;
endfunction
endclass
30. Write a Constraint to generate the 2 to the
pkt p3 = [Link](); // deep power of 2 Values.
Deep copy is preferred when storing transactions for later checking. If question means generate numbers that are (1,2,4,8,…):

class pow2_vals;
rand int x;

26. Explain Dynamic Array. // allow 2^0..2^7 (1..128) as example


constraint c_pow2 {
A is an unpacked array whose . x inside {1,2,4,8,16,32,64,128};
}
int da[]; // declaration (no size yet) endclass

43
Alternatively use an exponent variable:

class pow2_alt;
rand int e;
int x;
constraint c_e { e inside {[0:7]}; }
function void post_randomize();
x = 1 << e; // x = 2^e
endfunction
endclass

(End of Set 8A)

44
The mailbox automatically handles between generator and driver.

SystemVerilog Interview Q&A – Set


8B (Q1–51) 3. What is the difference between a component
This set corresponds to the questions from images 3–7.
and an object?
In UVM/SystemVerilog verification:

1. How do two classes communicate? ●

Two classes communicate using such 1. Instance of a class that extends uvm_object or plain
as: class.
2. Created with new(), no fixed place in testbench
● – one class put()s transactions, another get()s them. hierarchy.
● – both classes hold a handle to the 3. Typically used for , configuration,
same queue or object and use methods to exchange data. sequences.
● – uvm_blocking_put_port,

uvm_blocking_get_port, etc.
o Class that extends uvm_component.
Simple mailbox example: o Part of the ; built in
class producer; build_phase() and has a parent/child relationship.
mailbox #(int) mbx; o Represents structural elements: environment, agent,
function new(mailbox #(int) mbx); [Link] = mbx; endfunction
task run(); int v; forever begin driver, monitor, scoreboard.
v = $urandom_range(0,100);
[Link](v); So: object = data / lightweight helper; component = structural TB element
end endtask with phases and hierarchy.
endclass

class consumer;
mailbox #(int) mbx;
function new(mailbox #(int) mbx); [Link] = mbx; endfunction
task run(); int v; forever begin
4. Write a code for a class to display a property
[Link](v); from calling function.
$display("Got %0d", v);
class my_class;
end endtask
int value;
endclass
function new(int v = 0); value = v; endfunction

Both classes share the same mailbox handle, hence they communicate. function void print();
$display("value = %0d", value);
endfunction
endclass

2. Explain the implementation of mailbox using a function void show_value();


pseudo code. my_class obj = new(10);
[Link]();
endfunction
Pseudo‑code:
show_value() creates the object and calls the class method to display the
mailbox #(packet) mbx = new();
property.
class generator;
mailbox #(packet) mbx;
function new(mailbox #(packet) mbx); [Link] = mbx; endfunction

task run(); 5. Write a program for a queue to perform push


packet p;
forever begin
and pop operations in class.
p = new(); class queue_ex;
assert([Link]()); int q[$];
[Link](p); // send to driver
end function void push_back(int v);
endtask q.push_back(v);
endclass endfunction

class driver; function int pop_front();


mailbox #(packet) mbx; int v = q.pop_front();
function new(mailbox #(packet) mbx); [Link] = mbx; endfunction return v;
endfunction
task run();
packet p; function void display();
forever begin $display("q = %p", q);
[Link](p); // receive from generator endfunction
// drive pins using p endclass
end
endtask initial begin
endclass queue_ex obj = new();

45
obj.push_back(10); int i, j, tmp;
obj.push_back(20);
[Link](); initial begin
$display("popped = %0d", obj.pop_front()); for (i = 0; i < 5; i++)
end for (j = i+1; j < 5; j++)
if (a[j] < a[i]) begin
tmp = a[i]; a[i] = a[j]; a[j] = tmp;
end

6. Explain different data types of SystemVerilog $display("sorted = %p", a);


Programming Language. end
endmodule

Major categories: (Or mention you can also use [Link]() for dynamic arrays / queues.)

● : bit, byte, shortint, int, longint.


● : logic, reg, integer, time.
● : real, shortreal. 11. Write a code for structure pointer, bitwise &
● : string. logical operations.
● : typedef, enum, struct, union.
SystemVerilog doesn’t have C‑style pointers for structs, but you can use a
● .
or a struct variable and operate on its fields.
● : event, mailbox, semaphore, process, chandle.
● : fixed, dynamic, associative, queues (packed/unpacked). Example using bitwise & logical ops:

typedef struct packed {


bit [3:0] a;
7. Explain different types of arrays of bit [3:0] b;
SystemVerilog Programming Language. } s_t;

● : size known at compile time. module top;


s_t s;
● : size decided at runtime using new[].
bit [3:0] and_r;

● : indexed by arbitrary key type (int, string,


initial begin
s.a = 4'b1100;
packed array, class handle). s.b = 4'b1010;

● `**)**: ordered collection withpush/pop` operations. and_r = s.a & s.b; // bitwise AND
if (|and_r) // logical test using reduction OR
● Each of the above can be or based on $display("and_r = %b", and_r);
declaration. end
endmodule

If interviewer insists on “pointer” concept, you can say: use class handles
8. Differentiate between dynamic array, or ref arguments.
associative array and queue.
● : contiguous indices 0..size-1, resizable with
new[]. Good when number of items known but calculated at 12. Explain Mailbox and its methods.
runtime.
Mailbox is a between
● : indexed by key type; sparsely populated; threads/components.
supports exists, first, next for traversal.
Declaration:
● `**)**: ordered list;
supportspush_front,push_back,pop_front,pop_back`; good for mailbox mbx; // untyped
FIFO/LIFO behavior. mailbox #(packet) mbx_p; // typed

Key methods:

9. Differentiate between SV and Verilog HDL.


● new([int bound]) – create mailbox, optional capacity limit.
SystemVerilog is a of Verilog.
Verilog: mainly for hardware description; limited testbench ● put(item) – blocking put; waits if mailbox is full.
support; no classes, constraints, coverage, assertions.
● get(item) – blocking get; waits until item available.
SystemVerilog: adds , ,
, , , , ● try_put(item) – non‑blocking; returns 1 on success, 0 if full.
advanced data types, and supports .
● try_get(item) – non‑blocking; 1 on success, 0 if empty.
All valid Verilog code is (almost) valid SystemVerilog, but not
vice‑versa. ● peek(item) – read next item without removing.

● num() – number of items present.


10. Write a code to sort 5 elements in an array.
module sort5;
int a[5] = '{5, 3, 1, 4, 2}; 13. How does the following thread execute?
46
17. Differentiate between mailbox and queue.
You can explain using events or join ordering:
(Already covered in Set 8A Q12.) Summarize:
class A; task run(); ... endtask endclass
class B; task run(); ... endtask endclass
class C; task run(); ... endtask endclass ● Mailbox: class‑based, blocking put/get, used for communication
A a; B b; C c;
between threads.

initial begin
● Queue: dynamic array [$], non‑blocking, used as data structure
a = new(); b = new(); c = new(); inside a thread.

fork
begin [Link](); [Link](); [Link](); end
join 18. Explain polymorphism and its application.
end
Polymorphism: base‑class handle refers to different derived objects; calling
Or using events to signal completion: virtual method invokes derived implementation.
event ea, ec;
Application: in UVM, many APIs use base types (uvm_sequence,
// in main thread uvm_driver), but actual behavior comes from derived classes selected by
fork factory or configuration (e.g., different protocol drivers, different
begin [Link](); ->ea; end sequences) without changing testbench structure.
begin @ea; [Link](); ->ec; end
begin @ec; [Link](); end
join

Describe in words: we can chain tasks using events so that A must finish 19. Which is the default array used in
before C starts, and C must finish before B. SystemVerilog?
When you declare an array without explicitly specifying packed/unpacked,
you usually refer to . Some interviewers also expect:
14. Write a code to generate odd numbers using is default choice in verification when number of elements is
constraints. not fixed. A safe short answer:
class odd_c;
rand int x; Default normal array in SV is an with index
constraint c_odd { x % 2 == 1; } range specified to the right of the variable name.
endclass

To generate multiple odd numbers in an array:


20. Differentiate between bit [7:0] and byte.
class odd_arr;
rand int a[];
constraint c_sz { [Link]() == 10; }
● bit [7:0] – 8‑bit vector, unsigned.
constraint c_odd
endclass
{ foreach (a[i]) a[i] % 2 == 1; }
● byte – 8‑bit integer (range −128..+127).

Arithmetic on byte uses signed interpretation, while bit [7:0] is treated as


unsigned vector unless cast.
15. Write a constraint to declare an array with
specific size and generate unique numbers in the
array.
class unique_arr;
rand int a[];
constraint c_size { [Link]() == 8; }
constraint c_uniq { unique { a }; }
endclass

unique {a} ensures all elements have different values.

16. Differentiate between shallow copy and deep


copy.
● : copy handle → both handles refer to object.
● : create new object and copy all fields; two
objects.

Explain with

simple code as in previous sets.

47

You might also like