SystemVerilog를
이용한 검증 방법론
Verification Methodologies
.lan
aanear ane
S lee @ ,
Hardware Security Laboratory Largely based on slides of Prof. Hsiung
Verification
“ ... the industry is just beginning to fathom the
scope of the challenges confronting those who
integrate blocks of reusable IP on large chips.
Most of the participants summed up the
toughest challenge in one word: verification.”
Source: EE Times (Jan. 20, 1997)
Report on Design Reuse and IP Core Workshop
Organized by DARPA, EDA Industry Council, NIST
Hardware Security Laboratory
Verification Challenges
Verification goals
functionality, timing, performance, power, physical
Design complexity
MPUs, MCUs, DSPs, AMS IPs, ESW, clock/power distribution, test
structures, interface, telecom, multimedia
Hardware Security Laboratory
Verification Challenges
Diversity of blocks (IPs/Cores)
different vendors
soft, firm, hard
digital, analog, synchronous, asynchronous
different modeling and description languages - C,
Verilog, VHDL
software, firmware, hardware
Different phases in system design flow
specification validation, algorithmic, architectural,
hw/sw, full timing, prototype
Hardware Security Laboratory
Costs in Finding/fixing Bugs
System
Time to
fix a
bug
Module
Block
Design integration stage
• Increase in chip NREs make respins an unaffordable proposition
RESPIN • Average ASIC NRE ~$122,000
• SoC NREs range from $300,000 to $1,000,000 NRE=non-recurring engineering
Hardware Security Laboratory
Getting Worse in Deep Sub-Micron
Timing Closure
Sensitive to interconnect delays
Large Capacity
Hierarchical design and design reuse
Physical Properties
Signal integrity
(crosstalk, IR drop, power/ground bounce)
Design integrity
(electron migration, hot electron, wire self-heating)
Hardware Security Laboratory
Physical Issues in DSM
Interconnects
Signal Integrity
P/G integrity
Substrate coupling
Crosstalk
Parasitic Extraction
Reduced Order Modeling
Manufacturability and Reliability
Power Estimation
Hardware Security Laboratory
Interconnect Issues in DSM
tvam 670%
tvanaister
.
Scaling technology
wjve 20 % .
wire
They get longer and longer
Increasing complexity
New materials for low resistivity
Inductance and capacitance become more relevant
Larger and larger impact on the design
Need to model them and include them in the design choices
(gate-centric to interconnect-centric paradigm)
Hardware Security Laboratory
P/G and Substrate
Analog and digital blocks may share supply network and substrate
Can I just plug them together on the same chip? Will it work?
The switching activity of digital blocks injects noise current that may “kill”
analog sensitive blocks
Digital IP
Analog
Hardware Security Laboratory
Crosstalk
In DSM technologies, coupling capacitance dominates interlayer capacitance
there is a “bridge” between interconnects on the same layer….they interfere with each other!
wine
Hardware Security Laboratory
Reduced Order Modeling
Increasing complexity bigger and more complex models
E.g. supply grid, parasitics…
Need to find a “reduced” model so that
Still good representation
Manageable size
Hardware Security Laboratory
Manufacturability
Design a chip
Send it to fabrication
…….
Did I account for the fabrication process variations?
How many of my chips will work?
Just one? All? Most of them?
How good is my chips performance?
Design and verification need to account for process variations!
Hardware Security Laboratory
Reliability
Design a chip
Send it to fabrication
…….
Did I test my design for different kinds of stress?
Is it going to work even in the worst case?
Can I sell it both in Alaska and Texas?
Hardware Security Laboratory
Power Estimation
Advent of portable and high-density circuits
power dissipation of VLSI circuits becomes a
critical concern
Accurate and efficient power estimation
techniques are required
Hardware Security Laboratory
Hardware Security Laboratory
Verification Methods
Simulation Technologies
Static Technologies
Physical Verification and Analysis
Formal Technologies
Hardware Security Laboratory
Simulation Technologies
Event-driven Simulators
Cycle-based Simulators
Rapid Prototyping Systems
Emulation Systems
Speeding up Simulators (C, BFM, ISS,…)
Testing & Coverage-driven Verification
Assertion-based Verification
HW/SW Cosimulation
AMS Modeling and Simulation
Hardware Security Laboratory
Hardware Simulation
Event-driven
compiled code
native compiled code (directly producing optimized object code)
very slow
+ asynchronous circuits, timing verification, initialize to known state
S S
Cycle-based t C L
t
o o
+ faster (3-10x than NCC) a m g a
synchronous design, no timing t b. i
c t
verification,
cannot handle x,z states e e
clock
Hardware Security Laboratory
Performance vs Abstraction
Cycle-based
Simulator
Event-driven
Abstraction
Simulator
SPICE
.001x 1x 10x
Performance and Capacity
Hardware Security Laboratory
Validating SoC by Simulation
Need for both cycle-based and event-driven
asynchronous interfaces
verification of initialization
verification of buses, timing
Need for mixed VHDL/Verilog simulators
IP from various vendors
models in different languages
SoC verification not possible by current simulation tools
Growing gap between amount of verification desired and amount that can be done
1 million times more simulation load than chip in 1990 (Synopsys)
Hardware Security Laboratory
Rapid Prototyping Systems
Firmware Design
Source Object
Algorithm
Code Code
In Circuit
Emulator(ICE)
Integration Test
Behavior RTL GATE
Hardware Design
Hardware Security Laboratory
Enhancing Simulation Speed
Hardware model
Behavioral model in C
Bus-functional model (BFM)
Instruction-set simulation (ISS) model
instruction accurate
cycle accurate
Full-timing gate-level model
encrypted to protect IP
Hardware Security Laboratory
Testbench
Verification environment
Commonly referred as testbench
Definition of a testbench
A verification environment containing a set of components [such as bus
functional models (BFMs), bus monitors, memory modules] and the
interconnect of such components with the design under-verification
(DUV)
Verification (test) suites (stimuli, patterns, vectors)
Test signals and the expected response under given testbenches
Hardware Security Laboratory
Testbench Design
Auto or semi-auto stimulus generator is preferred
Automatic response checking is highly recommended
May be designed with the following techniques
Testbench in HDL
Testbench in programming language interface (PLI)
Waveform-based
Transaction-based
Specification-based
Hardware Security Laboratory
Coverage-driven Verification
Coverage reports can indicate how much of the design has
been exercised
Point out what areas need additional verification
Optimize regression suite runs
Redundancy removal (to minimize the test suites)
Minimizes the use of simulation resources
Quantitative sign-off (the end of verification process) criterion
Verify more but simulate less
Hardware Security Laboratory
Static Technologies
Inspection and Lint Checking
Static Timing Analysis
Hardware Security Laboratory
Inspection & Lint Checking
For designers, finding bugs by careful inspection is often faster
than that by simulation
Inspection process
Design (specification, architecture) review
Code (implementation) review
Line-by-line fashion
At the sub-block level
Lint-liked tools can help spot defects without simulation
Nova ExploreRTL, VN-Check, ProVerilog, …
Hardware Security Laboratory
HDL Linter
Fast static RTL code checker
Preprocessor of the synthesizer
RTL purification (RTL DRC)
Syntax, semantics, simulation
Check for built-in or user-specified rules
Testability checks
Reusability checks
……
Shorten design cycle
Avoid error code that increases design iterations
Hardware Security Laboratory
Static Timing Analysis (STA)
STA is a method for determining if a circuit meets timing constraints (setup,
hold, delay) without having to simulate
No input patterns are required
100% coverage if applicable
Challenging: multiple sources
Reference :Synopsys
Hardware Security Laboratory
Physical Verification & Analysis
Issues for physical verification:
Timing
Signal Integrity
Crosstalk
IR drop . 2 v Ina =
:
U . m
.
1
-
f
-/U
=
Electro-migration
Power analysis
Process antenna effects
Phase shift mask
Optical proximity correction
Hardware Security Laboratory
Device Test
To check if devices are manufactured defect-free
Focus on structure of chip
Wire connections
Gate truth tables
Not functionality
Hardware Security Laboratory
Device Test
Challenges in SoC device test:
Test Vectors: Enormous!
Core Forms: soft, firm, hard, diff tests
Cores: logic, mem, AMS, …
Accessibility: very difficult / expensive!
Hardware Security Laboratory
Device Test Strategies
Logic BIST (Built-In-Self-Test)
Stimulus generators embedded
Response verifiers embedded
Memory BIST
On-chip address generator
Data generator
Read/write controller (mem test algorithm)
Mixed-Signal BIST
For AMS cores: ADC, DAC, PLL
Scan Chain
Timing and Structural compliance
ATPG tools generate manufacturing tests automatically
Hardware Security Laboratory
Formal Technologies
Formal Verification: An analytic way of proving a system correct
no simulation triggers, stimuli, inputs
no test-benches, test-vectors, test-cases
Deductive Reasoning (theorem proving)
Model Checking
Equivalence Checking
Hardware Security Laboratory
Theorem Proving
Uses axioms, rules to prove system correctness
No guarantee that it will terminate
Difficult, time consuming: for critical applications only
Not fully automatic
FSU 6
Hardware Security Laboratory
,
Model (Property) Checking
Algorithmic method of verifying correctness
of (finite state) concurrent systems
against temporal logic specifications
A practical approach to formal verification
Hardware Security Laboratory
Model Checking
What is necessary for Model Checking?
A mathematically precise model of the system
A language to state system properties
A method to check if the system satisfies the given properties
Hardware Security Laboratory
Equivalence Checking
Checks if two circuits are equivalent
Register-Transfer Level (RTL)
Gate Level
Reports differences between the two
Used after:
clock tree synthesis
scan chain insertion
manual modifications
Hardware Security Laboratory
Formal Verification Issues
State-space explosion!!!
Cannot handle large systems!
For control-oriented behavior of small modules
For interface-centric verification
Constrained for feasible verification
Supplementary to simulation
Counterexample simulation trace
Hardware Security Laboratory
Comparing Verification Options
Hardware Security Laboratory
Requirements
Requirement: Desirable property of the executions of the system
Informal: Either implicit, or stated in English in documents
Formal: Stated explicitly in a mathematically precise manner
High assurance / safety-critical systems: Formal requirements
Model/design/system meets the requirements if every execution
satisfies all the requirements
Clear separation between requirements (what needs to be
implemented) and system (how it is implemented)
Verification problem: Given a requirement φ and a system/model C,
prove/disprove that the system C satisfies the requirement φ
Hardware Security Laboratory
Transition Systems
States + Initial states + Transitions between states
Hardware Security Laboratory
Definition of Transition System
Syntax: a transition system T has
A set S of (typed) state variables
Initialization Init for state variables
Transition description Trans given by code to update state vars
Semantics:
Set QS of states
Set [Init] of initial states (this is a subset of QS)
Set [Trans] of transitions, subset of QS x QS
Synchronous reactive components, programs, and more
generally systems, all have an underlying transition system
Hardware Security Laboratory
Switch Transition System
(press=0 & x<10)
(press=0) ? x:=x+1
(press=1) ?
int x:=0 State variables:
off on
{off, on} mode, int x
(press=1 | x>=10)
x:=0
Initialization:
(off,0) (on, 56) mode = off; x = 0
Transitions:
(on, 0) (on, 2) (off,n) -> (off,n);
(off,n) -> (on,n);
(on, 3) (on,n) -> (on,n+1) if n<10;
(off, 17) (on,n) -> (off,0)
(on, 17)
Hardware Security Laboratory
Reachable States
(press=0 & x<10)
(press=0) ? x:=x+1
(press=1) ?
int x:=0
off on
(press=1 | x>=10)
x:=0
(on, 56)
(off,0)
(on, 0) (on, 1) (on, 10)
(off, 17)
(on, 17)
Hardware Security Laboratory
Reachable States of Transition Systems
A state s of a transition system is reachable if there is an execution
starting in an initial state and ending in the state s
Hardware Security Laboratory
Invariants
(on, 56)
(off,0)
(on, 0) (on, 1) (on, 10)
(off, 17) (off, 10)
(on, 17)
Property of a transition system: Boolean-valued expression φ over state variables
Property φ is an invariant of T if every reachable state satisfies φ
Examples of invariants: (x <= 10); (x <= 50); (mode= off -> x=0)
Examples of properties that are not invariants: (x < 10); (mode=off)
Hardware Security Laboratory
Formal Verification
Model/Program yes/proof
Verifier
Requirement no/bug
Grand challenge:
Automate verification as much as possible !
Hardware Security Laboratory
Analysis Techniques
Dynamic Analysis (runtime)
Execute the system, possibly multiple times with different inputs
Check if every execution meets the desired requirement
Static Analysis (design time)
Analyze the source code or the model for possible bugs
Trade-offs
Dynamic analysis is incomplete, but accurate (checks real system, and
bugs discovered are real bugs
Static analysis can catch design bugs early !
Many static analysis techniques are not scalable (solution: analyze
approximate versions, can lead to false warnings)
Hardware Security Laboratory
Invariant Verification
Simulation
Simulate the model, possibly multiple times with different inputs
Easy to implement, scalable, but no correctness guarantees
Proof based
Construct a proof that system satisfies the invariant
Requires manual effort (partial automation possible)
State-space analysis (Model checking)
Algorithm explores “all” reachable states to check invariants
Not scalable, but current tools can analyze many real-world designs
(relies on many interesting theoretical advances)
Hardware Security Laboratory
Proving Invariants
Given a transition system (S, Init, Trans), and a property φ, prove
that all reachable states of T satisfy φ
Inductive definition of reachable states
All initial states are reachable using 0 transitions
If a state s is reachable in k transitions and (s,t) is a transition, then the state t
is reachable in (k+1) transitions
Reachable = Reachable in n transitions, for some n
Prove: for all n, states reachable in n transitions satisfy φ
Base case: Show that all initial states satisfy φ
Inductive case:
Assume that a state s satisfies φ
Show that if (s,t) is a transition then t must satisfy φ
Hardware Security Laboratory
Inductive Invariant
A property j is an inductive invariant of transition system T if
Every initial state of T satisfies φ
If a state satisfies φ and (s,t) is a transition of T, then t must satisfy φ
If φ is an inductive invariant, then all reachable states of T must
satisfy φ, and thus, it is an invariant
Hardware Security Laboratory
Proving Inductive Invariant Example
Consider transition system T given by
State variable int x, initialized to 0
Transition description given by “if (x < m) then x:=x+1”
Is the property φ : (0 <= x <= m) an inductive invariant of T ?
Base case: Consider initial state (x=0). Check that it satisfies φ
Inductive case: xk .
Consider an arbitrary state s, suppose s(x) = a
Assume that s satisfies φ, that is, assume 0 <= a <=m
Consider the state t obtained by executing a transition from s
If a < m then t(x) = a+1, else t(x) = a
In either case, 0 <= t(x) <= m
So t satisfies the property φ, and the proof is complete
Hardware Security Laboratory
Inductive Invariants
Initial
States
Property j
Reachable
States
Strengthening y
Hardware Security Laboratory
Muddy Children’s Puzzle
There are some kids playing in a muddy pond. Their teacher
walks by and says “some of you have mud on your forehead”.
Each kid can look around and see which of other kids have
muddy foreheads, but cannot see his/her own forehead. The
teacher says “raise your hand if you know that you have muddy
forehead”. Nobody raises their hands. The teacher repeats the
same question, and it continues like that. If k kids have muddy
foreheads, then after the teacher has asked the question k
times, exactly those kids with muddy foreheads raise their
hands.
Hardware Security Laboratory
Muddy Children’s Reasoning
Claim: For all n, if exactly n kids have muddy foreheads, then
(1) for first n-1 rounds nobody raises their hands and
(2) after n rounds, exactly those kids with muddy foreheads raise their hands.
Proof by induction.
Base case: Show the claim for n=1
Inductive hypothesis: Assume the claim for n=k
Inductive case: Show the claim for n=k+1
Note: We want to prove (2), but it cannot be proved on its own.
Proving (1) and (2) together is akin to inductive strengthening
Hardware Security Laboratory
Verification
Guidelines
SystemVerilog for Verification
Hardware Security Laboratory
Verification != Simulation/Testing
bug
buy
Model/Program yes/proof
Verifier
Requirement no/bug
Program testing can be used to show the presence of
bugs, but never their absence!
Edsger W. Dijkstra
Hardware Security Laboratory
Directed Verification
• Defines DUT states to be tested based on spec behavior and corner cases
• Writes directed test to verify each item in Test Plan
• If the design changes, we have to redo everything or big part of the testing.
• You can find only the bacteria for which you have provided reagent.
• Significant manual effort to write all the tests!
Hardware Security Laboratory
Directed Testing
Hardware Security Laboratory
Constrained Random Verification
• Verification engineer
• Defines DUT states to be tested based on spec behavior (the function to be implemented) and corner cases (edge
values and function discontinuities)
• Focus moves to reaching goal areas (creative),
versus execution of test lists (brute force)
• Non-goal state
• Constrained-random stimulus generation explores goal areas (& beyond) Stimuli are automatically generated,
based on the constraints specified by VE
Hardware Security Laboratory
Constrained Random Testing
,
Hardware Security Laboratory
Coverage
Hardware Security Laboratory
Constrained Random Stimulus
Hardware Security Laboratory
Coverage Convergence
Hardware Security Laboratory
What to Randomize
• Device configuration
• Environment configuration
• Input data
• Protocol exceptions
• Delays
• Errors and violations
Hardware Security Laboratory
Coverage Measurement
• Coverage is a simulation metric we use to measure verification
progress and completeness
Hardware Security Laboratory
Testbench Components
Hardware Security Laboratory
Layered Testbench
Hardware Security Laboratory
Data Types
SystemVerilog for Verification
Hardware Security Laboratory
New Data Types in SystemVerilog
• Two-state
• Better performance, reduced memory usage
• Queues, dynamic and associative arrays and automatic storage
• Reduced memory usage, built-in support for searching and sorting
• Unions and packed structures
• Allows multiple views of the same data
• Classes and structures
• Support for abstract data structures
• Strings
• Built-in string support
• Enumerated types
• Code is easier to write and understand
Hardware Security Laboratory
Logic type
• Which to use, reg? wire?
logic!
• The logic type can be
used
• Variables
• Continuous assignments
• Gates and modules
• But, cannot be driven by
multiple drivers wire
Gate only wine .
Hardware Security Laboratory
Two-State Variables
• Two states (0 or 1) vs. four states (0, 1, Z or X)
• Need to be careful
• The range of the byte variable is -128 to 127 (not 0 to 255)
• What if you assign a four-state variable to a two-state variable??
Hardware Security Laboratory
Declaration of Arrays
• Fixed-sized arrays
• Multidimensional arrays
Hardware Security Laboratory
Initialization of Arrays
warilog
Systen
Hardware Security Laboratory
Iteration: for and foreach
Hardware Security Laboratory
Lab 1: foreach and Indexing
program test;
initial begin
int md[2][3]='{'{0,1,2}, '{3,4,5}};
$display("Initial value:");
foreach(md[i,j])
$display("md[%0d][%0d]=%0d", i, j, md[i][j]);
end
endprogram
Initial valie
:
md [ ] [ ] =0
00 o o
.
[3
o 3
[oJ [2] =α
1 0 =
3
. 1
=
4
| 2
=
5
Hardware Security Laboratory
Lab 2: Aggregate Operations
program test;
initial begin
bit [31:0] src[5] = ’{0,1,2,3,4},
dst[5] = ’{5,4,3,2,1};
// Aggregate compare the two arrays
if (src==dst)
$display("src == dst");
else
$display("src != dst");
// Aggregate copy all src values to dst
dst = src;
// Change just one element
src[0] = 5;
// Are all values equal (no!)
$display("src %s dst", (src == dst) ? "==" : "!=");
// Are last elements 1-4 equal (yes!)
$display("src[1:4] %s dst[1:4]",
(src[1:4] == dst[1:4]) ? "==" : "!=");
end
endprogram
Hardware Security Laboratory
Dynamic Arrays
garbagecollecar
Hardware Security Laboratory
Lab 3: Queue
program test;
initial begin
8 0
o
int j = 11;
int q[$] = {10, 12, 15};
"
q.insert(1, j); // {10, 11, 12, 15} Insert 11 before 12
5
q.delete(2); // {10, 11, 15} Delete an element.
foreach (q[i])
0
$display(q[i]);
" q.push_front(16); // {16, 10, 11, 15} Insert at front
j = q.pop_back; // {16, 10, 11} j = 15
7 q.push_back(17); // {16, 10, 11, 17} Insert at back
j = q.pop_front; // {10, 11, 17} j = 16
foreach (q[i])
$display(q[i]);
end
endprogram
Hardware Security Laboratory
Lab 4: Associative Array
memory program test;
( Index value) initial begin
assoc :
logic [63:0] assoc[*], idx = 1;
.
repeat (64) begin
assoc[idx] = idx;
idx = idx << 1;
end
foreach (assoc[i])
$display("assoc[%h] = %h", i, assoc[i]);
end
endprogram
Hardware Security Laboratory
Associative Array Functions
First
elemeat id
×
Hardware Security Laboratory
String Index
Hardware Security Laboratory
Array Reduction
sum
product
and
or
xor
Hardware Security Laboratory
Array Locator
Hardware Security Laboratory
Lab 5: Find
program test;
initial begin
9
0
. .
int d[] = '{9, 1, 8, 3, 4, 4}, tq[$];
tq = d.find with (item >3); q
foreach(tq[i]) 4
$display(tq[i]);
4
end
endprogram
Hardware Security Laboratory
Find
Hardware Security Laboratory
typedef
• Old style
• New style
• Example
Hardware Security Laboratory
Structure
• Struct
• Packed
• Union
Hardware Security Laboratory
Enumeration
• Simple definition = 0, 1, 2 reaeling
• Specifying a value
• Incorrect specification
• Corrected one
0 .
The position variable is initialized 0, which is an illegal value of ordinal_e
Hardware Security Laboratory
Routines for Enumerated Types
• first
• last
• next
• next(N)
• prev
• prev(N)
Hardware Security Laboratory
Lab 6: Casting Enumerated Types
* .
program test;
← initial begin
typedef enum {RED, BLUE, GREEN} COLOR_E;
COLOR_E color, c2;
.
>
Castlag integer c;
c = color; // Convert from enum to integer
.
.
color is O / RED
c2 = COLOR_E'(c); // No type checking done
Color is | / BLUE
$display("Color is %0d / %0s", c2, c2.name);
c++; // Increment integer
if (!$cast(color, c)) // Cast integer back to enum
$display("Cast failed for c=%0d", c);
$display("Color is %0d / %0s", color, color.name);
end
endprogram
Hardware Security Laboratory
Lab 7: String
program test;
‰ ☆
initial begin
SUST MVERILOG string s;
s tesn s = "SystemVerilog";
@o : hy stemverilog
2 .
ga 42 $display(s.getc(0)); // Display: 83 (‘S’)
$display(s.toupper()); // Display: SYSTEMVERILOG
s = {s, "3.1b"}; // "SystemVerilog3.1b"
s.putc(s.len()-1, "a"); // change b-> a
$display(s.substr(2, 5)); // Display: stem
// Create temporary string, note format
my_log($psprintf("%s %5d", s, 42));
end
task my_log(string message);
// Print a message to a log
$display("@%0d: %s", $time, message);
endtask
endprogram
Hardware Security Laboratory
Procedural
Statements and
Routines
SystemVerilog for Verification
Hardware Security Laboratory
Lab 1: New Procedural Statements
Sum 45
0
=
. .
program test;
initial
begin : example // Begin label
integer array[10], sum, j;
// Declare i in for statement
for (int i=0; i<10; ++i) // Increment i
array[i] = i;
// Add up values in the array
sum = array[9];
j=8;
do // do...while loop
sum += array[j]; // Accumulate
while (j--); // Test if j=0
$display("Sum=%4d", sum); // %4d - specify width
end : example // End label
endprogram
Hardware Security Laboratory
break and continue
Hardware Security Laboratory
Verilog tasks and functions
• Task
• Can consume time
• Delay, #100
• Blocking statement, wait(ready)
• Function
• Cannot consume time
• Cannot call a task
• Must return a value
• SystemVerilog improvement
• Void function is supported, which can be called by any tasks and functions
Hardware Security Laboratory
Routine begin…end Removed
Hardware Security Laboratory
Routine Arguments
impet a !
logile as π
☆T
b!
impart 16 bit U
autp oot
:
=
logie bs
1 bit input logic
Hardware Security Laboratory
ref
Call by reference
Hardware Security Laboratory
Lab 2: Default Argument Values
program test;
function void print_sum (ref int a[],
input int start = 0,
input int last = -1);
int sum;
① 1 .
sum = 0; )
if (last == -1 || last > a.size)
last = a.size;
for (int i=start; i<last; i++)
sum += a[i];
$display("The sum of the arrays is ", sum);
endfunction
int x[] = '{1, 2, 3, 4, 5};
initial
begin
print_sum(x); // Sum x[0:size] – default
0
The sauw of the is 5
. .
arrays
print_sum(x, 2, 5); // Sum x[2:5] 2
print_sum(x, 1); // Start at 1 4
print_sum(x,, 3); // Sum x[0:3] "
6
end
endprogram
Hardware Security Laboratory
Lab 3: Local Data Storage
program test;
function void print_sum (ref int a[],
input int start = 0,
input int last = -1);
,
int sum = 0; 11
,
3
.
if (last == -1 || last > a.size)
last = a.size;
for (int i=start; i<last; i++)
sum += a[i];
$display("The sum of the arrays is ", sum);
endfunction
int x[] = '{1, 2, 3, 4, 5};
initial
begin 0
the sccae
~ ia 5
print_sum(x); // Sum x[0:size] – default
. .
print_sum(x, 2, 5); // Sum x[2:5] 45
47
print_sum(x, 1); // Start at 1 .
print_sum(x,, 3); // Sum x[0:3]
end
endprogram
Hardware Security Laboratory
Lab 4: Automatic
staak
program automatic test; // ,
function void print_sum (ref int a[],
input int start = 0,
input int last = -1);
int sum = 0;
if (last == -1 || last > a.size)
last = a.size;
for (int i=start; i<last; i++)
sum += a[i];
$display("The sum of the arrays is ", sum);
endfunction
int x[] = '{1, 2, 3, 4, 5};
initial
begin
print_sum(x); // Sum x[0:size] – default
print_sum(x, 2, 5); // Sum x[2:5]
print_sum(x, 1); // Start at 1
print_sum(x,, 3); // Sum x[0:3]
end
endprogram
Hardware Security Laboratory
Return
Hardware Security Laboratory
Time Scale
• Using `timescale
• Files must be compiled in order especially if different scales are used in
different files
• Improvement
delay FQ
Hardware Security Laboratory
Basic OOP
SystemVerilog for Verification
Hardware Security Laboratory
OOP Terminology
• Class – a basic building block containing routines and variables. The analogue in
Verilog is a module.
• Object – an instance of a class. In Verilog, you need to instantiate a module to
use it.
• Handle – a pointer to an object. In Verilog, you use the name of an instance when
you refer to signals and methods from outside the module. An OOP handle is like
the address of the object, but is stored in a pointer that can only refer to one type.
• Property – a variable that holds data. In Verilog, this is a signal such as a register
or wire. L∞ : member
ber
tmewa
• Method – the procedural code that manipulates variables, contained in tasks and
0
functions. Verilog modules have tasks and functions plus initial and always blocks.
• Prototype – the header of a routine that shows the name, type, and argument list.
The body of the routine contains the executable code.
Hardware Security Laboratory
SystemVerilog class
Hardware Security Laboratory
Instantiation :
.
Hardware Security Laboratory
Lab 1: Instantiation with Arguments
β
program test;
0
. .
Adaler : 0 000 000
class BusTran; [) auta [ o 3 : oar ro warw
5
logic [31:0] addr, crc, data[4]; Rata 13 : "
initirlize .
7a n tan t 23 ÷ ∵
s
function new(logic [31:0] addr=3, d=5); Batha I "
this.addr = addr; / argeseat 1 Alelen s oer wowooca
foreach (data[i]) Razan t 8 ] : "
[
data[i] = d; :
.
"
.
[ 23 =
"
endfunction - 3] :
Adaler oooraoos
function void display(); (Bata od : oroowoo
$display("Addr: %h", addr); "
[ .
foreach (data[i]) : "
33 s
$display("Data[%d]: %h", i, data[i]);
"
endfunction
endclass
initial begin
BusTran a, b, c;
a = new(); 11 # func
newo
#
C) -
new
2☆1
.
a.display();
b = new(10); // carg haneor (
I Asldr .
b.display();
c = new(1, 1); Aodela ,
c.display();
end
endprogram
Hardware Security Laboratory
Σ
new() vs new[]
• new()
• Instantiation of a class
• May have arguments
• new[]
• Instantiation of an array
Hardware Security Laboratory
Handles
.
objeatcpX .
Hardware Security Laboratory
Deallocation
,
obj ectl
. objeafl
af obbecgs
• Differences from C++
• Type-safe
• A SystemVerilog handle can only point to objects of one type
• Automatic garbage collection
• SystemVerilog keeps track of the number handles that point to an object
Hardware Security Laboratory
Lab 2: Static Variable
besoand id
Initialized in the declaration
8
= 1 count
=
,
.
program test;
class BusTran;
static int count = 0; // Number of objects created
int id; // Unique instance ID
function new;
id = count++; // Set ID, bump count
endfunction
endclass
BusTran b1, b2;
initial begin
b1 = new; // First instance, id=0
b2 = new; // Second instance, id=1
$display("Second id=%d, count=%d", b2.id, b2.count);
end
endprogram
Hardware Security Laboratory
Defining Routines Outside of the Class
// Prototype ,
1/ .
Hardware Security Laboratory
Name Scope :
Hardware Security Laboratory
this
Hardware Security Laboratory
Using One Class Inside Another
Hardware Security Laboratory
Compilation Order
Class
"
apedef
"
Statis tics ,
Hardware Security Laboratory
Lab 3: Passing Objects
program test;
class BusTran;
int addr, data;
endclass
task transmit(BusTran bt);
$display("BusTran %0d, %0d is transmitted", bt.addr, bt.data);
endtask
is eransmitted
BusTran b;
0
Bus Traw 1, 2
. .
initial begin
b = new;
b.addr = 1;
b.data = 2;
transmit(b);
end
endprogram
Hardware Security Laboratory
handk
Lab 4: Modification
program test;
class BusTran;
int addr, data;
endclass
task transmit(BusTran bt);
$display("BusTran %0d, %0d is being transmitted", bt.addr, bt.data);
bt.addr = 0;
endtask
BusTran b;
initial begin
b = new;
b.addr = 1;
b.data = 2;
transmit(b);
$display("BusTran %0d, %0d has been transmitted", b.addr, b.data);
end
endprogram
Hardware Security Laboratory
Lab 5: Creation Call by value s mill
pointer .
instnntiation
X .
program test;
class BusTran;
int addr, data;
endclass
task create(BusTran bt);
bt = new;
$display("BusTran %0d, %0d is being created", bt.addr, bt.data);
endtask
BusTran b;
initial begin
create(b);
$display("BusTran %0d, %0d has been created", b.addr, b.data);
end
endprogram
Hardware Security Laboratory
Lab 6: Correct Creation
program test;
class BusTran;
int addr, data;
endclass
task create(ref BusTran bt);
bt = new;
$display("BusTran %0d, %0d is being created", bt.addr, bt.data);
endtask : OO -
BusTran b;
initial begin
create(b);
$display("BusTran %0d, %0d has been created", b.addr, b.data);
end " OO -
endprogram
Hardware Security Laboratory
Array of Handles
array instantiation
θ
Hardware Security Laboratory
Copying Objects (Shallow Copy)
arway copy
σ
-
Hardware Security Laboratory
Problem with Shallow Copy
Hardware Security Laboratory
Copy Function
Hardware Security Laboratory
Connecting the
Testbench and Design
SystemVerilog for Verification
Hardware Security Laboratory
Port Connection
CGP T
.
Tecawloge
.
Resignon
pont
Hardware Security Laboratory
Interface
Hardware Security Laboratory
Connecting Interfaces and Ports
Hardware Security Laboratory
modport
Hardware Security Laboratory
Monitor
Hardware Security Laboratory
Interface Trade-offs
Advantages Disadvantages
• An interface is ideal for design reuse. When two blocks • For point-to-point connections, interfaces with
communicate with a specified protocol using two or modports are almost as verbose as using ports with lists
more signals, use an interface. If signals are repeated of signals. But all the declarations are still in one central
over and over, as in a networking switch, use a virtual location, reducing the chance for making an error.
interface. • You must now use the interface name in addition to the
• The interface takes the jumble of signals that you signal name, possibly making the modules more
declare over and over in every module or program and verbose.
puts it in a central location, reducing the possibility of • If you are connecting two design blocks with a unique
misconnecting signals. protocol that will not be reused, interfaces may be more
• To add a new signal, you just have to declare it once in work than just wiring together the ports.
the interface, not in higher-level modules, once again • It is difficult to connect two different interfaces. A new
reducing errors. interface (bus_if) may contain all the signals of an
• Modports allow a module to easily tap a subset of existing one (arb_if), plus new signals (address, data,
signals from an interface. You can specify signal etc.). But since interfaces cannot be hierarchical, you
direction for additional checking. have to break out the individual signals and drive them
appropriately.
Hardware Security Laboratory
Clocking in an Interface
Hardware Security Laboratory
Signal Synchronization
Hardware Security Laboratory
Lab 1: Synchronized Sampling Kt datr
δ
.
interface arb_if(input bit clk);
logic [1:0] grant, request;
logic reset;
clocking cb @(posedge clk); // Declare cb
output request;
σ
input grant;
q
endclocking
modport TEST (clocking cb, output reset);
modport DUT (input request, reset, output grant); .
endinterface 8 α PUT → TESF TEST lk
.
@ O :
grant
=
@ 10 :
grawnt
= 1 T ST posedge olkal
program test(arb_if.TEST arbif);
initial begin @ ho :
graunt
=
$monitor("@%0d: grant=%h", $time, arbif.cb.grant); @ 40 4
grant
: =
#50; clocking block h1 deata
end sraupliug .
endprogram
module arb(arb_if.DUT arbif);
initial begin
arbif.grant = 1; // @ 0ns /DuT Batar
#12 arbif.grant = 2; // @ 12ns
#18 arbif.grant = 3; // @ 30ns
end
endmodule
module top;
bit clk = 1;
always #5 clk = ~clk; I .5us = … T =
lons
arb_if arbif(.*);
arb a1(.*);
test t1(.*);
endmodule : top
Hardware Security Laboratory
Lab 2: Synchronized Driving
interface arb_if(input bit clk);
logic [1:0] grant, request;
logic reset;
clocking cb @(posedge clk); // Declare cb
output request;
input grant;
endclocking
modport TEST (clocking cb, output reset);
modport DUT (input request, reset, output grant); ,
endinterface
program test(arb_if.TEST arbif); @ o :
neq
=×
initial begin
# 2 arbif.cb.request <= 3; // @ 2ns @ 10 :
req
=
3
#10 arbif.cb.request <= 2; // @ 12ns
α
@ req
=
:
to
#18 arbif.cb.request <= 1; // @ 30ns
#50 $finish; O 30 :
req
end
endprogram
module arb(arb_if.DUT arbif);
initial
$monitor("@%0d: req=%h", $time, arbif.request);
endmodule
module top;
bit clk = 1;
always #5 clk = ~clk;
arb_if arbif(.*);
arb a1(.*);
test t1(.*);
endmodule : top
Hardware Security Laboratory
Assertion
.
. √
Hardware Security Laboratory
Custom Assertion Actions
9f us agsereion
-tlom coverage
asqer
.
Hardware Security Laboratory
Concurrent Assertion
Need to specify a sampling clock
⑦
F anknown
11
request ,
① / /
Hardware Security Laboratory
Randomization
SystemVerilog for Verification
Hardware Security Laboratory
Lab 1: SystemVerilog Randomization
class rand .
program test;
class Packet;
raunel
. O -
// The random variables X 5
randc
:
,
4
rand bit [31:0] src, dst, data[8]; .
sre
11~ 14
ov 3 lom
randc bit [1:0] kind; kimd n
// Limit the values for src
constraint c {src > 10;
src < 15;}
function void display();
$display("Src: %0d, Dst: %0d, Kind: %0d", src, dst, kind);
endfunction
endclass
Packet p;
initial begin
p = new; ramedom ! ze ,
30
for(int i=0; i<10; i++) begin 19
assert (p.randomize());
,
p.display();
end
end
endprogram
Hardware Security Laboratory
Multiple Expressions
Hardware Security Laboratory
inside
Hardware Security Laboratory
Choosing from an Array
Hardware Security Laboratory
Lab 2: Permutation
program test;
class RandcInside;
int array[]; // Values to choose
randc bit [15:0] index; // Index into array
function new(input int a[]); // Construct & initialize
array = a;
endfunction
function int pick; // Return most recent pick
return array[index];
endfunction
constraint c_size {index < array.size;}
endclass
initial begin
RandcInside ri;
ri = new('{1,3,5,7,9,11,13});
repeat (ri.array.size) begin
assert(ri.randomize());
$display("Picked %2d [%0d]", ri.pick(), ri.index);
end
end
endprogram
Hardware Security Laboratory
Distribution
Hardware Security Laboratory
Dynamically Changing Distribution
Hardware Security Laboratory
Conditional Constraints
Hardware Security Laboratory
Unconstrained
Hardware Security Laboratory
Implication
Hardware Security Laboratory
Implication and Bidirectional
Hardware Security Laboratory
x before y
Solve Before
y before x
Hardware Security Laboratory
Controlling Constraint Blocks
Hardware Security Laboratory
In-line Constraints
Hardware Security Laboratory
Pre- and Post-Randomization
• SystemVerilog supports two special void functions:
pre_randomize and post_randomize
Hardware Security Laboratory
Distribution Functions
• $dist_exponential — Exponential decay
• $dist_normal — Bell-shaped distribution
• $dist_poisson — Bell-shaped distribution
• $dist_uniform — Flat distribution
• $random — Flat distribution, returning signed 32-bit random
• $urandom — Flat distribution, returning unsigned 32-bit random
• $urandom_range — Flat distribution over a range
Hardware Security Laboratory
Nonrandom Values
• You may want to manually
change some variables.
However, your stimulus values
may not be correct according
to the constraints you created
to check validity.
• If there are just a few variables
that you want to override, use
rand_mode to make them
nonrandom.
• You may also manually call
handle.randomize(null)
to check the validity.
Hardware Security Laboratory
Turn Constraints Off and On
• What if you want to have
two tests with very different
flavors of data? You could
use the implication
operators (-> or if-else)
to build a single, elaborate
constraint controlled by
nonrandom variables.
Hardware Security Laboratory
Lab 3: Randomizing Signed Variables
program test;
class SignedVars;
rand byte pkt1_len, pkt2_len;
constraint total_len {
pkt1_len + pkt2_len == 64;
}
endclass
initial begin
SignedVars sv;
sv = new;
repeat (100) begin
assert(sv.randomize());
$display("%0d, %0d", sv.pkt1_len, sv.pkt2_len);
end
end
endprogram
Hardware Security Laboratory
Lab 4: Unsigned Variables
program test;
class SignedVars;
rand logic [31:0] pkt1_len, pkt2_len;
constraint total_len {
pkt1_len + pkt2_len == 64;
}
endclass
initial begin
SignedVars sv;
sv = new;
repeat (100) begin
assert(sv.randomize());
$display("%0d, %0d", sv.pkt1_len, sv.pkt2_len);
end
end
endprogram
Hardware Security Laboratory
Lab 5: Unsigned Variables with Size Limit
program test;
class SignedVars;
rand logic [7:0] pkt1_len, pkt2_len;
constraint total_len {
pkt1_len + pkt2_len == 64;
}
endclass
initial begin
SignedVars sv;
sv = new;
repeat (100) begin
assert(sv.randomize());
$display("%0d, %0d", sv.pkt1_len, sv.pkt2_len);
end
end
endprogram
Hardware Security Laboratory
Randomizing Array Size
Hardware Security Laboratory
Using Sum of Elements
Hardware Security Laboratory
Issues with Array Constraints (#1 Trial)
Hardware Security Laboratory
Issues with Array Constraints (#2 Trial)
1 / 0 ~ 255
1/ rand
> 1024 s oer fl ③
// .
Hardware Security Laboratory
Issues with Array Constraints (#3 Trial)
3
= oweaflow
Hardware Security Laboratory
Issues with Array Constraints (#4 Trial)
over
s
flow
Hardware Security Laboratory
Issues with Array Constraints (Finally!!)
//
Hardware Security Laboratory
Lab 6: randcase
program test;
initial begin
int len;
for(int i=0; i<10; i++) begin
randcase
weigt ⑤.1: len = $urandom_range(0, 2); // 10%: 0, 1, or 2
1 lok 8: len = $urandom_range(3, 5); // 80%: 3, 4, or 5
Y 1.
1: len = $urandom_range(6, 7); // 10%: 6 or 7
←
endcase
$display("len=%0d", len);
end
end
endprogram
Hardware Security Laboratory
Lab 7: randsequence
Bison-style production rules (Backus-Naur-Form)
program test;
initial begin
for (int i=0; i<10; i++) begin
randsequence (stream) A
weight / %
5
stream : cfg_read := 1 | io_read := 2 | mem_read := 5; 1 ~ µ ~
↑ - 3 1 .
Y*
cfg_read : { cfg_read_task; } | { cfg_read_task; } cfg_read; 1/ weight
mem_read : { mem_read_task; } | { mem_read_task; } mem_read;
io_read : { io_read_task; } | { io_read_task; } io_read;
endsequence
end // for
end
task cfg_read_task;
$display("cfg_read_task");
endtask
task mem_read_task;
$display("mem_read_task");
endtask
task io_read_task;
$display("io_read_task");
endtask
endprogram
Hardware Security Laboratory
Single Random Number Generator
Hardware Security Laboratory
Separate Generators per Object
Hardware Security Laboratory
Threads and
Interprocess
Communication
SystemVerilog for Verification
Hardware Security Laboratory
In Verilog
• begin ... end
• Statements in begin and end run sequentially
• fork ... join
• Statements in fork … join run in parallel
• All statements inside fork … join must finish before moving to the
outside
• As a result, it is rare to use it for Verilog testbenches
Hardware Security Laboratory
In SystemVerilog
Hardware Security Laboratory
Lab 1: fork … join
program test;
initial begin
$display("@%0d: start fork...join example", $time);
#10 $display("@%0d: sequential after #10", $time);
$display("@%0d: parallel start", $time);
fork
#50 $display("@%0d: parallel after #50", $time);
#10 $display("@%0d: parallel after #10", $time);
begin
#30 $display("@%0d: sequential after #30", $time);
#10 $display("@%0d: sequential after #10", $time);
end
join
$display("@%0d: after join", $time);
#80 $display("@%0d: final after #80", $time);
end
endprogram
Hardware Security Laboratory
Lab 1 Output $display
program test;
#10 $display
initial begin
$display("@%0d: start fork...join example", $time); $display
#10 $display("@%0d: sequential after #10", $time);
$display("@%0d: parallel start", $time);
fork #10 $display
#50 $display("@%0d: parallel after #50", $time); (/ lhreal [
#10 $display("@%0d: parallel after #10", $time); 1/ thread
2
begin
#30 $display("@%0d: sequential after #30", $time);
#10 $display("@%0d: sequential after #10", $time);
end
) ewads #30 $display
join #10 $display
$display("@%0d: after join", $time);
#80 $display("@%0d: final after #80", $time);
end
endprogram #50 $display
@0: start fork...join example $display
iime ntap
@10: sequential after #10
@10: parallel start
@20: parallel after #10
@40: sequential after #30
@50: sequential after #10
@60: parallel after #50
@60: after join
@140: final after #80 #80 $display
Hardware Security Laboratory
Lab 2: fork … join_any
program test;
initial begin
$display("@%0d: start fork...join_any example", $time);
#10 $display("@%0d: sequential after #10", $time);
$display("@%0d: parallel start", $time);
fork
#50 $display("@%0d: parallel after #50", $time);
#10 $display("@%0d: parallel after #10", $time);
begin
#30 $display("@%0d: sequential after #30", $time);
#10 $display("@%0d: sequential after #10", $time);
end
join_any
$display("@%0d: after join", $time);
#80 $display("@%0d: final after #80", $time);
end
endprogram
Hardware Security Laboratory
Lab 2 Output $display
program test;
#10 $display
initial begin
$display("@%0d: start fork...join_any example", $time); $display
#10 $display("@%0d: sequential after #10", $time);
$display("@%0d: parallel start", $time);
fork #10 $display
#50 $display("@%0d: parallel after #50", $time);
#10 $display("@%0d: parallel after #10", $time); $display
begin
#30 $display("@%0d: sequential after #30", $time); #30 $display
#10 $display("@%0d: sequential after #10", $time);
end
join_any #10 $display
$display("@%0d: after join", $time);
#80 $display("@%0d: final after #80", $time);
end
endprogram #50 $display
@0: start fork...join_any example
@10: sequential after #10
@10: parallel start
@20: parallel after #10
@20: after join #80 $display
@40: sequential after #30
@50: sequential after #10
@60: parallel after #50
@100: final after #80
Hardware Security Laboratory
Lab 3: fork … join_none
program test;
initial begin
$display("@%0d: start fork...join_none example", $time);
#10 $display("@%0d: sequential after #10", $time);
$display("@%0d: parallel start", $time);
fork
#50 $display("@%0d: parallel after #50", $time);
#10 $display("@%0d: parallel after #10", $time);
begin
#30 $display("@%0d: sequential after #30", $time);
#10 $display("@%0d: sequential after #10", $time);
end
join_none
$display("@%0d: after join", $time);
#80 $display("@%0d: final after #80", $time);
end
endprogram
Hardware Security Laboratory
Lab 3 Output
program test;
initial begin
$display
$display("@%0d: start fork...join_none example", $time);
#10 $display("@%0d: sequential after #10", $time); #10 $display
$display("@%0d: parallel start", $time);
fork
#50 $display("@%0d: parallel after #50", $time);
$display
#10 $display("@%0d: parallel after #10", $time);
begin $display #10 $display
#30 $display("@%0d: sequential after #30", $time);
#10 $display("@%0d: sequential after #10", $time);
end
join_none
$display("@%0d: after join", $time); #30 $display
#80 $display("@%0d: final after #80", $time);
end #10 $display
endprogram
@0: start fork...join_none example
@10: sequential after #10 #50 $display
@10: parallel start
@10: after join
@20: parallel after #10
@40: sequential after #30
@50: sequential after #10 #80 $display
@60: parallel after #50
@90: final after #80
Hardware Security Laboratory
Creating Threads in a Class UVM
Hardware Security Laboratory
Dynamic Thread Creation
Hardware Security Laboratory
Static Variables
,
fork …
join none
-
Hardware Security Laboratory
Automatic Variables
Hardware Security Laboratory
Disabling a Thread
lubel
using
Hardware Security Laboratory
Disabling Multiple
Threads
Hardware Security Laboratory
Disabling Multiple Threads with a Label
Hardware Security Laboratory
Lab 4: Blocking on an Event
program test;
event e1, e2;
initial begin
$display("@%0d: 1: before trigger", $time);
-> e1; /1
@e2; 11
$display("@%0d: 1: after trigger", $time);
end
initial begin
$display("@%0d: 2: before trigger", $time);
-> e2;
@e1;
$display("@%0d: 2: after trigger", $time);
end
endprogram
Hardware Security Laboratory
Lab 5: Wait on an Event
program test;
event e1, e2;
initial begin
$display("@%0d: 1: before trigger", $time);
-> e1;
@e2; 1 wait
/
$display("@%0d: 1: after trigger", $time);
end
initial begin
$display("@%0d: 2: before trigger", $time);
-> e2;
@e1;
$display("@%0d: 2: after trigger", $time);
end
endprogram
Hardware Security Laboratory
Passing an Event into a Constructor
Hardware Security Laboratory
Waiting on Multiple Events
Hardware Security Laboratory
Semaphore
,
"
2 ~
o
3 1
Hardware Security Laboratory
Mailbox
thread safety Library / structure
• new
• Instantiate a mailbox
• size
• The new function may take size as an argument
• put
• The put function may be blocked if the mailbox is full
• get
• The get function may be blocked if the mailbox is empty
Hardware Security Laboratory
Mailbox Example
Hardware Security Laboratory
Lab 6: Unsynchronized Communication
program test;
class Producer; mailbox mbx;
task run; Producer p;
for (int i=1; i<4; i++) begin Consumer c;
$display("Producer: before put(%0d)", i);
mbx.put(i); initial begin
end mbx = new;
endtask p = new;
endclass c = new;
class Consumer; fork
task run; p.run;
int i; c.run;
repeat (3) begin join
mbx.get(i); // Get integer from mbx end
$display("Consumer: after get(%0d)", i); endprogram
end
endtask
endclass
Hardware Security Laboratory
Lab 7: Bounded Mailbox
program test;
class Producer; mailbox mbx;
task run; Producer p;
for (int i=1; i<4; i++) begin Consumer c;
$display("Producer: before put(%0d)", i);
mbx.put(i); initial begin
end mbx = new(1); 11 1
endtask p = new;
endclass c = new;
class Consumer; fork
task run; p.run;
int i; c.run;
repeat (3) begin join
mbx.get(i); // Get integer from mbx end
$display("Consumer: after get(%0d)", i); endprogram
end
endtask
endclass
Hardware Security Laboratory
Lab 8: Synchronized Communication
program test;
event handshake; mailbox mbx;
class Producer; Producer p;
task run; Consumer c;
for (int i=1; i<4; i++) begin
$display("Producer: before put(%0d)", i); initial begin
mbx.put(i); mbx = new;
@handshake; p = new;
end c = new;
endtask
endclass fork
p.run;
class Consumer; c.run;
task run; join
int i; end
repeat (3) begin endprogram
mbx.get(i); // Get integer from mbx
$display("Consumer: after get(%0d)", i);
->handshake;
end
endtask
endclass
Hardware Security Laboratory
Transactor Example
Hardware Security Laboratory
Advanced OOP and
Guidelines
SystemVerilog for Verification
Hardware Security Laboratory
Inheritance
Hardware Security Laboratory
Constructor
Hardware Security Laboratory
Lab 1: Polymorphism
program test;
class Transaction;
rand bit [31:0] src;
function void display;
$display("Transaction: src=%0d", src);
endfunction
endclass
class BadTr extends Transaction;
bit bad_crc;
function void display;
$display("BadTr: bad_crc=%0d", bad_crc);
endfunction
endclass
Transaction tr;
BadTr br;
initial begin
br = new;
hande
tr = br;
$display(tr.src);
tr.display; display - . .
0
Tran Eacton : sra o
=
end
endprogram
Hardware Security Laboratory
Lab 2: Type Casting
program test;
class Transaction;
rand bit [31:0] src;
function void display;
$display("Transaction: src=%0d", src);
endfunction
endclass
class BadTr extends Transaction;
bit bad_crc;
function void display;
$display("BadTr: bad_crc=%0d", bad_crc);
endfunction
endclass
Transaction tr;
BadTr br, br2;
initial begin
br = new;
tr = br;
if(!$cast(br2, tr)) 11 ansign .
$display("cannot assign tr to br2");
$display(br2.bad_crc);
8 ⑥
br2.display; .
Bad Tr bad
o
end :
-
coc =
endprogram
Hardware Security Laboratory
Lab 3: Virtual Methods
program test;
class Transaction;
rand bit [31:0] src;
virtual function void display;
$display("Transaction: src=%0d", src);
endfunction
endclass
class BadTr extends Transaction;
bit bad_crc;
virtual function void display;
$display("BadTr: bad_crc=%0d", bad_crc);
endfunction
endclass
→
Transaction tr;
BadTr br;
initial begin
br = new;
tr = br;
$display(tr.src);
tr.display;
end . coc
BadTr ; 3 ad =
o
endprogram
Hardware Security Laboratory
Inheritance vs Composition
Inheritance Composition
Relationship Is-a Has-a
Do you need to group multiple subclasses together? No Yes
(SystemVerilog does not support multiple inheritance)
Does the higher-level class represent objects at a Yes No
similar level of abstraction?
Is the lower-level information always present or Yes No
required?
Does the additional data need to remain attached to Yes No
the original class while it is being processed by pre-
existing code?
Hardware Security Laboratory
Callback: To Maximize Reuse
Hardware Security Laboratory
Creating a Callback
Hardware Security Laboratory
Using a Callback
Hardware Security Laboratory
Functional
Coverage
SystemVerilog for Verification
Hardware Security Laboratory
Coverage Driven Verification
• Composition of a coverage driven environment
• Reusable stimulus sequences developed with “constrained random” generation
• Running unique seeds allows the environment to exercise different functionality
• Monitors independently watch the environment
• Independent checks ensure correct behavior
• Independent coverage points indicate which functionality has been exercised
Hardware Security Laboratory
Directed vs CRV
• Stimuli generation
• Monitoring and checking
• Coverage collection
Hardware Security Laboratory
Existing Technologies
• Languages: SystemVerilog, C/C++, SystemC
• Methodologies: eRM, UVM
• Tools: Cadence Incisive, Mentor Questa, Synopsys VCS
Hardware Security Laboratory
Coverage
• To answer the question “Are we done?” we need to answer:
• Were all the design features and requirements (functions) identified in
the testplan verified?
• Were there lines of code or structures (code) in the design model that
were never exercised?
• Coverage is a simulation metric we use to measure verification
completeness
Hardware Security Laboratory
Coverage Measurement
• Coverage is a simulation metric we use to measure verification
progress and completeness
Hardware Security Laboratory
Kinds of Coverage
• Code coverage (implicit coverage)
• Inherited from the design
• Functional coverage/assertion coverage (explicit coverage)
• Made by verification engineer
. .
X1
if CAI) d. X ,
× ,
else ∞ x2
1
×2 e1 .
if ( 131 ) d. 1 X 2 4α
franctlowal coverenge
.
else do .
Hardware Security Laboratory
Code Coverage
• Code coverage is a measurement of structures within the source
code that have been activated during simulation.
• Benefits:
• It is implicit, so it is automatically generated with little effort
• Limitations:
• The testbench must generate proper input stimulus to activate a design error
• The testbench must generate proper input stimulus to propagate all effects
resulting from the design error to an output port
• The testbench must contain a monitor that can detect the design error
• Even with 100% of code coverage, there could be functionality defined in the
specification that was never tested
Hardware Security Laboratory
A
Functional Coverage
Functional coverage
• Functional coverage helps us answer the question: Have all
specified functional requirements been implemented, and then
exercised during simulation?
• Benefits are defined in coverage definition:
• It helps us measure verification progress and completeness
• Limitation is that it is explicit, which means it is required to:
• Identify the functionality or design intent that you want to measure
• Implementing the machinery to measure the functionality or design
intent
list .
Hardware Security Laboratory
Lab 1: covergroup
testbench.sv run.do
program test; vsim +access+r;
class Transaction; run -all;
rand bit [31:0] data; acdb save;
rand bit [ 2:0] port; // Eight port numbers acdb report -db fcover.acdb -txt -o cov.txt;
endclass exit
covergroup CovPort;
coverpoint tr.port; // Measure coverage
endgroup
Transaction tr = new;
initial begin
CovPort ck = new; // Instantiate group
repeat (4) begin // Run a few cycles
assert(tr.randomize); // Create a transaction
ck.sample(); // Gather coverage " .
Hit
end
end
endprogram
Hardware Security Laboratory
Lab 2: Number of Bins
testbench.sv run.do
program test; vsim +access+r;
class Transaction; run -all;
rand bit [31:0] data; acdb save;
rand bit [ 2:0] port; // Eight port numbers acdb report -db fcover.acdb -txt -o cov.txt;
endclass exit
covergroup CovPort;
coverpoint tr.port {option.auto_bin_max = 2;}
endgroup
Transaction tr = new;
initial begin
CovPort ck = new; // Instantiate group
repeat (4) begin // Run a few cycles
assert(tr.randomize); // Create a transaction
ck.sample();
end
end
endprogram
Hardware Security Laboratory
Coverage in a Class
No need to define a separate instance name
Hardware Security Laboratory
Naming Bins
Hardware Security Laboratory
Conditional Coverage
Hardware Security Laboratory
Lab 3: Transition Coverage
testbench.sv run.do
program test; vsim +access+r;
class Transaction; run -all;
rand bit [31:0] data; acdb save;
rand bit [ 2:0] port; // Eight port numbers acdb report -db fcover.acdb -txt -o cov.txt;
endclass exit
covergroup CovPort;
port: coverpoint tr.port {bins t1 = (0=>1);}
endgroup
• Multiple transitions
Transaction tr = new; • (1,2 => 3,4) is equal to (1=>3), (1=>4), (2=>3),
initial begin (2=>4)
CovPort ck = new; // Instantiate group • Sequence
• (0=>1=>2) is different from (0=>1=>1+1=>2)
repeat (4) begin // Run a few cycles • Repeat
assert(tr.randomize); // Create a transaction
$display("Port = %0d", tr.port);
• 1[*3] means repeat 1 for 3 times
ck.sample(); • 1[*3:5] means repeat 1 for 3, 4, or 5 times
end • Wild card
end • 3’b??0
endprogram
Hardware Security Laboratory
Ignoring Bins
Hardware Security Laboratory
Cross Coverage
Hardware Security Laboratory
Excluding Bins From Cross Coverage
Hardware Security Laboratory
Cross Coverage Alternatives
Hardware Security Laboratory
Coverage Options
• Comment
• Per-instance
• Print empty bins
• Coverage goal
Hardware Security Laboratory
Parameterized Covergroup
Hardware Security Laboratory
Coverage Analysis
• Measuring coverage during simulation
• get_coverage
• get_coverage_inst
• You can use them to determine the end of simulation
• If the coverage level does not advance after a given number of
transactions or cycles, the test should stop.
• You can also use them to boost coverage
• Already covered points may be avoided to focus more on uncovered
points.
Hardware Security Laboratory
SystemVerilog를
이용한 검증 방법론
실습
Hardware Security Laboratory Largely based on slides of Prof. Hsiung
module APB_REG #(
Design (APB
parameter REG_NUM_BITS = 4 )
(
input wire CLK,
input wire RESETn,
Register File) input wire
input wire
input wire
i_psel,
i_penable,
i_pwrite,
input wire [31:0] i_paddr,
APB Rey input wire [31:0] i_pwdata,
output reg [31:0] o_prdata
);
reg [31:0] regfile[2**REG_NUM_BITS-1:0];
wire w_reg_rd_en;
wire w_reg_wr_en;
wire [REG_NUM_BITS-1:0] w_offset;
assign w_reg_rd_en = i_psel & i_penable & ~i_pwrite;
assign w_reg_wr_en = i_psel & i_penable & i_pwrite;
assign w_offset = i_paddr[REG_NUM_BITS-1:0];
// Register Value Read
always @(posedge CLK or negedge RESETn) begin
if (~RESETn)
o_prdata <= 32'h0000_0000;
else if (w_reg_rd_en)
o_prdata <= regfile[w_offset];
else if (w_reg_wr_en)
regfile[w_offset] <= i_pwdata;
end
endmodule
Hardware Security Laboratory
APB Protocol
Hardware Security Laboratory
module testbench();
logic clk;
logic reset;
Testbench
logic psel;
logic penable;
logic pwrite;
logic [31:0] paddr;
logic [31:0] pwdata;
logic [31:0] prdata;
APB_REG dut(
.CLK (clk),
.RESETn (reset),
.i_psel (psel),
.i_penable (penable),
.i_pwrite (pwrite),
.i_paddr (paddr),
.i_pwdata (pwdata),
.o_prdata (prdata)
);
always
begin
clk = 1; #5; clk = 0; #5;
end
task apb_reset();
psel = 0; penable = 0; pwrite = 0; paddr = 0; pwdata = 0;
endtask
task apb_write(input [31:0] addr, data);
psel = 1; penable = 1; pwrite = 1; paddr = addr; pwdata = data;
endtask
task apb_read(input [31:0] addr);
psel = 1; penable = 1; pwrite = 0; paddr = addr;
endtask
initial begin
$dumpfile("dump.vcd"); $dumpvars;
apb_reset();
reset = 1;
#11; reset = 0;
#10; reset = 1;
#10; apb_write(32'h8000_0004, 32'hdead_beef);
#10; apb_read(32'h8000_0004);
#20; $stop;
end
endmodule
4
Hardware Security Laboratory
Assignments
Step 1: Interface
• Connect the APB signals by the interface
☆ Step 2: Constrained random
• Randomize the address, data and write enable (wen)
☆ Step 3: Golden model .
• Verify the functionality by using a golden model
Step 4: Assertion
• Add assertions to check the result
☆ Step 5: Coverage
• Measure the cross coverage of the address and wen (not data)
5
Hardware Security Laboratory
Step 1: Interface
interface apb_if(input bit clk);
logic psel;
logic penable;
logic pwrite;
logic [31:0] paddr;
logic [31:0] pwdata;
logic [31:0] prdata;
endinterface
4 Hint !?
full code
Yon should wuite
Hardware Security Laboratory
Step 2: Constrained Random
class Req;
rand bit [REG_NUM_BITS-1:0] addr;
rand bit [31:0] data;
rand bit wen;
endclass
Hardware Security Laboratory
Step 3 & 4: Golden Model
Declare a golden model of the register file
When a data is written to the APB_REG, the same to the golden
model
When a data is read from the APB_REG, compare the output
data with the golden model with an assertion
Hardware Security Laboratory
Step 5: Coverage
,
I.
covergroup CovReq;
addr: coverpoint req.addr;
wen: coverpoint req.wen;
cross addr, wen;
endgroup
Hardware Security Laboratory