Top Banner
Introduction to SystemVerilog for Testbench
167

SystemVerilog Testbench

Apr 10, 2015

Download

Documents

Vivek

Tutorial on testbench design with SystemVerilog.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: SystemVerilog Testbench

Introduction toSystemVerilog for Testbench

Presenter
Presentation Notes
Remember, this is a one-day class – doesn’t show everything, just the highlights. Verify all code examples! Questions marked with ?? More examples, less BNF!
Page 2: SystemVerilog Testbench

2

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 3: SystemVerilog Testbench

3

SystemVerilog Testbench with VCS 05/07/2007

By the end of this class, you should be able to:

Lecture Objectives

Develop self checking testbenches using VCS and SystemVerilog How to connect your Design to a SV testbench How to perform random constrained testing How to take advantage of powerful concurrency How to implement Functional Coverage

Look forcoding tips!

Page 4: SystemVerilog Testbench

4

SystemVerilog Testbench with VCS

Based on IEEE P1800-2005 Standard Detailed in Language Reference Manual Verification-specific language features Constrained random stimulus generation Functional coverage SystemVerilog Assertions (SVA)

SystemVerilog for Verification

Introduction

Presenter
Presentation Notes
Synopsys has taken leadership position by making SystemVerilog 3.1a hardware verification language, a non-proprietary language.
Page 5: SystemVerilog Testbench

5

SystemVerilog Testbench with VCS

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 6: SystemVerilog Testbench

6

SystemVerilog Testbench with VCS

Verification EnvironmentDefinitions

DUT

Driver Monitor

Supplies datato the DUT

Observesdata

from DUTAssertions

Transactor

Executestransactions

Identifiestransactions

Checker

CheckscorrectnessCreates

stimulus

Test

Scoreboard

VerificationEnvironment

Testbench

Page 7: SystemVerilog Testbench

7

SystemVerilog Testbench with VCS

Methodology Introduction

To maximize design quality Provides guidance:

Find bugs fast! Identify the best practices Make the most of Synopsys tools

Methodology One verification environment, many tests Minimize test-specific code Reuse

Across testsAcross blocksAcross systemsAcross projects

Presenter
Presentation Notes
This is a pre discussion about VMM
Page 8: SystemVerilog Testbench

8

SystemVerilog Testbench with VCS 05/07/2007

Methodology Introduction

Testbench Design Start with a fully randomizable testbench Run many randomized simulation runs Analyze cumulative coverage and coverage holes

Then with minimal code changes: Add constrained stimulus to fill coverage holes

Finally: Make few directed tests to hit the remaining holes

Presenter
Presentation Notes
This is a pre discussion about VMM This is a pre discussion about VMM
Page 9: SystemVerilog Testbench

9

SystemVerilog Testbench with VCS 05/07/2007

Coverage-Driven Verification

Time

% C

over

age Goal Directed

Methodology

Measure progress using functional coverage

Self-checking random environment

development time

Coverage-DrivenMethodology

ProductivitygainWith

VIP

Presenter
Presentation Notes
This is a pre discussion about VMM
Page 10: SystemVerilog Testbench

10

SystemVerilog Testbench with VCS 05/07/2007

Key Benefits: Testbench Environment

Environment Creation takes less time Testbench is easy constrain from the top level file All Legal Device Configurations are tested

Regression can select different DUT configurations Configuration object is randomized and constrained

Enables reuse

Presenter
Presentation Notes
This is a pre discussion about VMM
Page 11: SystemVerilog Testbench

11

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 12: SystemVerilog Testbench

12

SystemVerilog Testbench with VCS 05/07/2007

What are We Going to Discuss?

Getting Started

SystemVerilog Testbench Verification Flow Compiling and Running in VCS Documentation and support

Page 13: SystemVerilog Testbench

13

SystemVerilog Testbench with VCS 05/07/2007

Compile:vcs -sverilog –debug top.sv test.sv dut.sv -sverilog Enable SystemVerilog constructs -debug Enable debug except line stepping -debug_all Enable debug including line stepping

Run:simv +user_tb_runtime_options -l logfile Create log file -gui Run GUI -ucli Run with new command line debugger -i cmd.key Execute UCLI commands

Getting Started

Compiling and Running with VCS

See the VCS User Guide for all options

Page 14: SystemVerilog Testbench

14

SystemVerilog Testbench with VCS 05/07/2007

SystemVerilog has dozens of new reserved keywords such as bit, packed, logic that might conflict with existing Verilog code

Keep your Verilog-2001 code separate from SystemVerilog code and compile with:vcs –sverilog new.v +verilog2001ext+.v2k old.v2k

orvcs +systemverilogext+.sv old.v new.sv

Getting Started

Legacy Code Issues

// Old Verilog-1995/2001 legacy codeinteger bit, count;initial begincount = 0;for (bit = 0; bit < 8; bit = bit + 1)if (adrs[bit] === 1'bx)count = count + 1;

end

Page 15: SystemVerilog Testbench

15

SystemVerilog Testbench with VCS 05/07/2007

Debug: Getting Started Invoke DVE > simv –gui -tbug

Sourcecode

tracing

Localvariables

Activethreads

Page 16: SystemVerilog Testbench

16

SystemVerilog Testbench with VCS 05/07/2007

Getting Started

SystemVerilog documentation Examples

$VCS_HOME/doc/examples

Email Support: [email protected]

On-line knowledge database http://solvnet.synopsys.com

Testbench Discussion Forum http://verificationguild.com

SystemVerilog LRM www.Accellera.org or www.eda.org/sv

Documentation and Support> vcs -doc

Page 17: SystemVerilog Testbench

17

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 18: SystemVerilog Testbench

18

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment

Someone gives you a DUT, now what?

How Should You Connect to DUT

resetrequest[1:0]grant[1:0]clock

arb.sv

Presenter
Presentation Notes
This section needs to be updated with the first part of the interface section
Page 19: SystemVerilog Testbench

19

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment

top.sv

clock

test.sv arb.sv

1. Create DUT interface with modports and clocking blocks

2. Create testbench program3. Create top module 4. Compile and run

Steps to hook up a DUT to a Testbench

Page 20: SystemVerilog Testbench

20

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment -- Interfaces

Introduction The complexity of communication between

blocks requires a new design entity Top level net-lists are too verbose and error prone

An interface encapsulates this communication Connectivity (signals) Directional information (modports) Timing (clocking blocks) Functionality (routines, assertions, initial/always blocks)

An interface can be: Connected at compile-time (default) Connected at run-time – virtual interfaces

An interface can not: Be hierarchical, or extended Device 1 Device 2interface

Page 21: SystemVerilog Testbench

21

SystemVerilog Testbench with VCS 05/07/2007

top

Testbench Environment -- Interfaces

Before Interfaces The RTL code was connect with a netlist

cpu

module mem (input bit req,

bit clk,bit start,wire [1:0] mode,wire [7:0] addr,

inout wire [7:0] data,output bit gnt,

bit rdy);…

mem

module cpu (input bit clk,

bit gnt,bit rdy,

inout wire [7:0] data,output bit req,

bit start,wire [1:0] mode,wire [7:0] addr);

…module top;logic req, gnt, start, rdy;bit clk;always #10 clk = !clk;logic [1:0] mode;logic [7:0] addr;wire [7:0] data;mem m1(req, clk, start, mode, addr, data, gnt, rdy);cpu c1(clk, gnt, rdy, data, req, start, mode, addr);endmodule

Page 22: SystemVerilog Testbench

22

SystemVerilog Testbench with VCS 05/07/2007

simple_busclk

top

Testbench Environment -- Interfaces

Named Bundle of Signals

cpu

interface simple_bus; logic req, gnt;logic [7:0] addr;wire [7:0] data;logic [1:0] mode;logic start, rdy;

endinterface

mem

module mem(simple_bus sb, input bit clk);

…endmodule

module top;logic clk = 0;always #10 clk = !clk;simple_bus sb(); mem m1(sb, clk); cpu c1(sb, clk);

endmodule

module cpu(simple_bus sb, input bit clk);

…endmodule

The RTL code is connected with bundled signals

Page 23: SystemVerilog Testbench

23

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment -- Interfaces

Referencing Signals in Interface Use hierarchical names for interface signals in a module

Signals with multiple drivers must be wire Signals driven by procedural assignment must be logic

interface simple_bus; logic req, gnt;logic [7:0] addr;wire [7:0] data;logic [1:0] mode;logic start, rdy;

endinterface: simple_bus

module cpu(simple_bus sb, input bit clk);logic addr_reg;always @(posedge clk)sb.addr <= addr_reg;

endmodule : cpu

Label on endstatement

Page 24: SystemVerilog Testbench

24

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment -- Interfaces

Dividing an Interface Not every device has the same access to an interface

Restrict signal access & direction with modportinterface simple_bus;

logic req, gnt;logic [7:0] addr;wire [7:0] data;logic [1:0] mode;logic start, rdy;modport SLAVE (input addr, gnt, mode, start,

output req, rdy,inout data);

modport MASTER (output addr, gnt, start, mode,input req, rdy,inout data);

endinterface: simple_bus

module cpu(simple_bus.MASTER sb, input bit clk);

…endmodule

module mem(simple_bus.SLAVE sb, input bit clk);

…endmodule

Page 25: SystemVerilog Testbench

25

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment -- Interfaces

Adding Timing An interface can use a clocking block to control timing

Directions are relative to program blockinterface arb_if (input bit clk);

logic [1:0] grant, request;logic reset;

clocking cb @(posedge clk);input grant; // TB inputoutput request; // TB output

endclocking

modport DUT (input clk,input request, reset, // Design under test output grant);

modport TB (clocking cb, // Synch signalsoutput reset); // Async signals

endinterface: arb_if

Step 1

resetrequest[1:0]grant[1:0]clock

arb.sv

Page 26: SystemVerilog Testbench

26

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment -- Interfaces

Use in the interface, just for testbench

Benefits: Creates explicit synchronous timing domains Provides race-free operation if input skew > 0 Your testbench will always drive the signals at the right time!

Functionality: An interface can contain multiple clocking blocks There is one clock per clocking block. Default is “default input #1step output #0;” “1step” specifies that the values are sampled immediately

upon entering this time slot in Prepone region, before any design activity

Clocking Blocks

Page 27: SystemVerilog Testbench

27

SystemVerilog Testbench with VCS 05/07/2007

SystemVerilog Scheduling

Each time slot is divided into 5 major regions (plus PLI) Prepone Sample signals before any changes (#1step) Active Design simulation (module), including NBA Observed Assertions evaluated after design executes Reactive Testbench activity (program) Postpone Read only phase

SystemVerilog Scheduling Details

clock

data

REGION

ACTIVITY

NextPrevious

Prepone Observed Reactive PostponeActive

designsample assertions testbench $monitor

Current

Assertion and testbench events can trigger more design evaluations in this time slot

Page 28: SystemVerilog Testbench

28

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment - Program Block

Benefits: Encapsulates the testbench Separates the testbench from the DUT Provides an entry point for execution Creates a scope to encapsulate program-wide data

Functionality: Can be instantiated in any hierarchical location Typically at the top level

Interfaces and ports can be connected in the same manner as any other module

Leaf node, can not contain any hierarchy, just classes Code goes in initial blocks & routines, no always blocks Executes in the Reactive region

Program Block

Page 29: SystemVerilog Testbench

29

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment – Program

Create testbench program: test.sv

program test(arb_if.TB arbif);initial begin// Asynch drive reset

arbif.reset <= 0;#15ns arbif.reset <= 1; #35ns arbif.reset <= 0;

// Synch drive request##1 arbif.cb.request <= 1;##1 arbif.cb.request <= 0;wait (arbif.cb.grant == 1);

endendprogram

interface arb_if (input bit clk);logic grant, request, reset;clocking cb @(posedge clk);

input grant;output request;

endclockingmodport TB (clocking cb,

output reset);endinterface: arb_if

Step 2

Wait 1 clock cycleCommon mistake: forgetting “cb.” in signal referenceError: arbif.request notvisible via modport

clkreset

request

ns!

Page 30: SystemVerilog Testbench

30

SystemVerilog Testbench with VCS 05/07/2007

Using the Clocking Block

Clocking Block signals are referenced by pre-pending the clocking block name to the signal:

Assignment will happen at next active clock edge Time will NOT advance unless you use #1 or ##1

Synchronous Signal Access

interface arb_if (input bit clk);logic grant, request, reset;clocking cb @(posedge clk);

input grant;output request;

endclockingmodport TB (clocking cb, output reset);

endinterface: arb_if

arbif.cb.request <= 1; // drivevalue = arbif.cb.grant; // sample

All drives must use non-blocking assignment

Page 31: SystemVerilog Testbench

31

SystemVerilog Testbench with VCS 05/07/2007

Driving, Sampling, Synchronizing

Synchronize to active clock edge specified in clocking block

Synchronize to any edge of signal

Wait for N clock cycles with ##n – blocking statement

Signal Synchronization

@arbif.cb; // continue on posedge of arb_if clkrepeat (3) @arbif.cb; // Wait for 3 posedges

@arbif.cb.grant; // continue on any edge of grant@(posedge arbif.cb.grant); // continue on posedge@(negedge arbif.cb.grant); // continue on negedgewait (arbif.cb.grant==1); // wait for expression

// no delay if already true

##2 arbif.cb.request <= 0; // Wait 2 cycles // then assign

Presenter
Presentation Notes
Waiting for several CB cycles will be ##3 eventually, when implemented
Page 32: SystemVerilog Testbench

32

SystemVerilog Testbench with VCS 05/07/2007

Testbench Timing

When you are using interfaces with a clocking block: There is a 1-cycle delay from DUT output to testbench input

“Virtual synchronizer” added to TB input No delay from testbench output to DUT inputdefault input #1step output #0;”

SystemVerilog Testbench in Simulation

clock

Sample inputsbefore clock

Drive outputsat clock

Design

Testbench

Page 33: SystemVerilog Testbench

33

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment – Top Block

Create top module

// Synchronous TB program test(arb_if.TB arbif);…endprogram

module top;bit clk;test t1 (.*);arb d1 (.*);arb_if arbif(.*); always #50clk = !clk;

endmodulemodule arb(arb_if.DUT arbif,

bit clk);// Some logic here…endmodule

Step 3

interface arb_if (input bit clk);…endinterface: arb_if The syntax .* connect ports

and signals with same names

Page 34: SystemVerilog Testbench

34

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment - Scoping

Scoping Rules

`timescale 1ns/1nstypedef enum {IDLE, RUN, WAIT} fsm_state_t;parameter TIMEOUT = 1_000_000;

SystemVerilog defines a global scope, $root, outside any module or program Define global items such as shared enums Use parameters for global constants, not macros

module state_machine(…);fsm_state_t state, next_state;

endmodule

program test;fsm_state_t state;initial #TIMEOUT $finish;

endprogram

root.sv

dut.sv

test.sv

Page 35: SystemVerilog Testbench

35

SystemVerilog Testbench with VCS 05/07/2007

Testbench Environment -- Communication

DUT visibility The program block can see all signals & routines in

the design A module can not see anything in program block

Use absolute hierarchical path to access DUT Start with $root, then top-level instance name, DUT, etc.

Use care when calling DUT routines from program Good practice is to use a function to get info Don’t try to trigger DUT code

SV accesses ports & XMR signals immediately (asynchronously)

dstate = top.dut.state; // Immediate XMR sampledstate = $root.top.dut.state; // Absolute path

Presenter
Presentation Notes
If SVA succeeds, then clause executed if it exists. If SVA fails, else clause executed if it exists, or an error message is printed
Page 36: SystemVerilog Testbench

36

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Check signal values

program test (arb_if arbif);initial beginarbif.cb.request <= 1;repeat (2) @arbif.cb;a1: assert (arbif.cb.grant==1);

end

SystemVerilog Assertion

Check a SVA procedurally Non-blocking statement

“test.sv", 7: top.t1.a1: started at 55ns failed at 55nsOffending '(arbif.cb.grant == 1)‘

in case of error…

Presenter
Presentation Notes
If SVA succeeds, then clause executed if it exists. If SVA fails, else clause executed if it exists, or an error message is printed Default message: “test.sv", 72: arb_top.t1.unnamed$$_0.a1: started at 55ns failed at 55ns Offending '(arbif.cb.grant == 2'b1)‘ $info message: Info: "assert.sv", 72: arb_top.t1.unnamed$$_0.a1: at time 55 ns Info message $error message: "assert.sv", 72: arb_top.t1.unnamed$$_0.a1: started at 55ns failed at 55ns Offending '(arbif.cb.grant == 2'b0)' Error: "assert.sv", 72: arb_top.t1.unnamed$$_0.a1: at time 55 ns error message
Page 37: SystemVerilog Testbench

37

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Check signal values

program test (arb_if arbif);initial begin

arbif.cb.request <= 1;repeat (2) @arbif.cb;a1: assert (arbif.cb.grant==1)success++;

else$error(“No grant received”);

end

Optional then & else clauses for success / failure If SVA failure and no else-clause, a generic error is printed

Use $info, $warn, $error, and $failure for reporting These are only valid in SVA’s (IEEE-1800)

Custommessage

Presenter
Presentation Notes
If SVA succeeds, then clause executed if it exists. If SVA fails, else clause executed if it exists, or an error message is printed
Page 38: SystemVerilog Testbench

38

SystemVerilog Testbench with VCS 05/07/2007

> vcs -sverilog -debug root.sv top.sv arb_if.sv test.sv arb.sv

> simv –gui -tbug

Testbench Environment – Compile and Run

Compile and run

Run withdebugger

Step 4

Page 39: SystemVerilog Testbench

39

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 40: SystemVerilog Testbench

40

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

SystemVerilog basics Data types Arrays Subroutines Interfaces

This class assumes you already know most Verilog-1995 and 2001 constructs

What are We Going to Discuss?

Page 41: SystemVerilog Testbench

41

SystemVerilog Testbench with VCS 05/07/2007

Basic SystemVerilog Data Types

reg [31:0] r; // 4-statelogic [7:0] w; // 4-state

Explicit 2-state variables give better performance, but they will not propagate X or Z, so keep away from DUT

assert(!$isunknown(ifc.cb.data));

SystemVerilog Data Types

In SystemVerilog, the old reg type has been extended so it can be driven by single drivers (gates, modules, continuous assignments) like a wire. It has anew name logic. It can not have multiple drivers – use a wire.

bit [31:0] b; // 2-state bit 0 or 1 integer i; // 4-state, 32-bits, signed Verilog-1995int i; // 2-state, 32-bit signed integerbyte b8; // 2-state, 8-bit signed integershortint s; // 2-state, 16-bit signed integerlongint l; // 2-state, 64-bit signed integer

Page 42: SystemVerilog Testbench

42

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

User defined types Use typedef to create a synonym for another type

Define a structure with multiple variables

Use union for merged storage

SystemVerilog Data Types

typedef bit [31:0] uint;typedef bit [0:5] bsix_t; // Define new typebsix_t my_var; // Create 6-bit variable

typedef union {int i; shortreal f; } num_t;num_t un;un.f = 0.0; // set n in floating point format

typedef struct {bit [7:0] opcode;bit [23:0] addr; }

instruction; // named structure typeinstruction IR; // define variable

Use classesinstead!

Usefultype

Page 43: SystemVerilog Testbench

43

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Enumerated type Explicitly typed and scoped (program or class-level) Can only create variables at class level, not typedef

Allows compile time error checking

SystemVerilog Data Types

// Declare single enum variableenum {RED, BLUE, GREEN} color;

// declare data typetypedef enum {INIT, DECODE, IDLE} fsmstate_t;fsmstate_t pstate, nstate; // declare variablesint i = 1;case (pstate)IDLE: nstate = INIT; // data assignmentINIT: nstate = DECODE;default: nstate = IDLE;

endcase

$display(“Next state is %0s”, nstate.name);

nstate = fsmstate_t’(i); // cast integer to enum

Print thesymbolic

name

Presenter
Presentation Notes
NYI - typedef in a class This just shows examples of enum. The first enum creates a variable color, but not a type, so there will be only one variable of that that type. Next, a type is created for the state machine. This type can be used again to create many variables. Lastly, you can print an enumerated type symbolically by using the name() method.
Page 44: SystemVerilog Testbench

44

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Fast, static size Multiple dimensions supported Out-of-bounds write ignored Out-of-bounds read returns X, even for 2-state Array data stored in 32-bit words

Fixed Size Arrays

int twoD1[0:7][0:23]; // 2D arrayint twoD2[8][24]; // same as abovetwoD1 = twoD2; // Array copyif (twoD1==twoD2)… // Array compare

bytes[1]bytes[2]

bytes[0] 01234567 0123456701234567 0123456701234567 0123456701234567 0123456701234567 0123456701234567 01234567

type name [constant];

bytes[0][3] bytes[0][1][6]

Use bit & word subs together

with fixed arrays

bit [3:0][7:0] bytes [0:2]; // 3 entries of packed 4 bytes

Presenter
Presentation Notes
Verified. Is this too busy?
Page 45: SystemVerilog Testbench

45

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Fast, variable sized with call to new() Similar to a fixed size array, but size given at run time Single dimension only, never packed Out-of-bounds access causes run-time error

Dynamic Arrays

int d[], b[]; // Two dynamic arraysd = new[5]; // Make array with 5 elementsforeach (d[j]) // Initialize

d[j] = j; b = d; // Copy a dynamic arrayb[0] = 5;$display(d[0],b[0]); // See both values (0 & 5)d = new[20](d); // Expand and copyd = new[100]; // Allocate 100 new integers

// Old values are lostd.delete(); // Delete all elements

type name [ ];

Presenter
Presentation Notes
Verified OpenVERA used [*], NTB-SV uses []
Page 46: SystemVerilog Testbench

46

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Flexible – size can easily change Variable size array with automatic sizing, single dimension Many searching, sorting, and insertion methods (see LRM) Constant time to read, write, and insert at front & back Out of bounds access causes run-time error

Queues

int q[$] = {0,1,3,6};int j = 2, b[$] = {4,5};q.insert(2, j); // {0,1,2,3,6} Insert before s[2] q.insert(4, b); // {0,1,2,3,4,5,6} Insert whole queueq.delete(1); // {0,2,3,4,5,6} Delete element #1q.push_front(7); // {7,0,2,3,4,5,6} Insert at frontj = q.pop_back(); // {7,0,2,3,4,5} j = 6q.push_back(8); // {7,0,2,3,4,5,8} Insert at backj = q.pop_front(); // {0,2,3,4,5,8} j = 7$display(q.size); // “6”foreach (q[i]) $display(q[i]);

type name [$];

FAST

!

Presenter
Presentation Notes
Verified Queues are useful and intuitive. You can look at the code and know exactly what’s going on. It’s just standard array. With a FIFO modeled as a queue, you can run your entire regression and track how big it gets, then add 10 (joke here) and specify the size in the queue declaration and bingo – it’s synthesizable. Again, you just change the declaration but not any of the code that actually uses it. A queue will use more memory than a dynamic array, but it is more flexible, and just as fast
Page 47: SystemVerilog Testbench

47

SystemVerilog Testbench with VCS 05/07/2007

Checking Results with Queues

What if transactions get out of order, are dropped or are corrupted in the DUT? Store expected transactions in a queue, with a timestamp Contents are addressable, push/pop Look up transaction ID on arrival for out-of-order delivery If actual transaction not found: corrupted data Periodically scan array for old transactions. Mark them as

dropped and removeTr2 @3000

Tr1 @1000

Tr4 @2000

DUT

Driver Monitor

Transactor Checker

Queues for Scoreboards

Page 48: SystemVerilog Testbench

48

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Great for sparse memories Dynamically allocated, non-contiguous elements Accessed with integer, or string index, single dimension Great for sparse arrays with wide ranging index Array functions: exists, first, last, next, prev

int aa[*], i;reg[7:0] mydata[string];

Associative Arrays

// Print full arrayforeach(aa[i])

$display(i,,aa[i]);

type name [*];

All memoryallocated, even

unused elements

Associative arrayStandard array

Unused elements don’t use memory

Presenter
Presentation Notes
Verified – if i is declared as reg[63:0], OpenVERA used [], NTB-SV uses [*] string c_name[ClassName]; not supported yet Assoc arrays are slower than other arrays, but if you need a sparse memory, they are the best datatype.
Page 49: SystemVerilog Testbench

49

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Search through arrays (fixed, dynamic, queue, assoc.) Many more methods will be implemented, such as sort…

Returns a queue or scalar a.sum of single bit values returns 0/1 Unless you compare to wider value: a.sum == 32’h3 Also available: product, and, or, xor

Array Methods

int q[$] = {1,3,5,7}, tq[$];int d[] = {9,1,8,3,4};int f[6] = {1,6,2,6,8,6};

$display(q.sum, q.product); // 16 105tq = q.min(); // {1}tq = q.max(); // {7}tq = f.unique; // {1,6,2,8}tq = d.find with (item > 3); // {9,8,4}tq = d.find_index with (item > 3); // {0,2,4}

LRM requires a queue

IEEE changed array const from {0,1} to ’{0,1}(VCS issues Warning for old usage)

Presenter
Presentation Notes
NYI: sort, rsort, reverse, find_first, find_first_index, find_last, find_last_index, shuffle
Page 50: SystemVerilog Testbench

50

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Arbitrary length array of chars (like C), grows automatically Compare operators ==, !=, and compare() and icompare()

methods Use { } for concatenation Built-in conversion itoa, atoi, atohex, atooct, atobin

string s = “SystemVerilog”;$display(s.getc(0),, s.toupper());s = {s, “3.1b”}; // string concats.putc(s.len()-1, “a”); // change b-> a$display(s);$display(s.substr(2, 5)); // 4 characters

// Create temporary string, note format my_log($psprintf(“%s %5d”, s, 42));

Strings string name;

Presenter
Presentation Notes
2005.06: Not yet supported –a2real,real2a The putc function will write a single character, and s.len()-1 points to the last character The final substr command prints characters 2, 3, 4, & 5 The $psprintf returns a temporary string – may not be in IEEE standard Note the %5d – Verilog only allowed %0d
Page 51: SystemVerilog Testbench

51

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Tasks and Functionstask reset();

reset_l = 1’b0;#100 reset_l = 1’b1;

endtask

function void print_sum(ref int a[], input int start=0);int sum = 0;for (int j=start; j<a.size; j++)sum += a[j];

$display(“Sum of array is %0d”, sum);endfunction…print_sum(my_array);print_sum(my_array, );

Default value

Function can never contain blocking statements or calls to tasksVoid functions do not return a value

function int add2(int n); return n + 2;

endfunction

Presenter
Presentation Notes
Verified Without “automatic”, sum needs to be initialized every call. Use default value with empty argument
Page 52: SystemVerilog Testbench

52

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Static vs. Automatic Tasks and Functions All calls to static routine shares the same storage space within a

module instance. It can’t be reentrant or recursive. (Verilog-1995) An automatic routine allocates new space for each call. (This is

the default in other languages.) (Verilog-2001) Class routines are automatic by default, while routines in

modules and program are static by default. (SystemVerilog) The print_sum example on the previous slide will NOT work

with static storage as sum will only be initialized at time 0.

Tasks and Functions

program automatic test;task is_automatic();

Change storage defaultfor programs

Presenter
Presentation Notes
Verified A program is static by default. Using “program automatic name” changes this. Assigning to a function name is the same as using the return statement.
Page 53: SystemVerilog Testbench

53

SystemVerilog Testbench with VCS 05/07/2007

SV Language Basics

Argument Passing Type is sticky, following arguments default to that type input - copy value in at beginning - default output - copy value out at end inout - copy in at beginning and out at end ref - pass by reference (effects seen right away) Saves time and memory for passing arrays to tasks & functions

Modifier: const - argument is not allowed to be modified

Tasks and Functions

task T3(a, b, output bit [15:0] u, v);

Default dir is input,default type is logic

a, b: input logicu, v: output bit [15:0]

Watch out for reffollowed by input…

Page 54: SystemVerilog Testbench

54

SystemVerilog Testbench with VCS 05/07/2007

Lab 1

Verify an arbiter

Objective Verify the arbiter’s reset Verify arbiter handles simple requests and grants Verify proper handling of request sequences

Key Topics Port list, clocking block, program block, assert, drive samples

and check responses.

Time Allotted 45 minutes

Page 55: SystemVerilog Testbench

55

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 56: SystemVerilog Testbench

56

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

What Are We Going to Discuss? What is OOP Terminology An example class Default methods for classes Static attribute Assignment and copying Inheritance Polymorphism

Page 57: SystemVerilog Testbench

57

SystemVerilog Testbench with VCS 05/07/2007

Introduction to OOP

OOP: Object Oriented Programming Traditional programming deals with data structures and

algorithms separately OOP organizes transactions and transactors better

Objects group data and algorithms together logically Routines are actions that work on the grouped data

OOP closely ties data and functions together -encapsulation

Extend the functionality of existing objects -inheritance

Wait until runtime to bind data with functions -polymorphism

What is OOP?

Presenter
Presentation Notes
This is a discussion of the ideas behind OOP. Traditional programming languages such as C rely heavily on global data structures which are modified by many routines. Even with the ideas of “structured programming”, these routines often have many side effects, so that calling one routine causes changes that you did not intend. The result is that the code is tightly tied to one implementation, and is hard to modify and reuse. OOP tightly ties data structures to the routines which modify them. Encapsulating data and code together into objects makes a program easier to understand, modify, and reuse. Once an object is defined and well debugged, its functionality can be extended by using it to build a new, more complex object by adding new data and routines, but not modifying the underlying object. Since you do not change the original object, it remains as robust as ever. The new object inherits the working code, so that you can reuse the work that has already been done. The last concept is a way to simplify your programs by having similar routines use the same name. When you add two variables together, you always write A+B, regardless of whether A and B are integers, real numbers, or 4-state multi-bit signals. Likewise, your program should be able to say Copy(A,B) and have Vera call the right routine depending on the data types of A & B.
Page 58: SystemVerilog Testbench

58

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

OOP breaks a testbench into blocks that work together to accomplish the verification goal

Advantages• Objects are easily reused and extended• Allows for complex data structures• Allows access to advanced SystemVerilog

testbench features• Variables, functions, and tasks are protected from

side effects or misuse by other code• Debug small sections of code, one class at a time

What is OOP?

Page 59: SystemVerilog Testbench

59

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

HDL OOP Verilog SystemVerilog Block definition module class

Block instance instance object

Block name instance name handle

Data Types registers & wires Properties: Variables

Executable Code behavioral blocks (always, initial), tasks, functions

Methods: tasks and functions

Communication between blocks

Ports or cross-module task calls

calls, mailboxes, semaphores, etc.

Terminology

Presenter
Presentation Notes
This slide compares Verilog programming constructs with Vera and OOP. The two are actually very similar. For example, making a copy of a “block” is called instantiation in both languages. One big difference is that Verilog modules communicate primarily using ports (data) while Vera objects communicate using task and function calls.
Page 60: SystemVerilog Testbench

60

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

Class Programming element “containing” related group of features

and functionality Encapsulates functionality Provides a template for building objects Can be used as data structures

Object An object is an instance of a class

Handle Type-safe pointer to an object – can not be corrupted

Properties Variables contained in the instance of the class

Methods Tasks/functions (algorithms) that operate on the properties in

this instance of the class

TerminologyBlueprint for a house

A completehouse

Lightswitches

Turn on/off switches

Address of a house

Page 61: SystemVerilog Testbench

61

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

class Transaction;// properties (variables) logic [31:0] src, dst, data[1024], crc;logic [7:0] kind;// methodsfunction void display;

$display(“Tr: %h, %h”, src, dst);endfunction

function void calc_crc();crc = src ^ dst ^ data.xor;

endfunctionendclassprogram automatic test;endprogram

Class Example Variables & methods are public by default

In a class, methods are always automatic

Presenter
Presentation Notes
Use “local” to hide a variable or method from all other classes. Use “protected” to hide from all but extended classes.
Page 62: SystemVerilog Testbench

62

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

Call new() to create an object The class constructor allocates memory and initializes variables

Result stored in a handle to the object

You must to call new() for every handle in an array

SystemVerilog uses a predefined new() for every class, but you can redefine your own

Coding style: don’t call new in declaration Otherwise objects are created before any procedural code

task init;Transaction tr; // A single handleTransaction tr_arr[5]; // An array of handles// Handles are null until initializedtr = new(); // Create a new objectforeach (tr_arr[i]) // Create an arraytr_arr[i] = new(); // of new objects

endtask

Creating an Object From a Class

Declare firstthen construct

Page 63: SystemVerilog Testbench

63

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

Call new(), assigned values to the object properties Handles have the default value of null Using a null handle is an error

Every call to the constructor creates a new object that is independent of all other objects Properties and methods accessed through handle Handles are type safe – can’t misused or modified, unlike C

Class Destruction/De-allocation Automatic Garbage Collection taken care of by SystemVerilog

(like Java, unlike C++) When an object is no longer being referenced, it is garbage

collected No segmentation faults from manual memory deallocation No memory leaks or unexpected side effects

if (tr.done) // No longer needed?tr = null; // clear handle

Working with Objects

Error: null object access in file xx.sv line 38

Page 64: SystemVerilog Testbench

64

SystemVerilog Testbench with VCS 05/07/2007

Where are all the objects?

Drivestransactionsinto the DUT

Scoreboard holdstransactionsExtended

class

Self Check

VerificationEnvironment

Executestransactions

Comparestransactions

Puts datainto

transactions

A transactor can be an object too!

Driver Monitor

DUT

CheckerTransactor

Test

Page 65: SystemVerilog Testbench

65

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

Accessing Class Members Reference properties by pre-pending the object handle

class Transaction;bit [31:0] src, dst, data[1024];bit [7:0] kind;function void display; $display(“Tr: %h, %h”, src, dst);

endfunctionendclass

Transaction tr;

initial begintr = new();tr.src = 5;tr.dst = 7;tr.display();end

Page 66: SystemVerilog Testbench

66

SystemVerilog Testbench with VCS 05/07/2007

OOP Basics

Initializing Class Properties

program automatic test1;class Transaction;

bit [31:0] src, dst;function new();src = 5;dst = 3;

endfunctionendclass

Transaction tr;

initialtr = new();

endprogram

program automatic test2;class Transaction;

bit [31:0] src, dst;function new (int src, int dst=3);this.src = src; // Disambiguatethis.dst = dst;

endfunctionendclass

Transaction tr;

initialtr = new(5); // dst uses default

endprogram

Initialize the class properties in the constructor when the object is created

Function type not needed

Page 67: SystemVerilog Testbench

67

SystemVerilog Testbench with VCS 05/07/2007

Static attribute

How do I create a variable shared by all objects of a class, but not make a global?

A static property is associated with the class definition, not the instantiated object. It is often used to store meta-data, such as number of

instances created It is shared by all objects of that class.

class Transaction; static int count = 0;int id;…function new();

id = count++;endfunction

endclass

Using a id field canhelp keep track of

transactions as theyflow through test

Page 68: SystemVerilog Testbench

68

SystemVerilog Testbench with VCS 05/07/2007

Assignment is not a copy

Assignment of one handle to another only affects the handles. It does not copy data

class Thing; int data;

endclass…Thing t1, t2; // Two handlesinitial begint1 = new(); // Allocate first thingt1.data = 1;t2 = new(); // Allocate secondt2.data = 2;t2 = t1; // Second Thing is lostt2.data = 5; // Modifies first thing$display(t1.data); // Displays “5”

end

data=1

t1

t2

Page 69: SystemVerilog Testbench

69

SystemVerilog Testbench with VCS 05/07/2007

Assignment is not a copy

Assignment of one handle to another only affects the handles. It does not copy data

class Thing; int data;

endclass…Thing t1, t2; // Two handlesinitial begint1 = new(); // Allocate first thingt1.data = 1;t2 = new(); // Allocate secondt2.data = 2;t2 = t1; // Second Thing is lostt2.data = 5; // Modifies first thing$display(t1.data); // Displays “5”

end

data=1

t1

t2

data=2

Page 70: SystemVerilog Testbench

70

SystemVerilog Testbench with VCS 05/07/2007

Assignment is not a copy

Assignment of one handle to another only affects the handles. It does not copy data

class Thing; int data;

endclass…Thing t1, t2; // Two handlesinitial begint1 = new(); // Allocate first thingt1.data = 1;t2 = new(); // Allocate secondt2.data = 2;t2 = t1; // Second Thing is lostt2.data = 5; // Modifies first thing$display(t1.data); // Displays “5”

end

data=1

t1

t2

data=2

Page 71: SystemVerilog Testbench

71

SystemVerilog Testbench with VCS 05/07/2007

Assignment is not a copy

Assignment of one handle to another only affects the handles. It does not copy data

class Thing; int data;

endclass…Thing t1, t2; // Two handlesinitial begint1 = new(); // Allocate first thingt1.data = 1;t2 = new(); // Allocate secondt2.data = 2;t2 = t1; // Second Thing is lostt2.data = 5; // Modifies first thing$display(t1.data); // Displays “5”

end

data=5

t1

t2

Page 72: SystemVerilog Testbench

72

SystemVerilog Testbench with VCS 05/07/2007

How to copy objects

Assigning handles does not change objects To copy the data, pass it into new:

This is a shallow copy, only data in top object is copied. Your new() is not called!

SystemVerilog does not currently support deep object copy – look for it in a future IEEE version To do a deep copy of all objects, make a copy() method

for all objects nested inside the class.

t2 = new t1;

id=5body

t2

t1

stuffid=5body

t1

stuff

id=5body

t2

Page 73: SystemVerilog Testbench

73

SystemVerilog Testbench with VCS 05/07/2007

Inheritance

How do I share code between classes? Instantiate a class within another class Inherit from one class to another (inheritance/derivation)

Inheritance allows you to ‘add’ extra: Add extra Properties (data members) Add extra Methods Change the behavior of a method

Common code can be grouped into a base class Additions and changes can go into the derived class

Advantages: Reuse existing classes from previous projects with less

debug Won’t break what already works

Page 74: SystemVerilog Testbench

74

SystemVerilog Testbench with VCS 05/07/2007

Inheritance

Add additional functionality to an existing class

class Transaction;reg [31:0] src, dst, data[1024], crc;

endclass

Extended a class with new fields

class BadTr extends Transaction;rand bit bad_crc;

endclass

BadTr = Transaction + bad_crc

Transactionsrc

data

BadTrbad_crc

dst

crc

BadTr bt;bt = new;bt.src = 42;bt.bad_crc = 1;

Page 75: SystemVerilog Testbench

75

SystemVerilog Testbench with VCS 05/07/2007

Inheritance

Change the current functionality of a classclass Transaction;

reg [31:0] src, dst, data[1024], crc;function void calc_crc();crc = src ^ dst ^ data.xor;

endfunctionendclass

Override existing fields to a class

class BadTr extends Transaction; rand bit bad_crc;function void calc_crc();crc = super.calc_crc();if (bad_crc) crc = ~crc;

endfunctionendclass

Transactionsrc

data

dst

crc

BadTrbad_crc

calc_crc

calc_crc

Page 76: SystemVerilog Testbench

76

SystemVerilog Testbench with VCS 05/07/2007

program good_test;Transaction tr;task main();assert(tr.randomize());my_driver.send(tr);endtask

endprogram

class BadTr extends Transaction;rand bit bad_crc;function void calc_crc();

endclass

class Transaction;function void calc_crc();endclass

Inheritance

Create a transactor that works with a base object Extend the transaction class to inject errors Send these into the transactor from the test

Error injection

class Driver;task send(Transaction tr);tr.calc_crc();// Drive interface signals

endtaskendclass

class Transaction;virtual function void calc_crc();

endclass

class BadTr extends Transaction;rand bit bad_crc;virtual function void calc_crc();

endclass

program BadTest;BadTr bt = new;task main();assert(bt.randomize());my_driver.send(bt);

endtaskendprogram

Page 77: SystemVerilog Testbench

77

SystemVerilog Testbench with VCS 05/07/2007

Transaction

BadTr

src

data

dst

crc

bad_crc

calc_crc

calc_crc

Overriding Methods

By default, a method is found using the handle type What happens when extended object is referenced

by a base handle?

Inheritance allows methods to be overridden

task main();Transaction tr;BadTr bt;tr = new();bt = new();

tr.calc_crc();bt.calc_crc();

tr = bt;tr.calc_crc();

endtask

class Transaction;reg [31:0] crc;function void calc_crc();

endclass

class BadTr extends Transaction;bit bad_crc;function void calc_crc();

endclass

Oops, this extended objectjust used base class method!

Page 78: SystemVerilog Testbench

78

SystemVerilog Testbench with VCS 05/07/2007

Transaction

BadTr

src

data

dst

crc

bad_crc

calc_crc

calc_crc

task main();Transaction tr;BadTr bt;tr = new();bt = new();

tr.calc_crc();bt.calc_crc();

tr = bt;tr.calc_crc();

endtask

Polymorphism

Allow a single name refer to many methods

class Transaction;reg [31:0] crc;virtual function void

calc_crc();endclass

class BadTr extends Transaction;bit bad_crc;virtual function void

calc_crc();endclass Virtual method so…

‘tr’ is really ‘bt’ => BadTr=> call BadTr.calc_crc();

Virtual – lookup method at runtime, not compile The object’s type is used to find the right method

Analogous to virtual memory that can have many locations

Page 79: SystemVerilog Testbench

79

SystemVerilog Testbench with VCS 05/07/2007

Handle Assignment

Handles for base and extended class

class Transaction;reg [31:0] src, dst;virtual function void calc_crc();

endclass

class BadTr extends Transaction;bit bad_crc;virtual function void calc_crc();

endclass

Extend

src, dst Base

bad_crc

The handles for the base and extended classes are not interchangeable A base handle can not access extended properties

Transaction tr;BadTr bt, b2;bt = new(); // Allocate extended objecttr = bt; // Assign to base handletr.calc_crc(); // Calculate CRCb2 = tr; // Error! Not allowed$cast(b2, tr); // Allow assignif ($cast(b2, tr)) // Check if legal

b2.calc_crc();

Compile check

Run-time check

Page 80: SystemVerilog Testbench

80

SystemVerilog Testbench with VCS 05/07/2007

Inheritance

Why do I want all this complexity? Driver will treat all transactions the same way Transaction class knows how to perform actions

Cell.display() Print ATM cell data if I’m at ATM cell Print Ethernet MCA data if I’m an Ethernet packet Print Sonet frame data if I’m a Sonet frame Print USB packet data if I’m a USB packet

Code calling display doesn’t need to know what type of cell/packet ‘cell’ handle references

Classes are self-contained, they know how to perform actions on themselves based on their type

Self-contained, robust, reusable code.

Page 81: SystemVerilog Testbench

81

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 82: SystemVerilog Testbench

82

SystemVerilog Testbench with VCS 05/07/2007

Randomization

What Are We Going to Discuss? Why use randomization Randomization options Randomization of objects Class constraints and distributions In-line constraints and distributions Tricks and techniques

Page 83: SystemVerilog Testbench

83

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Why Use Randomization? Automatic stimulus generation

Change the characteristics of the data driving the DUT

Random setting of parameters Select ports, addresses, operational parameters randomly.

Directed testing detects the bugs you expect. Random testing detects the bugs you did not expect.

A random test’s behavior depends on the seed If you run the same test with the same seed, you will get the

same behavior If you run the same test with many different seeds, you will get

the equivalent of many different tests

Page 84: SystemVerilog Testbench

84

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Randomization Example

program automatic test;

class Transaction;rand bit [31:0] src, dst, data[]; // Dynamic array randc bit [2:0] kind; // Cycle through all kinds constraint c_len { data.size inside {[1:1000]}; } // Limit array size

endclass

Transaction tr;

initial begintr = new();assert(tr.randomize());send(tr);end

endprogram

rand: rolling dicerandc: dealing cards

Page 85: SystemVerilog Testbench

85

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Randomization of Objects Random variables

rand – returns values over the entire range randc – random cyclic value up to 16 bits

Object variables are randomized by randomize() The method is automatically available to classes with random

variables. Returns a 1 upon success, 0 on failure

Optional: pre_randomize() & post_randomize() void functions which will be called automatically pre_randomize() – set up random weights post_randomize() – cleanup calculations like CRC Remember calc_crc ?

Always checkrandomize()

Presenter
Presentation Notes
Verified – VCS allows randc up to 16 bits
Page 86: SystemVerilog Testbench

86

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Constraining Randomness Purely random stimulus takes too long to do something

interesting Specify the interesting subset of all possible stimulus with

constraint blocks You can define separate, non-overlapping constraints for different

tests

Constraints and distribution weights can form the basis for a “test writer interface” to your testbench

User-Created Test:- subset of legal stimulus vectors- subset of legal stimulus sequences

Your Testbench:- all legal stimulus vectors- all legal stimulus sequences

SIM

Page 87: SystemVerilog Testbench

87

SystemVerilog Testbench with VCS 05/07/2007

constraint c_default {data.size <= 1000;data.size > 0;kind == 0; // Equivalent, not assignment cntrl inside {[2:10], 20, 40, [100:107]};if (test_mode == CONGEST)

dest inside {[src-100:src+100]};}

constraint c_long {data.size > 5000;

}

Randomization

Class Constraints Constraint Blocks

Made of relational expressions, not assignments

Constraints can be dynamically enabled/disabled with: handle.[constraint_name.]constraint_mode(1/0)

Unsolvable or conflicting constraints cause a run-time error

Disable this with:handle.c_long.constraint_mode(0)

Page 88: SystemVerilog Testbench

88

SystemVerilog Testbench with VCS 05/07/2007

constraint c_0 {src dist {0:=30, [1:3]:=60};dst dist {0:/30, [1:3]:/60};

}

Randomization

Distributions dist constraint

Distribution weights can be variables or constants

Weighted probabilities := assigns weight to each element:/ divides weight evenly in range

Distributions do not have to add up to 100%

Value Dist0 30/901 20/902 20/903 20/90

Value Dist0 30/2101 60/2102 60/2103 60/210

Page 89: SystemVerilog Testbench

89

SystemVerilog Testbench with VCS 05/07/2007

Randomization

In-Line Constraints and Distributions

initial beginTransaction t = new();s = t.randomize() with {src >= 50; src <= 1500; dst < 10;}; driveBus(t);

// force src to a specific values = t.randomize() with { src == 2000; dst > 10;};driveBus(t);

end

Constraints may be defined at the time of randomization Allows test-specific constraints Don’t modify the original class for just a single test

In-line constraints are additive with existing class constraints

Supports all SystemVerilog constraints and distributionsclass Transaction;

rand bit [31:0] src, dst, data[1024];constraint valid {src inside{[0:100], [1000:2000]}; }

endclasssrc: 50-100, 1000-1500

dst<10

src==2000dst>10

Page 90: SystemVerilog Testbench

90

SystemVerilog Testbench with VCS 05/07/2007

Randomization

The solver has to handle algebraic factoring, complex Boolean expressions, mixed integer and bit expressions and more

All constraints interact bidirectionally and are solved concurrently

Keep in mind rules regarding precedence, sign extension, truncation and wrap-around when creating constraints

SystemVerilog requires a strong constraint solver!

class Parameters;rand bit [15:0] a, b, c, d, e, f; constraint c_0 {(a + b) < 4;0<c; c<d; d<e; e<150;f == e % 16’d6; // Restrict width for: * % /

}endclass

Page 91: SystemVerilog Testbench

91

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Conditional operator: if … else if … else Behaves like a procedural “if”, except the conditionals

are evaluated bi-directionally. Equivalent to implication.

Implication Operator: -> Short version of “if” Ex: (mode == SMALL) -> (data.size < 10);

Global Constraints: x < other_object.y; References to rand object data members in the

constraints get solved simultaneously

Variable ordering: solve x before y; Otherwise VCS solves all constraints simultaneously

Constraint constructs in SystemVerilog

Page 92: SystemVerilog Testbench

92

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Create a random array Constrain its size, individual elements, or all elements

class C;rand bit [5:0] a[];constraint cc {a.size inside {[1:5]};array[0] > 0;foreach (a[i])if (i > 0)a[i] > a[i-1]);

}function void pre_randomize;a.delete; // Needed in 2005.06

endfunctionendclass

// Outputa[0] = 1;a[1] = 2;a[2] = 33;a[3] = 39;a[4] = 40;

Array constraints

Array size

Single element

Multiple elements

Page 93: SystemVerilog Testbench

93

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Set valid on 3 cycles out of 5

Two foreach loops with relationships Constraints solved

simultaneously x[] in 1:8 y[] in 2:9

Array Constraints

class ValidOn;rand bit valid[5];constraint cv{valid.sum == 32’d3;}

endclass

class E;rand bit [15:0] x[10], y[10];constraint size_cons {

foreach (x[i]){x[i] > 0; x[i] < y[i];

foreach (y[i])y[i] inside {[1:9]};

}endclass

Page 94: SystemVerilog Testbench

94

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Watch out for signed variables What are legal values for first and second?

Make instances rand Or they won’t be randomized

Don’t call randomize() in new() constructor Test may want to change constraints first

Use rand_mode to make a variable random / non-random env.first.rand_mode(0);

Just replace result of randomization for a directed test

Tricks and Techniques

class Nesting;rand SubClass data;

endclass

class Environment;rand byte first, second;constraint c {

first + second < 8’h40; }

endclass

first second

9. ‘h09 20. ‘h14

85. ‘h55 -70. ‘hba

-20. ‘hec -32. ‘he0

Presenter
Presentation Notes
A possible solution is first = 40, second = -39, probably not what you wanted.
Page 95: SystemVerilog Testbench

95

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Need to modify a constraint in a test? Use a variable in the constraint

Extend the base class to override original constraint

Use constraint_mode() to turn it off

More Tricks and Techniques

class Base;rand int size;constraint c {size inside {[1:10]};}

endclass

class Bigger extends Base;constraint c {size inside {[1:1000]};}

endclass

rand int size;int max_size = 100;constraint c {size inside {[1:max_size]}; }

Presenter
Presentation Notes
Most people forget about constraint_mode() from the original slide
Page 96: SystemVerilog Testbench

96

SystemVerilog Testbench with VCS 05/07/2007

Randomization

Want to randomize without a class? Use randcase or $urandom_range

Good for creating single variable, stateless code, or nested set of actions

Constrained randomization is easier to modify, and can make state variables for scoreboard The bad_crc variable can be used for both

generating stimulus and checking the response

Procedural randomization

randcase1: len = $urandom_range(0, 2); // 10%: 0, 1, or 2 8: len = $urandom_range(3, 5); // 80%: 3, 4, or 51: len = $urandom_range(6, 7); // 10%: 6 or 7

endcase

Presenter
Presentation Notes
You will need some state information when you check the DUT’s response. For example, did you send a transaction with an error? If you use randomize, you probably have an error variable. Nested actions – like the Sequence Generator. Choose a Read, Write, or IO command. For Read, choose a Single, or Burst.
Page 97: SystemVerilog Testbench

97

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Language Basics Connecting to HDL OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 98: SystemVerilog Testbench

98

SystemVerilog Testbench with VCS 05/07/2007

Controlling Threads

What Are We Going to Discuss? The power of parallel threads Concurrency defined Creating and controlling threads Communication between threads

Page 99: SystemVerilog Testbench

99

SystemVerilog Testbench with VCS 05/07/2007

Port0

port7

DUTport1

---

port0

port7

port1

---

Create stream of transactions Check received

transactions

Functional Coverage

Self-

Checking

Sent transactions to all ports?

FIFO overflow checked?

DataGeneration

Concurrency is Essential for Verification

The Power of Threads

Page 100: SystemVerilog Testbench

100

SystemVerilog Testbench with VCS 05/07/2007

join_anyjoin_none

Threads

join

Fork / Join The execute() task runs in parallel with the begin-end block. The tasks generate() and check() run serially.

forkexecute();begingenerate();check();

endjoin_none

forkfork fork

Page 101: SystemVerilog Testbench

101

SystemVerilog Testbench with VCS 05/07/2007

Threads

Creating and Controlling Threads:

fork / join | join_none | join_any create threads disable label; terminate just the named block disable fork; terminate all child threads below the current

context level Use carefully – may stop more threads than you wanted!

wait fork; suspend a process until all children have completed execution

wait (expression) suspend a process until the expression is true Level sensitive

@(edge-exp) suspend a process until the edge-exp value changes Edge sensitive

Presenter
Presentation Notes
The warning on “disable fork” is needed as users often kill off too much
Page 102: SystemVerilog Testbench

102

SystemVerilog Testbench with VCS 05/07/2007

Threads

If there are multiple threads ready to execute at a given simulation time, their order of execution is indeterminate

Execution order for threads scheduled at the same time can be manipulated within the code

// Timeout example

fork : check_block

wait (arbif.cb.grant == 1); // May never complete

#1000 $display(“@%0d: Error, grant never received”, $time);

join_any

disable check_block;

Presenter
Presentation Notes
This slide needs some spice!
Page 103: SystemVerilog Testbench

103

SystemVerilog Testbench with VCS 05/07/2007

Communication Between Threads

MailboxExchange messages / objects between two threads

FeaturesFIFO with no size limitget/put are atomic operations, no possible race conditionsCan suspend a processDefault mailbox has no data typeQueuing of multiple threads is fair

mailbox mbx; // Declare a mailboxmbx = new(); // allocate mailboxmbx.put(p); // Put p object into mailboxmbx.get(p); // p will get object removed from FIFOsuccess = mbx.try_get(p); // Non-blocking versionmbx.peek(p); // Look but don’t remove, can blocksuccess = mbx.try_peek(p); // Non-blocking versioncount = mbx.num(); // Number of elements in mailbox

Page 104: SystemVerilog Testbench

104

SystemVerilog Testbench with VCS 05/07/2007

Communication Between ThreadsMailbox Example

class Generator;Transaction t;task main;

repeat (10) begint = new();assert(t.randomize());mbx.put(t);

endendtaskendclass

class Driver;Transaction t;

task main;repeat (10) begin

mbx.get(t);@(posedge busif.cb.ack);busif.cb.addr <= t.addr;busif.cb.kind <= t.kind;…

endendtask

program mailbox_example(…);mailbox mbx = new();Generator g = new();Driver d = new();initial begin

forkg.main();d.main();

joinend endprogram

Allocate mailbox

Put data into mailbox

Get data from mailbox

Page 105: SystemVerilog Testbench

105

SystemVerilog Testbench with VCS 05/07/2007

Communication Between Threads

Semaphore

Used for mutual exclusion and synchronization.

FeaturesVariable number of keys can be put and removedControlled access to a shared object, such as sharing a bus from models

Think of two people wanting to drive the same car – the key is a semaphoreBe careful – you can put back more keys than you took out!

Syntaxsemaphore sem;sem = new(optional_initial_keycount = 0); sem.get(optional_num_keys = 1);sem.put(optional_num_keys = 1);

Presenter
Presentation Notes
I hate BNF…
Page 106: SystemVerilog Testbench

106

SystemVerilog Testbench with VCS 05/07/2007

Communication Between Threads

Semaphore Example

…task sequencer();

repeat($random()%10) @bus.cb;sendTrans();

endtask

task sendTrans();sem.get(1);@bus.cb;bus.cb.addr <= t.addr;bus.cb.kind <= t.kind;bus.cb.data <= t.data;sem.put(1);

endtaskendprogram

Wait for bus to be available

When done, replace key

program automatic test;semaphore sem;initial beginsem = new(1);forksequencer();sequencer();

join end

Allocate a semaphore, 1 key available

Page 107: SystemVerilog Testbench

107

SystemVerilog Testbench with VCS 05/07/2007

Communication Between Threads

Events

Synchronize concurrent threads

Features Synchronize parallel threads Sync blocks process execution until event is triggered Events connect triggers and syncs Can be passed into tasks

event ev; // Declare event-> ev; // Trigger an event@ev; // Block process, wait for future event wait (ev.triggered); // Block process, wait for event,

// including this timeslot// Reduces race conditions

driver = new(ev); // Pass event into task

Page 108: SystemVerilog Testbench

108

SystemVerilog Testbench with VCS 05/07/2007

Communication Between Threads

Event ExampleGenerator transactor

event gen_done[4];

Generator gen[4];

initial begin// Instantiate testbenchforeach (gen[i])gen[i] = new(gen_done[i]);

// Run transactorsgen[i].main();…

// Wait for finishforeach (gen[i])wait(gen_done[i].triggered);

end

class Generator;event done;// Pass event from TBfunction new (event done);this.done = done

endfunction

task main( );forkbegin// Create transactions-> done;end

join_noneendtask

endclass

Main Testbench

Page 109: SystemVerilog Testbench

109

SystemVerilog Testbench with VCS 05/07/2007

Lab 2

Verify the APB Interface, Part 1

Objective Write a structured testbench to learn more about classes,

randomization, threads and mailboxes Verify that a basic transaction can be created, randomized, and

sent through the design

Time Allotted 1 hour

Page 110: SystemVerilog Testbench

110

SystemVerilog Testbench with VCS 05/07/2007

Lab 2

apb_trans

apb_gen

apb_master

apb_mbox

DUT

Page 111: SystemVerilog Testbench

111

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 112: SystemVerilog Testbench

112

SystemVerilog Testbench with VCS 05/07/2007

Virtual Interfaces

What Are We Going to Discuss? Virtual interfaces

Why are they needed? Creating virtual interfaces Connecting to physical interfaces Using in classes and methods

Page 113: SystemVerilog Testbench

113

SystemVerilog Testbench with VCS 05/07/2007

Virtual Interfaces

Virtual Interfaces Allow grouping of signals by function Create a handle to an interface

Virtual interfaces can be passed to routines with different values.

Promotes reuse by separating testbench from implementation names

Advancedtopic

4x4ATM

Switch

enable_1

soc_1

data_1[7:0] RX_1

enable_3

soc_3

data_3[7:0] RX_3

Page 114: SystemVerilog Testbench

114

SystemVerilog Testbench with VCS 05/07/2007

Virtual Interfaces

1. Define physical interfacesUse clocking blocks and modports

2. Connect the interfacesUsually in top netlist

3. Create procedural code that uses virtual interfaceA generic method that is not tied to any one interface

4. Create virtual interface & connect to physicalProcedural code in testbench

5. Use virtual interfaces with classes and methodsA generic method can operate on many interfaces

The Five Steps to Virtual Interfaces

Page 115: SystemVerilog Testbench

115

SystemVerilog Testbench with VCS 05/07/2007

Virtual Interfaces

Virtual Interfaces Syntax

// ATM Rx interfaceinterface Rx (input logic clk);logic [7:0] data;logic soc, en, clav;

clocking Rcb @(posedge clk);output data, soc, clav; // Relative toinput en; // testbench

endclocking : Rcb

modport DUT (output en, // DUT connectioninput data, soc, clav);

modport TB (clocking Rcb); // TB connectionendinterface : Rx

STEP 1: Define a physical interface

Page 116: SystemVerilog Testbench

116

SystemVerilog Testbench with VCS 05/07/2007

Virtual Interfaces

Binding signals to a physical interface STEP 2: Connect the interface

module top;logic clk = 0;

Rx Rx0(clk), Rx1(clk), Rx2(clk), Rx3(clk);Tx Tx0(clk), Tx1(clk), Tx2(clk), Tx3(clk);

atm_switch a1 (Rx0, Rx1, Rx2, Rx3, Tx0, Tx1, Tx2, Tx3, clk);

test t1 (Rx0, Rx1, Rx2, Rx3, Tx0, Tx1, Tx2, Tx3, clk);

always #20 clk = !clk;endmodule : top

Interfacename

Interfaceinstances

Page 117: SystemVerilog Testbench

117

SystemVerilog Testbench with VCS 05/07/2007

Virtual Interfaces

Define virtual interface

class Driver;virtual Rx.TB Rx;

function new(virtual Rx.TB Rx);this.Rx = Rx; // Initialize VI

endfunction

task sendCell();Rx.Rcb.soc <= 0; // Drive signal w/clocking block...

endtask

endclass

STEP 3: Define procedural code that uses virtual interface Interface

& modport

Presenter
Presentation Notes
“typedef virtual” is not yet supported – this will simplify the above code
Page 118: SystemVerilog Testbench

118

SystemVerilog Testbench with VCS 05/07/2007

Virtual Interfaces

Using Virtual Interfaces STEP 4: Define virtual interface & connect to physical STEP 5: Call routine with virtual interface variablesprogram automatic test(Rx.TB Rx0, Rx1, Rx2, Rx3, … );

`include “driver.vh”

Driver driver[4];

virtual Rx.TB vRx[4];

initial begin

vRx[0] = Rx0; …

for (int i=0; i<4; i++)

driver[i] = new(vRx[i]);

driver[$random % 4].sendCell(); // Send to random port

end

One variable in the method references different connections. This allows for a single class to operate on many physical interfaces.

Presenter
Presentation Notes
2005.06 bugs: can not have foreach(driver[i]) driver[i].property = 0; // VCS thinks i is being modified Does not support: typedef virtual Rx.tb vRx_t; // chokes on “virtual” keyword can VCS initialize array of virtual interfaces: virtual Rx.TB vRx[4] = {Rx0, Rx1, Rx2, Rx3}; ??
Page 119: SystemVerilog Testbench

119

SystemVerilog Testbench with VCS 05/07/2007

Lab 3

Verify the APB Interface, Part 2

Objective Create virtual interfaces for communication between

design and testbench

Time Allotted 1 hour

Page 120: SystemVerilog Testbench

120

SystemVerilog Testbench with VCS 05/07/2007

Lab3

apb_trans

apb_gen

apb_master

apb_mbox

DUT

apb_monitor

scoreboard mon2scb

mas2scb

Page 121: SystemVerilog Testbench

121

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 122: SystemVerilog Testbench

122

SystemVerilog Testbench with VCS 05/07/2007

Functional Coverage Example

program automatic test(busifc.TB ifc);class Transaction;rand bit [31:0] src, dst, data;rand bit [ 2:0] kind;

endclass

covergroup CovKind;coverpoint tr.kind; // Measure coverage

endgroup

Transaction tr = new(); // Instantiate transaction CovKind ck = new(); // Instantiate group

initial beginrepeat (32) begin // Run a few cyclesassert(tr.randomize());ifc.cb.kind <= tr.kind; // Transmit transaction ifc.cb.data <= tr.data; // onto interface ck.sample(); // Gather [email protected]; // Wait a cycleend

endendprogram

Have I tried all transaction kinds?

Page 123: SystemVerilog Testbench

123

SystemVerilog Testbench with VCS 05/07/2007

Sample HTML Reports

Page 124: SystemVerilog Testbench

124

SystemVerilog Testbench with VCS 05/07/2007

Coverage Group

Encapsulates the coverage specification (bins, transitions) for a set of coverpoints and cross combinations of coverpoints

Variables in a group belong together: Data members of a class Cross coverage across these variables Sample them on the same event (trigger)

Write specification once (just like a class definition), Instantiate many times

Define your coverage model

covergroup CovKind @(posedge ifc.cb.valid);coverpoint global;coverpoint ifc.cb.kind;

endgroup…CovKind ck = new;

The variable global and signal ifc.cb.kind are

sampled every posedge of ifc.cb.valid signal

Page 125: SystemVerilog Testbench

125

SystemVerilog Testbench with VCS 05/07/2007

Embedded Coverage Group

Easy way to cover a subset of the members of a class You must instantiate the coverage group to gather results

For efficiency, put coverage groups in “static” objects A simulation could have 10,000 transactions, but just 1 driver object

SystemVerilog automatically creates bins for cover points without having to specify the bins explicitly

class Driver;bit [3:0] x, y;covergroup cg;coverpoint x;coverpoint y;

endgroupfunction new;cg = new;

endfunctionendclass

Members x and y will be sampled on the active

edge of the ifc.cb clock.

Embed covergroup in a class

Page 126: SystemVerilog Testbench

126

SystemVerilog Testbench with VCS 05/07/2007

bit [3:0] x, y;covergroup Cov1;

coverpoint x;coverpoint y;

endgroup…Cov1 c1 = new();x = 1;y = 8;c1.sample();x = 2;c1.sample();x = 15;y = 9;c1.sample();

Automatic Bin Creation (Example 1)

Level where coverage “counts”

Page 127: SystemVerilog Testbench

127

SystemVerilog Testbench with VCS 05/07/2007

bit [3:0] x, y;covergroup Cov1;

coverpoint x;coverpoint y; // Divide ranges in 1/2option.auto_bin_max = 2;

endgroup…Cov1 c1 = new();x = 1;y = 8;c1.sample();x = 2;c1.sample();x = 15;y = 9;c1.sample();

Automatic Bin Creation (Example 2)

Page 128: SystemVerilog Testbench

128

SystemVerilog Testbench with VCS 05/07/2007

User Defined Coverage Bins for Coverpoints

User defined bins for coverage using ranges of values Bin lo is associated with values of port_number between 0 and 1 Bin hi_4 to hi_7 are associated with values between 4 and 7 Bin misc is associated with values 2 & 3 Transition bin t1 is associated with any value transition (single) of

port_number from 0=>1, 0=>2, 0=>3

logic [2:0] port_number;covergroup CovPorts;coverpoint port_number {bins lo = {[0:1]}; // 1 bin for 2 valuesbins hi[] = {[4:$]}; // 4 separate binsbins misc = default; // Unspecified valuesbins t1 = (0=>1), (0=>2), (0=>3); // transitions

}endgroup

0: lo1: lo2: misc3: misc4: hi_45: hi_56: hi_67: hi_7

Page 129: SystemVerilog Testbench

129

SystemVerilog Testbench with VCS 05/07/2007

If you create bins with the [] syntax, VCS will not create new bins for values that are out of bounds

bit [3:0] x, y;covergroup Cov1;

coverpoint x { bins s[] = {[0:4]};

}coverpoint y;

endgroup…Cov1 c1 = new();x = 1;y = 8;c1.sample();x = 2;c1.sample();x = 15;y = 9;c1.sample();

Automatic Bin Creation (Example 3)

Out of bounds value ignored

Coverageholes

Page 130: SystemVerilog Testbench

130

SystemVerilog Testbench with VCS 05/07/2007

Cross Coverage

Specified in the coverage group using cross Cross argument can be a coverpoint or variable Bins are automatically created for the cross products

bit [3:0] globalclass MyClass;

bit [4:0] y;covergroup cg;

cc1: cross y, global;endgroupfunction new;cg = new;

endfunctionendclass…MyClass obj1 = new();obj1.y = ‘h14;global = 2;obj1.cg.sample();obj1.cg.sample(); obj1.y++;obj1.cg.sample();

Use label forcoverage report

Page 131: SystemVerilog Testbench

131

SystemVerilog Testbench with VCS 05/07/2007

Defining the Sample Event

Specifying the coverage event You can specify an event expression in the coverage group

definition. This will be used for all instances of a coverage definition.

Or use instance.sample();

Valid event expressions @SV_event; @(SV_variable);

You can use interface signals, including ones in clocking blocks

Values are sampled upon occurrence (triggering) of the coverage event expression

Page 132: SystemVerilog Testbench

132

SystemVerilog Testbench with VCS 05/07/2007

Assertion Coverage

A covergroup can react to a SystemVerilog Assertion Use SVA action block to trigger event, Have covergroup sample on event

program automatic test;

covergroup Write_cg @$root.mem.write_event;coverpoint $root.mem.data;coverpoint $root.mem.addr;option.auto_bin_max = 2;

endgroup

Write_cg wcg;

initial beginwcg = new();// Apply stimulus here#10000 $finish;

endendprogram

module mem(simple_bus sb);bit [7:0] data, addr;event write_event;cover property (@(posedge clk) write_ena==1)-> write_event;

// Other logic hereendmodule

SVA

Page 133: SystemVerilog Testbench

133

SystemVerilog Testbench with VCS 05/07/2007

Coverage

VCS writes coverage data to a binary database file The database file is named simv. db

VCS report formats HTML > urg –dir simv.vdb Text: > urg –dir simv.vdb –format text HTML data presented hierarchically using hypertext links

$set_coverage_db_name ( name ); Sets the filename of the coverage database into which

coverage information is saved at the end of a simulation run.

$load_coverage_db ( name ); Load from the given filename the cumulative coverage

information for all coverage group types.

Databases

Presenter
Presentation Notes
We need examples of all of this.
Page 134: SystemVerilog Testbench

134

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 135: SystemVerilog Testbench

135

SystemVerilog Testbench with VCS 05/07/2007

Starting Point : Design Spec and Test Plan

Design Spec:• A packet consists address in valid address range and variable

sized payload.• The valid address range is between 0 and 8’hBF.• Data length support is max 1024 bytes transfers

Test Plan (Partial): Define 3 address regions as [0:0x3F], [0x40:0x7F]

and[0x80:0xBF].

Page 136: SystemVerilog Testbench

136

SystemVerilog Testbench with VCS 05/07/2007

More Complete Class Example

class packet;typedef enum {WRITE, READ} transtype_t;rand bit [`ADDR_WIDTH:0]addr;rand bit [`DATA_WIDTH-1:0] data[];rand transtype_t trans_type;

constraint addr_c {addr inside {[0:8’hBF]};}

constarint data_c {data.size <= 1024;

}

task display();$display(“ %s, %h”, pkt.trans_type.name(), a

endtask

covergroup pktCov;coverpoint addr,data,trans_type;endgroup

endclass

DataMembers

ConstraintBlock

Procedural Code

Coverage Group

Classes are containers of data objects, transactors, generators, verification environments, etc.

Page 137: SystemVerilog Testbench

137

SystemVerilog Testbench with VCS 05/07/2007

Coverage Driven Verification

Start with a fully randomizable testbench Run many randomized simulation runs Analyze cumulative coverage and coverage holes

Then with minimal code changes: Add constrained stimulus to fill coverage holes Make few directed tests to hit the remaining holes

ConstrainableRandom Generation

FunctionalCoverage

Many runs,different seeds

Identifyholes

Addconstraints

Minimal CodeModifications

DirectedTestcase

Page 138: SystemVerilog Testbench

138

SystemVerilog Testbench with VCS 05/07/2007

Capture Input Stimulus and RandomizeDesign Spec: A packet consists of a destination address and a

variable sized payload.

Implementation: Declare variables as rand so constraint solver will fill with random values.

class packet;

rand bit [31:0]addr;rand bit [7:0] data[];rand transtype_t trans_type;

endclass

program automatic test;packet pkt;initial beginpkt = new();repeat(50) beginpkt.randomize(); transmit(pkt);

endendendprogram

Basic TestPacket Class

Page 139: SystemVerilog Testbench

139

SystemVerilog Testbench with VCS 05/07/2007

Constrain the Randomness (Design Spec)Design Spec: • Size of the payload is between 0 and 1024 bytes.

Implementation:• Without constraints, VCS solver generates random data which may be

illegal and will either be ignored by device or result in errors. Add a new control field pktSize.

class packet;

rand bit [31:0]addr;rand bit [7:0] data[];rand transtype_t trans_type;rand bit[7:0] pktSize;

constraint packetSize_c {

pktSize inside {[0:1024]};

data.size() == pktSize;

}endclass

Page 140: SystemVerilog Testbench

140

SystemVerilog Testbench with VCS 05/07/2007

Constrain the Randomness (Design Spec)Design Spec:• The valid address range is between 0 and 8’hBF. • Address 8’hBB is not writable

Implementation: See below.

class packet;

rand bit [31:0]addr;rand bit [7:0] data[];...rand transtype_t trans_type;

constraint addr_c {

(trans_type == WRITE) -> addr != 8'hBB;

addr inside {[0:8’hBF]};

}endclass

Implication Constraints

Page 141: SystemVerilog Testbench

141

SystemVerilog Testbench with VCS 05/07/2007

Directed Random Testing

Test Plan: Test device with WRITE type , data size 20 bytes at address

8’h55.

Implementation: Override constraint custom_c. Same testbench as before.

constraint packet::custom_c {pktSize == 20;trans_type == WRITE;addr == 8’h55;

}

Page 142: SystemVerilog Testbench

142

SystemVerilog Testbench with VCS 05/07/2007

Change Default Distribution

Test Case: Test device with 80% WRITE and 20% READ.

Implementation: Use distribution constraint to change probability Minimal declarative changes needed for new testcase

class packet;rand address_e addrTyp;

.

.constraint custom_c;

endclass

constraint packet::custom_c {trans_type dist {WRITE:=80, READ:=20

program automatic test;packet pkt;initial beginpkt = new();pkt.randomize();transmit(pkt);

endendprogram

Test with 20% READ transPacket Class

Page 143: SystemVerilog Testbench

143

SystemVerilog Testbench with VCS 05/07/2007

Directed Random Stimulus Generation

Test Plan: Inject the device with 50 WRITE packets mostly targeting the hi_range of addresses.

Implementation: Add a test specific constraint to direct generation to the area of interest. Create an instance of the packet class in the test and randomize 50 times.

constraint packet::custom_c { addr dist {[8’h80:8’hBF] := 90, [0:8’h7F] := 10};trans_type == WRITE;

}

program automatic test;packet pkt;initial beginpkt = new();repeat(50) if (pkt.randomize())transmit(pkt);

endendprogram

Page 144: SystemVerilog Testbench

144

SystemVerilog Testbench with VCS 05/07/2007

Derive Coverage Model From Test Plan

Test Plan: • Define 3 address regions: 0:0x3F, 0x40:0x7F and 0x80:0xBF• Test with packets of all types = 2 bins• Test with packets targeted to all address regions = 3 bins• Test with all permutations of all packets types to all address

regions = 6 bins

• Implementation:• Do not write directed test for each test item• Instead map each test item into an executable coverage point• Run random suite of tests and collect functional coverage.• Analyze coverage results and to improve functional coverage

either run more random tests or for hard-to-reach coverage points create a more constrained test (Directed random).

Page 145: SystemVerilog Testbench

145

SystemVerilog Testbench with VCS 05/07/2007

Implement Coverage Model

covergroup pktCov;

coverpoint trans_type; // Creates 2 bins

coverpoint addr { // Item 2: Creates 3 bins

bins low_range = {[0:0x3F]};

bins mid_range = {[0x40:0x7F]};

bins hi_range = {[0x80:0xBF]};

}

cross trans_type, dst; // Item 5: Creates 6 bins

endgroup

Page 146: SystemVerilog Testbench

146

SystemVerilog Testbench with VCS 05/07/2007

Lab 4

Implementing Coverage

Objective Add functional coverage to the APB Interface Create a constrained random test Use this test to make directed test Analyze the functional coverage in URG

Time Allotted 1 hour

Page 147: SystemVerilog Testbench

147

SystemVerilog Testbench with VCS 05/07/2007

Agenda Introduction Methodology Introduction Getting Started Testbench Environment Language Basics OOP Basics Randomization Controlling Threads Virtual Interfaces Functional Coverage Coverage Driven Verification Testbench Methodology

Page 148: SystemVerilog Testbench

148

SystemVerilog Testbench with VCS 05/07/2007

Testbench Methodology

What Are We Going to Discuss? Reference Verification Methodology Testbench Structure Simple Testbench Building Blocks

Page 149: SystemVerilog Testbench

149

SystemVerilog Testbench with VCS 05/07/2007

Testbench Methodology - ArchitectureLayers

Constrained random tests

DUT

Driver

Transactor

Generators

Tests

Monitor

CheckerSelf Check

Test

Scenario

Functional

Command

Signal

Func

tiona

l Cov

erag

e

Assertions

Page 150: SystemVerilog Testbench

150

SystemVerilog Testbench with VCS 05/07/2007

Testbench Methodology - Overview

How do you use these concepts such as OOP and randomization to build a verification environment?

Synopsys’ Verification Methodology Manual (VMM) contains guidelines, coding styles, and base classes Based on many years of experience

This is an overview to show basic concepts, highlights of the VMM 2-day class

This does NOT show how to use VMM base classes

Page 151: SystemVerilog Testbench

151

SystemVerilog Testbench with VCS 05/07/2007

VMM MethodologyGuiding Principles

Maximize design quality More testcases More checks Less code

Approaches Reuse Across tests Across blocks Across systems Across projects

One verification environment, many tests Minimize test-specific code Assertions

VMM Methodology emphasizes“Coverage Driven Verification”

Page 152: SystemVerilog Testbench

152

SystemVerilog Testbench with VCS 05/07/2007

Transactions and Transactors

Transaction Data models Variant data Error protection

properties Standard methods Constraints

Transaction objects Objects vs. procedures Transaction response

Transactor Categories Master vs. slave Driver vs. monitor

Interfaces Transaction interface Physical interface Sub-layering

Reusable transactors Starting & stopping Notifications Integrating scoreboards Adding functional

coverage Injecting errors Customization and

extensibility

Page 153: SystemVerilog Testbench

153

SystemVerilog Testbench with VCS 05/07/2007

class Transaction;rand enum {READ, WRITE}

kind;rand bit [ 7:0] sel;rand bit [31:0] addr;rand bit [31:0] data;

endclass

Data & TransactionsImplementation

Data modeled using classes Packets Frames Cells Instructions Pixels Samples

Flows through the verification environment 100,000+ instances created and freed during a

simulation 100+ in existence at any given time Duplicated only when necessary

Page 154: SystemVerilog Testbench

154

SystemVerilog Testbench with VCS 05/07/2007

Data & TransactionsFlow

DUT

Driver

Transactor

Generators

Tests

Monitor

CheckerScoreboard

Accumulatedhere

Createdhere

Createdhere

Freedhere

Freedhere

Duplicatedhere

Assertions

Page 155: SystemVerilog Testbench

155

SystemVerilog Testbench with VCS 05/07/2007

TransactionsGenerating Transactions

Simple to generate random streams of data

Can use constraints and solver Add or override constraints via extensions Constraints across multiple instancesclass my_tr extends Transaction;

constraint available_targets {sel inside {[0:3]};if (sel == 0 && kind == READ) {

addr inside {[0:15], 27, 31};} else {

addr < 31;}

}endclass

Transaction tr;tr = new;assert(tr.randomize());apb.do(tr);

Page 156: SystemVerilog Testbench

156

SystemVerilog Testbench with VCS 05/07/2007

TransactionsTransaction Interface

Can use transaction interface object Transactors connected via objects

sw_driver

apb_master

Proceduralinterface

sw_driver

apb_master

Interfaceobject

apb.write(...);

task write(...);

mbx.put(tr);

mbx.get(tr);

Mailbox

Presenter
Presentation Notes
Procedural interface forces a bottom-up verification assembly. You cannot replace (or back-fill) a lower-level transactor without "opening up" the higher level layers of the environment. This also creates a strict naming and typing requirement for compatible transactors. Using a channel decouples the layers so they can be independently instantiated, replaced or connected. One is not aware of the other's presence.
Page 157: SystemVerilog Testbench

157

SystemVerilog Testbench with VCS 05/07/2007

TransactionsTransaction Interface Objects

Can mix and match transactors without modifications

eth_gen

mac.put(tr);

Test

mac_layer

mac.get(tr);

phy.put(tr);

mii_phyphy.get(tr);

gmii_phyphy.get(tr);

xgmii_phyphy.get(tr);

Page 158: SystemVerilog Testbench

158

SystemVerilog Testbench with VCS 05/07/2007

Transactors

Building blocks of the verification environment Transactors modeled using classes

Bus-functional models Functional layer components Generators

Few instances Created at the start of simulation Remain in existence for duration

Data and transactions flow through them Scheduling Transformation Processing

Page 159: SystemVerilog Testbench

159

SystemVerilog Testbench with VCS 05/07/2007

TransactorCategories

Active Transactors – Master Initiate transactions Supply data to other side Example: AHB master, Ethernet Tx

Reactive Transactor – Slave Transaction initiated by other side React by supplying requested data Example: AHB slave

Passive Transactor – Monitor Transaction initiated by other side Collect transaction data from other side Slave monitor example: AHB bus monitor

Page 160: SystemVerilog Testbench

160

SystemVerilog Testbench with VCS 05/07/2007

Creating a transactor

Main routine contains loop that receives a transaction, processes it, and sends it out.

driver(xactor)

generator(xactor)

transactor(xactor)

DUT

class apb_xactor;function new(mailbox mgen, mdrv);

task main();forever begin

mgen.get(t);// process transaction tmdrv.put(t);end

endclass

Page 161: SystemVerilog Testbench

161

SystemVerilog Testbench with VCS 05/07/2007

Generators

Randomizable objects Data streams Configuration Error injection Election

Atomic generators Modifying constraints Run-time generator control Inserting directed stimulus

Scenario generators Atomic scenarios Grammar-based scenarios Defining new scenarios Modifying scenario distributions

scenario generator

scenario

atomic generator

blueprint

Copy

Page 162: SystemVerilog Testbench

162

SystemVerilog Testbench with VCS 05/07/2007

Randomizable AspectsDisturbance Injection

Variations specific to a level of abstraction Delay Collisions Abort/Retry No handshake Data corruption Ordering

Should be controlled in relevant transactor Not at transaction source

eth_gen mac_layer mii_phy

Generate MII-leveldisturbances here

Generate MAC-leveldisturbances hereNot here

Page 163: SystemVerilog Testbench

163

SystemVerilog Testbench with VCS 05/07/2007

Randomize DUT & TB ConfigurationConfigurations

Generated by verification environment

eth_gen mac_layer mii_phyverif_env

cfg_gen

class cfg;...

endclass

Used tobuild

Generatesone instance

eth_gen mac_layer mii_phy

eth_gen mac_layer mii_phy

eth_gen mac_layer mii_phy

ahb_mstrDownloaded

into DUT via...

Page 164: SystemVerilog Testbench

164

SystemVerilog Testbench with VCS 05/07/2007

Self-Checking Functionality

Entirely DUT-specific Can only detect errors

Detected errors identified in planning stage Each error detection mechanism part of coverage model Ensure that opportunity to check error existed No error was actually found

Can be implemented in different ways Transfer function + Scoreboard Reference model Maybe in different language

Off-line Assertions

Self-Checking methodology is a full day topic

Page 165: SystemVerilog Testbench

165

SystemVerilog Testbench with VCS 05/07/2007

Generator DesignControllable Aspects

Good controllable random generators don't "just happen" Design constraint controls

Plan for trivial testcases Generate only 1 object Generate simple objects

Plan for corner cases Scenarios Synchronization

Plan for directed stimulus Interruption Reactivity

Page 166: SystemVerilog Testbench

166

SystemVerilog Testbench with VCS 05/07/2007

Verification EnvironmentExecution Flow

All testbenches must have the same execution flow Some steps may be blank

Extend base environment toimplement DUT-specificenvironment

Basic flow is: pre-test run-test post-test

Randomize testconfiguration descriptor

Start components

Allocate and connectenvironment components

Download testconfiguration into DUT

Stop data generators &Wait for DUT to drain

Check recorded stats &sweep for lost data

End-of-test detection threads(ends when returns)

Presenter
Presentation Notes
Some steps may be trivial for specific DUTs, but all testcases have to execute this type of execution sequence. rvm_env manages the execution to ensure it executes in one direction only.
Page 167: SystemVerilog Testbench

167

SystemVerilog Testbench with VCS 05/07/2007

Onward!

Where do I go next? Complete the labs / and QuickStart

($VCS_HOME/doc/examples) Read the Verification Methodology Manual Take the VMM-Basic and Advanced classes

Please let us know your feedback on this [email protected]

THANK YOU!!!