Sei sulla pagina 1di 294

CUSTOMER EDUCATION SERVICES

SystemVerilog Testbench
Workshop
Student Guide
50-I-052-SSG-001 2005.06-SP1

Synopsys Customer Education Services


700 East Middlefield Road
Mountain View, California 94043

Workshop Registration: 1-800-793-3448

www.synopsys.com
Copyright Notice and Proprietary Information
Copyright  2006 Synopsys, Inc. All rights reserved. This software and documentation contain confidential and proprietary
information that is the property of Synopsys, Inc. The software and documentation are furnished under a license agreement and
may be used or copied only in accordance with the terms of the license agreement. No part of the software and documentation
may be reproduced, transmitted, or translated, in any form or by any means, electronic, mechanical, manual, optical, or otherwise,
without prior written permission of Synopsys, Inc., or as expressly provided by the license agreement.

Right to Copy Documentation


The license agreement with Synopsys permits licensee to make copies of the documentation for its internal use only. Each copy
shall include all copyrights, trademarks, service marks, and proprietary rights notices, if any. Licensee must assign sequential
numbers to all copies. These copies shall contain the following legend on the cover page:

“This document is duplicated with the permission of Synopsys, Inc., for the exclusive use of
__________________________________________ and its employees. This is copy number __________.”

Destination Control Statement


All technical data contained in this publication is subject to the export control laws of the United States of America. Disclosure to
nationals of other countries contrary to United States law is prohibited. It is the reader’s responsibility to determine the applicable
regulations and to comply with them.

Disclaimer
SYNOPSYS, INC., AND ITS LICENSORS MAKE NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO
THIS MATERIAL, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.

Registered Trademarks (®)


Synopsys, AMPS, Arcadia, C Level Design, C2HDL, C2V, C2VHDL, Cadabra, Calaveras Algorithm, CATS, CSim, Design
Compiler, DesignPower, DesignWare, EPIC, Formality, HSPICE, Hypermodel, iN-Phase, in-Sync, Leda, MAST, Meta, Meta-
Software, ModelTools, NanoSim, OpenVera, PathMill, Photolynx, Physical Compiler, PowerMill, PrimeTime, RailMill, RapidScript,
Saber, SiVL, SNUG, SolvNet, Superlog, System Compiler, Testify, TetraMAX, TimeMill, TMA, VCS, Vera, and Virtual Stepper are
registered trademarks of Synopsys, Inc.

Trademarks (™)
abraCAD, abraMAP, Active Parasitics, AFGen, Apollo, Apollo II, Apollo-DPII, Apollo-GA, ApolloGAII, Astro, Astro-Rail, Astro-Xtalk,
Aurora, AvanTestchip, AvanWaves, BCView, Behavioral Compiler, BOA, BRT, Cedar, ChipPlanner, Circuit Analysis, Columbia,
Columbia-CE, Comet 3D, Cosmos, CosmosEnterprise, CosmosLE, CosmosScope, CosmosSE, Cyclelink, Davinci, DC Expert, DC
Expert Plus, DC Professional, DC Ultra, DC Ultra Plus, Design Advisor, Design Analyzer, Design Vision, DesignerHDL,
DesignTime, DFM-Workbench, Direct RTL, Direct Silicon Access, Discovery, DW8051, DWPCI, Dynamic-Macromodeling,
Dynamic Model Switcher, ECL Compiler, ECO Compiler, EDAnavigator, Encore, Encore PQ, Evaccess, ExpressModel, Floorplan
Manager, Formal Model Checker, FoundryModel, FPGA Compiler II, FPGA Express, Frame Compiler, Galaxy, Gatran, HDL
Advisor, HDL Compiler, Hercules, Hercules-Explorer, Hercules-II, Hierarchical Optimization Technology, High Performance Option,
HotPlace, HSPICE-Link, iN-Tandem, Integrator, Interactive Waveform Viewer, i-Virtual Stepper, Jupiter, Jupiter-DP, JupiterXT,
JupiterXT-ASIC, JVXtreme, Liberty, Libra-Passport, Library Compiler, Libra-Visa, Magellan, Mars, Mars-Rail, Mars-Xtalk, Medici,
Metacapture, Metacircuit, Metamanager, Metamixsim, Milkyway, ModelSource, Module Compiler, MS-3200, MS-3400, Nova
Product Family, Nova-ExploreRTL, Nova-Trans, Nova-VeriLint, Nova-VHDLlint, Optimum Silicon, Orion_ec, Parasitic View,
Passport, Planet, Planet-PL, Planet-RTL, Polaris, Polaris-CBS, Polaris-MT, Power Compiler, PowerCODE, PowerGate, ProFPGA,
ProGen, Prospector, Protocol Compiler, PSMGen, Raphael, Raphael-NES, RoadRunner, RTL Analyzer, Saturn, ScanBand,
Schematic Compiler, Scirocco, Scirocco-i, Shadow Debugger, Silicon Blueprint, Silicon Early Access, SinglePass-SoC, Smart
Extraction, SmartLicense, SmartModel Library, Softwire, Source-Level Design, Star, Star-DC, Star-MS, Star-MTB, Star-Power,
Star-Rail, Star-RC, Star-RCXT, Star-Sim, Star-SimXT, Star-Time, Star-XP, SWIFT, Taurus, TimeSlice, TimeTracker, Timing
Annotator, TopoPlace, TopoRoute, Trace-On-Demand, True-Hspice, TSUPREM-4, TymeWare, VCS Express, VCSi, Venus,
Verification Portal, VFormal, VHDL Compiler, VHDL System Simulator, VirSim, and VMC are trademarks of Synopsys, Inc.

Service Marks (SM)


MAP-in, SVP Café, and TAP-in are service marks of Synopsys, Inc.

SystemC is a trademark of the Open SystemC Initiative and is used under license.
ARM and AMBA are registered trademarks of ARM Limited.
All other product or company names may be trademarks of their respective owners.

Document Order Number: 50-I-052-SSG-001


SystemVerilog Testbench Student Guide

Synopsys Customer Education Services


Table of Contents

Day 1

Unit i: Introduction & Overview


Introductions ..................................................................................................................... i-2
Facilities............................................................................................................................ i-3
Workshop Goal ................................................................................................................. i-4
Target Audience................................................................................................................ i-5
Workshop Prerequisites .................................................................................................... i-6
Agenda: Day 1 .................................................................................................................. i-7
Agenda: Day 2 .................................................................................................................. i-8
Agenda: Day 3 .................................................................................................................. i-9
Icons Used in this Workshop .......................................................................................... i-10

Unit 1: The Device Under Test (DUT)


Unit Objectives ................................................................................................................ 1-2
What Is the Device Under Test? ...................................................................................... 1-3
A Functional Perspective ................................................................................................. 1-4
The Router Description.................................................................................................... 1-5
Input Packet Structure...................................................................................................... 1-6
Output Packet Structure ................................................................................................... 1-7
Reset Signal ..................................................................................................................... 1-8
The DUT: router.v ........................................................................................................... 1-9
Unit Objectives Review ................................................................................................. 1-10

Unit 2: SystemVerilog Verification Environment


Unit Objectives ................................................................................................................ 2-2
What is Verification? ....................................................................................................... 2-3
Verification Goal ............................................................................................................. 2-4
Process of Reaching Verification Goal............................................................................ 2-5
The SystemVerilog Test Environment............................................................................. 2-6
SystemVerilog Testbench Building Process.................................................................... 2-7
Create Verilog Test Harness File..................................................................................... 2-8
Creating SystemVerilog Interface File ............................................................................ 2-9
Define Test Program Interface Port ............................................................................... 2-10
Build Testbench ............................................................................................................. 2-11
Sample Testbench .......................................................................................................... 2-12
Driving Synchronous Device Signals ............................................................................ 2-13
Sampling Synchronous Device Signals ......................................................................... 2-14

Synopsys 50-I-052-SSG-001 i SystemVerilog Test Bench Workshop


Table of Contents

Advancing Simulation Time ......................................................................................... 2-15


Create SystemVerilog Harness File ............................................................................... 2-16
Complete Top Level Harness File ................................................................................. 2-17
Compile RTL & Simulate w/ VCS NTB ....................................................................... 2-18
SystemVerilog Run-Time Option .................................................................................. 2-19
Getting Help with VCS.................................................................................................. 2-20
Lab 1 Introduction ......................................................................................................... 2-21
Unit Objectives Review ................................................................................................. 2-22
Appendix........................................................................................................................ 2-23
Compiling and Running with VCS ................................................................................ 2-24
Legacy Code Issues ....................................................................................................... 2-25
Testbench Debug: Getting Started ................................................................................ 2-26

Unit 3: SystemVerilog Language Basics


Unit Objectives ................................................................................................................ 3-2
SystemVerilog Testbench Code Structure ....................................................................... 3-3
SystemVerilog Lexical Convention................................................................................. 3-4
2-State Data Types (1/2) .................................................................................................. 3-5
2-State Data Types (2/2) .................................................................................................. 3-6
4-State Data Types (1/2) .................................................................................................. 3-7
4-State Data Types (2/2) .................................................................................................. 3-8
Floating Point Data Type ................................................................................................. 3-9
String Data Type ............................................................................................................ 3-10
Enumerated Data Types................................................................................................. 3-11
Data Arrays (1/4) ........................................................................................................... 3-12
Data Arrays (2/4) ........................................................................................................... 3-13
Data Arrays (3/4) ........................................................................................................... 3-14
Queue Manipulation Examples...................................................................................... 3-15
Data Arrays (4/4) ........................................................................................................... 3-16
Associate Array Examples............................................................................................. 3-17
Array Loop Support ....................................................................................................... 3-18
Array Locator Methods (1/4)......................................................................................... 3-19
Array Locator Methods (2/4)......................................................................................... 3-20
Array Locator Methods (3/4)......................................................................................... 3-21
Array Locator Methods (4/4)......................................................................................... 3-22
Recommended Usage Model ......................................................................................... 3-23
System Functions: Randomization ................................................................................ 3-24
User Defined Types and Type Cast ............................................................................... 3-25
Operators........................................................................................................................ 3-26
Know Your Operators! .................................................................................................. 3-27
Sequential Flow Control ................................................................................................ 3-28
Subroutines (task and function) ..................................................................................... 3-29
Subroutine Arguments ................................................................................................... 3-30
Test For Understanding ................................................................................................. 3-31

Synopsys 50-I-052-SSG-001 ii SystemVerilog Test Bench Workshop


Table of Contents

Scope and Lifetime Of Variables................................................................................... 3-32


Code Block Lifetime Controls ....................................................................................... 3-33
Unit Objectives Review ................................................................................................. 3-34
Appendix........................................................................................................................ 3-35
Import and Export Subroutines...................................................................................... 3-36
Packed Arrays ................................................................................................................ 3-37
Array Querying System Functions ................................................................................ 3-38
Array Querying System Functions Examples................................................................ 3-39
Data Structure ................................................................................................................ 3-40
Data Union ..................................................................................................................... 3-41
........................................................................................................................................ 3-42

Unit 4: Drive and Sample DUT Signals


Unit Objectives ................................................................................................................ 4-2
Driving & Sampling DUT Signals................................................................................... 4-3
SystemVerilog Testbench Timing ................................................................................... 4-4
SystemVerilog Scheduling .............................................................................................. 4-5
Synchronous Drive Statements ........................................................................................ 4-6
Synchronous Drive Example ........................................................................................... 4-7
Sampling Synchronous Signals ....................................................................................... 4-8
Signal Synchronization .................................................................................................... 4-9
Test For Understanding (1/2)......................................................................................... 4-10
Test For Understanding (2/2)......................................................................................... 4-11
Lab 2 Introduction ......................................................................................................... 4-12
Unit Objectives Review ................................................................................................. 4-13

Day 2

Unit 5: Concurrency
Unit Objectives ................................................................................................................ 5-2
Day 1 Review................................................................................................................... 5-3
Day 1 Review (Building Testbench Files)....................................................................... 5-4
Day 1 Review (Testbench Architecture) ......................................................................... 5-5
Concurrency in Simulators .............................................................................................. 5-6
Creating Concurrent Processes ........................................................................................ 5-7
How Many Child Processes? ........................................................................................... 5-8
Join Options ..................................................................................................................... 5-9
Process Execution .......................................................................................................... 5-10

Synopsys 50-I-052-SSG-001 iii SystemVerilog Test Bench Workshop


Table of Contents

Process Execution Model............................................................................................... 5-11


Subtleties in Concurrency (1/5) ..................................................................................... 5-12
Subtleties in Concurrency (2/5) ..................................................................................... 5-13
Subtleties in Concurrency (3/5) ..................................................................................... 5-14
Subtleties in Concurrency (4/5) ..................................................................................... 5-15
Subtleties in Concurrency (5/5) ..................................................................................... 5-16
Unroll the for-loop ......................................................................................................... 5-17
Solution (1/2): automatic Variable ................................................................................ 5-18
Solution (2/2): Wait Control .......................................................................................... 5-19
Disable Forked Processes .............................................................................................. 5-20
Helpful Debugging Features .......................................................................................... 5-21
Unit Objectives Review ................................................................................................. 5-22

Unit 6: Inter-Process Communications


Unit Objectives ................................................................................................................ 6-2
Inter-Process Communications (IPC) .............................................................................. 6-3
Event Based IPC .............................................................................................................. 6-4
Event Based IPC Example ............................................................................................... 6-5
Event Wait Syntax ........................................................................................................... 6-6
Trigger Syntax ................................................................................................................. 6-7
Controlling Termination of Simulation ........................................................................... 6-8
Resource Sharing IPC ...................................................................................................... 6-9
Semaphores .................................................................................................................... 6-10
Semaphores .................................................................................................................... 6-11
Creating Semaphores ..................................................................................................... 6-12
Acquiring Semaphore Keys ........................................................................................... 6-13
Returning/Creating Semaphore Keys ............................................................................ 6-14
Arbitration Example ...................................................................................................... 6-15
Mailbox .......................................................................................................................... 6-16
Mailboxes....................................................................................................................... 6-17
Creating Mailboxes........................................................................................................ 6-18
Putting Messages into Mailboxes .................................................................................. 6-19
Retrieve Messages from Mailboxes (1/2)...................................................................... 6-20
Retrieve Messages from Mailboxes (2/2)...................................................................... 6-21
Lab 3 Introduction ......................................................................................................... 6-22
Unit Objectives Review ................................................................................................. 6-23

Synopsys 50-I-052-SSG-001 iv SystemVerilog Test Bench Workshop


Table of Contents

Unit 7: OOP Encapsulation


Unit Objectives ................................................................................................................ 7-2
Abstraction Enhances Re-Usability of Code ................................................................... 7-3
OOP Encapsulation (OOP Class) .................................................................................... 7-4
Creating OOP Objects ..................................................................................................... 7-5
Accessing Object Members ............................................................................................. 7-6
Initialization of Object Properties.................................................................................... 7-7
OOP Data Hiding (Integrity of Data) .............................................................................. 7-8
Protect Against Unintentional Corruption ....................................................................... 7-9
Protect Against Data Corruption.................................................................................... 7-10
Working with Objects – Handle Assignment ................................................................ 7-11
Working with Objects – Garbage Collection................................................................. 7-12
Working with Objects – Static Properties...................................................................... 7-13
Best Practices (1/2) ........................................................................................................ 7-14
Best Practices (2/2) ........................................................................................................ 7-15
Unit Objectives Review ................................................................................................. 7-16
Appendix........................................................................................................................ 7-17
Virtual Interfaces .......................................................................................................... 7-18

Unit 8: OOP Randomization


Unit Objectives ................................................................................................................ 8-2
Why Randomization?....................................................................................................... 8-3
Alternatives to Exhaustive Testing? ................................................................................ 8-4
When Do We Apply Randomization? ............................................................................. 8-5
OOP Based Randomization ............................................................................................. 8-6
Randomization Example.................................................................................................. 8-7
Issues with Randomization .............................................................................................. 8-8
Distributed Constraints (1/2) .......................................................................................... 8-9
Distributed Constraints (2/2) ........................................................................................ 8-10
Array Constraint Support............................................................................................... 8-11
Implication and Order Constraints................................................................................. 8-12
Constraint Solver Order ................................................................................................ 8-13
Can randomize() Fail? ................................................................................................... 8-14
VCS Will Find Value if Solution Exist ......................................................................... 8-15
Effects of Calling randomize()....................................................................................... 8-16
Applying pre_randomize()............................................................................................. 8-17
Applying post_randomize() ........................................................................................... 8-18
Inline Constraints........................................................................................................... 8-19
Controlling rand Property Randomization..................................................................... 8-20
Selective Randomization of Properties.......................................................................... 8-21
Controlling Constraint at Runtime................................................................................. 8-22

Synopsys 50-I-052-SSG-001 v SystemVerilog Test Bench Workshop


Table of Contents

Nested Objects with Random Variables ........................................................................ 8-23


Lab 3 Introduction ......................................................................................................... 8-24
Unit Objectives Review ................................................................................................. 8-25

Day 3

Unit 9: OOP Inheritance


Unit Objectives ................................................................................................................ 9-2
Object Oriented Programming: Inheritance..................................................................... 9-3
Object Oriented Programming: Inheritance..................................................................... 9-4
OOP: Polymorphism........................................................................................................ 9-5
OOP: Polymorphism........................................................................................................ 9-6
Data Protection: Local ..................................................................................................... 9-7
Data Protection: Protected ............................................................................................... 9-8
Test For Understanding ................................................................................................... 9-9
Test For Understanding: Answer ................................................................................... 9-10
Test For Understanding: Solution.................................................................................. 9-11
Unit Objectives Review ................................................................................................. 9-12

Unit 10: Functional Coverage


Unit Objectives .............................................................................................................. 10-2
Phases of Verification .................................................................................................... 10-3
The Testbench Environment/Architecture..................................................................... 10-4
Combinational Logic Example ...................................................................................... 10-5
State Transition Example............................................................................................... 10-6
Cross Correlation Example ............................................................................................ 10-7
Functional Coverage in SystemVerilog......................................................................... 10-8
Functional Coverage Example....................................................................................... 10-9
State Bin Creation (Automatic) ................................................................................... 10-10
Measuring Coverage .................................................................................................... 10-11
Automatic State Bin Creation Example....................................................................... 10-12
State and Transition Bin Creation (User) .................................................................... 10-13
Cross Coverage Bin Creation (Automatic) .................................................................. 10-14
Specifying Sample Event Timing ................................................................................ 10-15
Determining Coverage Progress .................................................................................. 10-16
Coverage Measurement Example ................................................................................ 10-17
Coverage Attributes ..................................................................................................... 10-18
Major Coverage Options (1/2)..................................................................................... 10-19

Synopsys 50-I-052-SSG-001 vi SystemVerilog Test Bench Workshop


Table of Contents

Major Coverage Options (2/2)..................................................................................... 10-20


Coverage Result Reporting Utilities ............................................................................ 10-21
Sample HTML Report ................................................................................................. 10-22
Lab 6 Introduction ....................................................................................................... 10-23
Unit Objectives Review ............................................................................................... 10-24

Unit 11: RVM-SV (VMM) Overview


Unit Objectives .............................................................................................................. 11-2
Coverage-Driven Verification ....................................................................................... 11-3
The Testbench Environment/Architecture..................................................................... 11-4
Testbench Considerations: Abstraction ......................................................................... 11-5
Testbench Considerations: Re-Use................................................................................ 11-6
What Does RVM-SV Provide?...................................................................................... 11-7
RVM-SV Base Classes and Macros .............................................................................. 11-8
RVM Guiding Principles ............................................................................................... 11-9
Implementing RVM Testbench.................................................................................... 11-10
Environment Execution Flow ...................................................................................... 11-11
Execution Flow – Under the hood ............................................................................... 11-12
Example: Basic RVM Environment ............................................................................ 11-13
Testing Basic RVM Environment................................................................................ 11-14
Example: RVM Test Configuration............................................................................. 11-15
Testing RVM Configuration ........................................................................................ 11-16
Set Specific RVM Testcase Configuration.................................................................. 11-17
Example: RVM Stimulus Generation .......................................................................... 11-18
Testing RVM Atomic Generator ................................................................................. 11-19
Example: RVM Transactor Class ................................................................................ 11-20
Example: RVM Coverage (Callbacks) ........................................................................ 11-21
RVM Coverage Continued .......................................................................................... 11-22
RVM Coverage Continued .......................................................................................... 11-23
Testing RVM Coverage ............................................................................................... 11-24
Example: Implementing RVM Scoreboard ................................................................. 11-25
Example: RVM Scoreboard Continued ....................................................................... 11-26
RVM Scoreboard Callbacks ........................................................................................ 11-27
RVM Scoreboard Callbacks ........................................................................................ 11-28
Summary: RVM Guiding Principles............................................................................ 11-29
Unit Objectives Review ............................................................................................... 11-30
Appendix...................................................................................................................... 11-31
RVM-OV vs. RVM-SV ............................................................................................... 11-32
Planning for RVM-SV ................................................................................................. 11-41

Synopsys 50-I-052-SSG-001 vii SystemVerilog Test Bench Workshop


Table of Contents

Customer Support
Synopsys Support Resources ........................................................................................ CS-2
SolvNet Online Support Offers: ................................................................................... CS-3
SolvNet Registration is Easy ........................................................................................ CS-4
Support Center: AE-based Support............................................................................... CS-5
Other Technical Sources ............................................................................................... CS-6
Summary: Getting Support ........................................................................................... CS-7

Synopsys 50-I-052-SSG-001 viii SystemVerilog Test Bench Workshop


System Verilog
Testbench
VCS 2005.06-SP1

Synopsys Customer Education Services


© 2006 Synopsys, Inc. All Rights Reserved Synopsys 50-I-052-SSG-001

Introduction & Overview i-1


SVTB © 2006
Introductions

 Name
 Company
 Job Responsibilities
 EDA Experience
 Main Goal(s) and Expectations for this Course

i- 2

EDA = Electronic Design Automation

Introduction & Overview i-2


SVTB © 2006
Facilities

Building Hours Phones

Emergency EXIT Messages

Restrooms Smoking

Meals Recycling

Please turn off cell phones and pagers

i- 3

Introduction & Overview i-3


SVTB © 2006
Workshop Goal

Acquire the skills to write a SystemVerilog


testbench to verify Verilog/SystemVerilog RTL
code with coverage-driven random stimulus.

i- 4

Introduction & Overview i-4


SVTB © 2006
Target Audience

Design or Verification engineers


writing SystemVerilog testbenches
to verify Verilog or SystemVerilog code.

i- 5

Introduction & Overview i-5


SVTB © 2006
Workshop Prerequisites

 You must have experience in the following areas:


 Familiarity with a UNIX text editor
 Basic programming skills in Verilog, VHDL or C
 Debugging experience with Verilog, VHDL or C

i- 6

Introduction & Overview i-6


SVTB © 2006
Agenda: Day 1

DAY
1
1 The Device Under Test (DUT)

2 SystemVerilog Verification Environment

3 SystemVerilog Language Basics

4 Drive and Sample DUT Signals

i- 7

Introduction & Overview i-7


SVTB © 2006
Agenda: Day 2

DAY
2
5 Concurrency

6 Inter-Process Communications

Object Oriented Programming (OOP)


7 – Encapsulation

Object Oriented Programming (OOP)


8 – Randomization

i- 8

Introduction & Overview i-8


SVTB © 2006
Agenda: Day 3

DAY
3 Object Oriented Programming (OOP)
9 – Inheritance

10 Functional Coverage

11 SystemVerilog RVM (VMM) Overview

CS Customer Support

i- 9

Introduction & Overview i-9


SVTB © 2006
Icons Used in this Workshop

Lab Exercise ! Caution

Definition of
Recommendation
Acronyms

For Further Reference Question

“Under the Hood”


Group Exercise
Information

i- 10
Lab Exercise: A lab is associated with this unit, module, or concept.
Recommendation: Recommendations to the students, tips, performance boost, etc.
For Further Reference: Identifies pointer or URL to other references or resources.
Under the Hood Information: Information about the internal behavior of the tool.
Caution: Warnings of common mistakes, unexpected behavior, etc.
Definition of Acronyms: Defines the acronym used in the slides.
Question: Marks questions asked on the slide.
Group Exercise: Test for Understanding (TFU), which requires the students to work in groups.

Introduction & Overview i-10


SVTB © 2006
Agenda

DAY
1
1 The Device Under Test (DUT)

2 SystemVerilog Verification Environment

3 SystemVerilog Language Basics

4 Drive and Sample DUT Signals

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 1- 1

The Device Under Test (DUT) 1-1


SVTB © 2006
Unit Objectives

After completing this unit, you should be able to:


 Describe the function of the Device Under Test
(DUT)
 Identify the control and data signals of the DUT
 Draw timing diagram for sending and receiving
a packet of data through the DUT

1- 2

The Device Under Test (DUT) 1-2


SVTB © 2006
What Is the Device Under Test?

A router:
16 x 16 crosspoint switch

din [15:0] dout [15:0]

frame_n[15:0] frameo_n [15:0]

valid_n [15:0]
router valido_n [15:0]

reset_n

clock

1- 3
The router has 16 input and 16 output ports. Each input and output port consists of 3 signals, serial
data, frame and valid. These signals are represented in a bit-vector format, din[15:0], frame_n[15:0],
valid_n[15:0], dout[15:0], frameo_n[15:0] and valido_n[15:0].

To drive an individual port, the specific bit position corresponding to the port number must be
specified. For example, if input port 3 is to be driven, then the corresponding signals shall be din[3],
frame_n[3] and valid_n[3].

To sample an individual port, the specific bit position corresponding to the port number must be
specified. For example, if output port 7 is to be sampled, then the corresponding signals shall be
dout[7], frameo_n[7] and valido_n[7].

The Device Under Test (DUT) 1-3


SVTB © 2006
A Functional Perspective

inputs outputs
frame_n[0] port port
frameo_n[0]
valid_n[0] 0 0 valido_n[0]
din[0] dout[0]
1 1

2 2

3 3

4 4
partial view

1- 4

The Device Under Test (DUT) 1-4


SVTB © 2006
The Router Description

 Single positive-edge clock


 Input and output data are serial (1 bit / clock)
 Packets are sent through in variable length:
 Each packet is composed of two parts
 Header
 Payload

 Packets can be routed from any input port to any


output port on a packet-by-packet basis
 No internal buffering or broadcasting (1-to-N)

1- 5

The Device Under Test (DUT) 1-5


SVTB © 2006
Input Packet Structure
 frame_n:
 Falling edge indicates first bit of packet
 Rising edge indicates last bit of packet
 din:
 Header (destination address & padding bits) and payload
 valid_n:
 valid_n is low if payload bit is valid, high otherwise

clock
din[i] x A0 A1 A2 A3 d0 .... x dn-1 dn x

valid_n[i] x x x x x

frame_n[i]

dest. address pad payload


1- 6

The Device Under Test (DUT) 1-6


SVTB © 2006
Output Packet Structure

 Output activity is indicated by:


frameo_n, valido_n, and dout
 Data is valid only when:
 frameo_n output is low (except for last bit)
 valido_n output is low
 Header field is stripped

clock
dout[i] x x d0 d1 x x d2 d3 dn-3 x dn-2 dn-1 x

valido_n[i] x x

frameo_n[i]

1- 7

The Device Under Test (DUT) 1-7


SVTB © 2006
Reset Signal

 While asserting reset_n, frame_n and valid_n


must be de-asserted
 reset_n is asserted for at least one clock cycle
 After de-asserting reset_n, wait for 15 clocks
before sending a packet through the router

clock

reset_n

frame_n[i]

15 clock cycles

1- 8
During these 15 clock cycles, the router is performing self-initialization. If you attempt to drive a
packet through the router during this time, the self-initialization will fail and the router will not work
correctly afterwards.

The Device Under Test (DUT) 1-8


SVTB © 2006
The DUT: router.v

 The Design Under Test, router.v, is a Verilog file:


 Located under the rtl directory
 From the lab workspace: ../../rtl/router.v

labs/ solutions/ rtl/

lab1/ lab2/ lab6/ lab1/ lab6/ router.v

lab work files

1- 9

The Device Under Test (DUT) 1-9


SVTB © 2006
Unit Objectives Review

Having completed this unit, you should be able to:


 Describe the function of the Device Under Test (DUT)
 Identify the control and data signals of the DUT
 Draw timing diagram for sending and receiving
a packet of data through the DUT

1- 10

The Device Under Test (DUT) 1-10


SVTB © 2006
Agenda

DAY
1
1 The Device Under Test (DUT)

2 SystemVerilog Verification Environment

3 SystemVerilog Language Basics

4 Drive and Sample DUT Signals

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 2- 1

SystemVerilog Verification Environment 2-1


SVTB © 2006
Unit Objectives

After completing this unit, you should be able to:


 Describe the process of reaching verification
goals
 Create templates for a SystemVerilog testbench
 Use these templates as a starting point for
writing SystemVerilog testbench code
 Compile and simulate SystemVerilog testbench

2- 2

SystemVerilog Verification Environment 2-2


SVTB © 2006
What is Verification?

Verification is the process of verifying the transformation


steps in the design flow are executed correctly.

Architecture/ End
Idea Algorithm Spec RTL Gate GDSII ASIC product

Transformations

Spec Formal Functional/ Product


Acceptance Simulation/ Timing Sign-Off Acceptance
C-Model Review Code Review Verification Review ATE Test

2- 3

SystemVerilog Verification Environment 2-3


SVTB © 2006
Verification Goal

 Ensure full conformance with specification:


 Must avoid false positives (untested functionalities)

Testbench RTL code


False positive
Simulation results in shipping
Good Bad(bug) a bad design
result

Pass

Tape out!
???

Debug Debug
Fail testbench RTL code

How do we achieve this goal?

2- 4

SystemVerilog Verification Environment 2-4


SVTB © 2006
Process of Reaching Verification Goal

Phases of verification
Preliminary Broad-Spectrum Corner-case
Verification Verification Verification

Goal
% Coverage

Difficult to reach
Corner-case
Verification

Time

Build verification
environment

2- 5
The process of reaching the verification goal starts with the definition of the verification goal.
What does it mean to be done with testing? Typically, the answer lie in the functional coverage spec
within a verification plan. The goal is then to reach 100% coverage of the defined functional
coverage spec in the verification plan.
Once the goal has been defined, the first step in constructing the testbench is to build the verification
environment.
To verify the the environment is set up correctly, preliminary verification tests are usually executed
to wring out the rudimentary RTL and testbench errors.
When the testbench environment is deemed to be stable, broad-spectrum verification based on
random stimulus generation is utilized to quickly detect and correct the majority of the bugs in both
RTL code and testbench code.
Based on functional coverage analysis, the random-based tests are then constrained to focus on
corner-cases not yet reached via broad-spectrum testing.
Finally, for the very difficult to reach corner cases, customized directed tests are used to bring the
coverage up to 100%.
Verification is complete when you reach 100% coverage as defined in the verification plan.

SystemVerilog Verification Environment 2-5


SVTB © 2006
The SystemVerilog Test Environment

Checks Checks
Configure
completeness correctness

Generator Coverage Identifies


transactions
Test
Transactor Self Check Transactor program
Top level
harness file
Driver Observes data Monitor
from DUT

DUT interface

2- 6

SystemVerilog Verification Environment 2-6


SVTB © 2006
SystemVerilog Testbench Building Process

router.v

ntb_template -t router router.v

Discard
router.test_top.v router.vr.tmp router.if.vrh

router.test_top.sv router.if.sv router.tb.sv


Top level harness Interface Test program

vcs –sverilog router.test_top.sv router.tb.sv router.if.sv router.v

simv

2- 7

SystemVerilog Verification Environment 2-7


SVTB © 2006
Create Verilog Test Harness File

 Use VCS template generator

ntb_template -t router router.v

 Generates three files:


 router.test_top.v Verilog test harness file
 router.if.vrh Discard (for OpenVera only)
 router.vr.tmp Discard (for OpenVera only)
 -t router Specifies DUT module name
 router.v DUT source code file
 router.test_top.v will be used to help build
SystemVerilog testbench files

2- 8
router.v must be the last entry in the ntb_template command.

SystemVerilog Verification Environment 2-8


SVTB © 2006
Creating SystemVerilog Interface File
 Create interface file from router.test_top.v
cp router.test_top.v router.if.sv

 Encapsulate signals in interface block


module router_test_top;
parameter simulation_cycle = 100;
reg SystemClock ;
wire reset_n ;
wire [15:0] din ; Create from default harness file
wire clock ; Change module to interface
wire [15:0] frame_n ;
wire [15:0] valid_n ; Delete all except wires
wire [15:0] dout ;
wire [15:0] busy_n ;
wire [15:0] valido_n ;
interface router_io(input logic clock);
wire [15:0] frameo_n ;
logic reset_n ;
`ifdef SYNOPSYS_NTB
logic [15:0] din ; Move clock to
...
`endif //wire clock; input argument
router dut( … ); logic [15:0] frame_n ;
initial begin logic [15:0] valid_n ;
SystemClock = 0 ; logic [15:0] dout ; router.if.sv
forever begin logic [15:0] busy_n ;
#(simulation_cycle/2) logic [15:0] valido_n ;
SystemClock = ~SystemClock ;
logic [15:0] frameo_n ;
end
endinterface
end router.test_top.v Change wire to logic
endmodule
2- 9

SystemVerilog Verification Environment 2-9


SVTB © 2006
Define Test Program Interface Port
 By default all interface signals are asynchronous
 Synchronous signals can be created via clocking
block and connected to test program via modport
interface router_io(input logic clock); router.if.sv
logic reset_n ;
logic [15:0] din ; Configure
logic [15:0] frame_n ;
logic [15:0] valid_n ;
Generator Coverage
logic [15:0] dout ;
logic [15:0] busy_n ;
logic [15:0] valido_n ; Transactor Self Check Transactor
Create synchronous logic [15:0] frameo_n ;
clocking cb @(posedge clock); Driver Monitor
by placing signals default input #1 output #1;
into clocking block output reset_n;
output din; DUT
output frame_n;
output valid_n;
input dout;
input busy_n; Sample/drive skew
input valido_n;
Define connection input frameo_n; Direction w/respect to test
for test program endclocking
modport TB(clocking cb, output reset_n);
with modport endinterface
Synchronous Asynchronous
2- 10
If unspecified, the sample and drive skew defaults to:

default input #1 output #0;

SystemVerilog Verification Environment 2-10


SVTB © 2006
Build Testbench

 Testbench is encapsulated in program block


 List interface signals in argument

Both synchronous and


asynchronous signals are
encapsulated in modport
router.tb.sv
program automatic router_test(router_io.TB router);
// develop test code in initial block:
initial begin
Configure
$vcdpluson; // Dumping file control
Generator Coverage
$display(“Hello World”);
Transactor Self Check Transactor
end
Driver Monitor
endprogram
DUT

2- 11

SystemVerilog Verification Environment 2-11


SVTB © 2006
Sample Testbench
 Develop test program code in initial block
program automatic router_test(router_io.TB router);
//testbench code in initial block: interface router_io(input logic clock);
initial begin logic reset_n ;
logic [15:0] din ;
$vcdpluson; // Dumping file control logic [15:0] frame_n ;
// $display(“Hello World”); logic [15:0] valid_n ;
...
end clocking cb @(posedge clock);
initial begin Asynchronous signals are default input #1 output #1;
reset(); driven without reference to output reset_n;
output din;
end clocking block output frame_n;
task reset(); output valid_n;
...
router.reset_n <= 1’b0; endclocking
router.cb.frame_n <= 16’hffff; modport TB(clocking cb, output reset_n);
endinterface
router.cb.valid_n <= ~(’b0);
##2 router.cb.reset_n <= 1’b1; // reset_n can be both synchronous and asynchronous
repeat(15) @(router.cb);
Synchronous signals are
endtask
driven via clocking block
endprogram
Advance clock cycles
via clocking block
2- 12

SystemVerilog Verification Environment 2-12


SVTB © 2006
Driving Synchronous Device Signals
[##num] interface.cb.signal <= <value> or <variable expression>;
 Must be driven with <= (non-blocking assignment)
 Can be specified with ##num of clocks delay
##1 router.cb.din[3] <= var_a;
Equivalent to:
repeat(num) @(router.cb);
router.din[3] <= #input_skew_value var_a;

clock

var_a
din[3]

Statement executes here Apply drive here


Variable expression evaluates Next statement executes
router.cb.din[3] = 1’b1; // error (must be non-blocking)
2- 13

SystemVerilog Verification Environment 2-13


SVTB © 2006
Sampling Synchronous Device Signals

variable = interface.cb.signal;
 No delay attribute (## num)
 Variable is assigned the sampled value
 Sampling of output signal is not allowed
Examples:
data[i] = router.cb.dout[7];
all_data = router.cb.dout;
@(posedge router.cb.frameo_n[7]);
$display(“router.cb.din = %b\n”, router.din); //error
if(router.cb.din[3] == 1’b0) //error

2- 14

SystemVerilog Verification Environment 2-14


SVTB © 2006
Advancing Simulation Time
 Asynchronous (Verilog coding style):
#delay;
@(negedge interface.signal);
 Synchronous (advancing clock cycles):
 Verilog coding style:
@(posedge interface.clock_signal);
repeat (10) @(posedge interface.clock_signal);
 SystemVerilog coding style (clocking block):
@(interface.clocking_block);
repeat (10) @(interface.clocking_block);
 Each clocking block specifies a clock signal and edge:
interface router_io(input logic clock);
clocking cb @(posedge clock);
...
endclocking
endinterface
2- 15
In order for the syntax @(posedge interface.clock_signal); to work. The clock_signal must be passed in as an additional
asynchronous signal argument to the modport for the test program connection:

interface router_io(input logic clock);


logic reset_n ;
logic [15:0] din ;
logic [15:0] frame_n ;
logic [15:0] valid_n ;
logic [15:0] dout ;
logic [15:0] busy_n ;
logic [15:0] valido_n ;
logic [15:0] frameo_n ;
clocking cb @(posedge clock);
default input #1 output #1;
output reset_n;
output din;
output frame_n;
output valid_n;
input dout;
input busy_n;
input valido_n;
input frameo_n;
endclocking
modport TB(clocking cb, output reset_n, input clock);
endinterface

SystemVerilog Verification Environment 2-15


SVTB © 2006
Create SystemVerilog Harness File

 Create harness file from router.test_top.v


mv router.test_top.v router.test_top.sv
Configure

module router_test_top; Generator Coverage


parameter simulation_cycle = 100;
reg SystemClock ; Transactor Self Check Transactor
wire reset_n ;
wire clock ; Driver Monitor
wire [15:0] frame_n ;
wire [15:0] valid_n ; DUT
Delete
wire [15:0] dinall; wire declarations
wire [15:0] dout ;
wire [15:0] andbusy_n
all OpenVera
; stuff
wire [15:0] valido_n ;
wire [15:0] frameo_n ; module router_test_top;
`ifdef SYNOPSYS_NTB parameter simulation_cycle = 100;
... reg SystemClock ;
`endif router dut( … );
router dut( … ); initial begin
initial begin SystemClock = 0 ;
SystemClock = 0 ; forever begin
forever begin #(simulation_cycle/2)
#(simulation_cycle/2) SystemClock = ~SystemClock ;
SystemClock = ~SystemClock ; end
end end router.test_top.sv
end router.test_top.sv endmodule
endmodule
2- 16

SystemVerilog Verification Environment 2-16


SVTB © 2006
Complete Top Level Harness File
 Instantiate test program and interface in harness file
Instantiate Connect SystemClock
router.test_top.sv interface to interface block
module router_test_top; module router_test_top;
parameter simulation_cycle = 100; parameter simulation_cycle = 100;
reg SystemClock ; reg SystemClock;
router dut( router_io top_io(SystemClock);
.reset_n(reset_n), router_test test(top_io);
.clock(clock), router dut(.reset_n(top_io.reset_n),
.frame_n(frame_n), Instantiate .clock(top_io.clock),
.valid_n(valid_n), test program .frame_n(top_io.frame_n),
.din(din), .valid_n(top_io.valid_n),
.dout(dout), Update DUT .din(top_io.din),
.busy_n(busy_n), .dout(top_io.dout),
.valido_n(valido_n), instantiation using .busy_n(top_io.busy_n),
.frameo_n(frameo_n)); interface connection .valido_n(top_io.valido_n),
initial begin .frameo_n(top_io.frameo_n));
SystemClock = 0 ; initial begin
forever begin SystemClock = 0 ;
#(simulation_cycle/2) forever begin
SystemClock = ~SystemClock ; #(simulation_cycle/2)
end SystemClock = ~SystemClock ;
end end
endmodule end
endmodule

2- 17
If the DUT module was already constructed with SystemVerilog interface, the connection would
simplify to:

router dut(top_io);

SystemVerilog Verification Environment 2-17


SVTB © 2006
Compile RTL & Simulate w/ VCS NTB

Configure

Generator Coverage
router.tb.sv
Transactor Self Check Transactor
router.test_top.sv
Driver Monitor
router.if.sv
DUT
router.v

 Compile HDL code: (generate simv simulation binary)


> vcs –sverilog [-debug] router.test_top.sv \
router.tb.sv router.if.sv router.v
 Get vcs compiler switch summary:
> vcs -help
 Simulate DUT with SystemVerilog testbench: (running simv)
> ./simv

2- 18

SystemVerilog Verification Environment 2-18


SVTB © 2006
SystemVerilog Run-Time Option

 Set SystemVerilog run-time option with +argument


 Retrieve +argument value with $value$plusargs()
initial begin
int user_seed;
if ($value$plusargs("ntb_random_seed=%d", user_seed))
$display(“User seed is %d", user_seed);
else
$display(“Using default seed");
end

> ./simv +ntb_random_seed=100


User seed is 100

2- 19

SystemVerilog Verification Environment 2-19


SVTB © 2006
Getting Help with VCS
 Get vcs compiler switch summary:
shell> vcs -help
 Read vcs manuals:
shell> vcs –doc
 Examples
 $VCS_HOME/doc/examples
 Email Support:
 vcs-support@synopsys.com
 On-line knowledge database
 http://solvnet.synopsys.com
 SystemVerilog LRM
 www.Accellera.org or
 www.eda.org/sv
2- 20

SystemVerilog Verification Environment 2-20


SVTB © 2006
Lab 1 Introduction

Build Simulation
Environment
Generate Template Files
30 min
program automatic router_test;
initial begin
$vcdpluson; Write Test Code
$display(“Hello”);
end
initial begin
reset();
end Compile & Simulate
task reset(); ...
endprogram

DUT

2- 21

SystemVerilog Verification Environment 2-21


SVTB © 2006
Unit Objectives Review

Having completed this unit, you should be able to:


 Describe the process of reaching verification goals
 Create templates for a SystemVerilog testbench
 Use these templates as a starting point for writing
SystemVerilog testbench code
 Compile and simulate SystemVerilog testbench

2- 22

SystemVerilog Verification Environment 2-22


SVTB © 2006
Appendix

Useful VCS compile and run time switches


Debugging with DVE & Testbench Debugger

SystemVerilog Verification Environment 2-23


SVTB © 2006
Compiling and Running with VCS

 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

See the VCS User Guide for all options


2- 24

SystemVerilog Verification Environment 2-24


SVTB © 2006
Legacy Code Issues

 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
 or
vcs +systemverilogext+.sv old.v new.sv

// Old Verilog-1995/2001 legacy code


integer bit, count;
initial begin
count = 0;
for (bit = 0; bit < 8; bit = bit + 1)
if (adrs[bit] === 1'bx)
count = count + 1;
end
2- 25

SystemVerilog Verification Environment 2-25


SVTB © 2006
Testbench Debug: Getting Started

 Invoke DVE > simv -gui


Need VCS
 Start separate testbench debugger 2005.06-6

 Simulator -> TB-Debugger

2- 26

SystemVerilog Verification Environment 2-26


SVTB © 2006
Testbench Debug: Getting Started
 The testbench debugger is separate from DVE
 TB_Debugger > Enable
 Testbench window will open when simulator starts
 Default = off
 Option is saved from one session to the next
 TB_Debugger > Debug on Error
 Testbench window will open upon error
 Default = off
 TB_Debugger > Start
 Testbench window will open at start of Simulator
 Default = off
 Simulator > Start
 Starts simulator
 Testbench debugger window will open depending whether or not
TB_Debugger.Debug_on_start or TB_Debugger.Start is set
2- 27

SystemVerilog Verification Environment 2-27


SVTB © 2006
Testbench Debug: Getting Started

 Testbench Debugger window

Active
threads
Source
code
tracing

Watch
variables

Local
variables

2- 28

SystemVerilog Verification Environment 2-28


SVTB © 2006
Agenda

DAY
1
1 The Device Under Test (DUT)

2 SystemVerilog Verification Environment

3 SystemVerilog Language Basics

4 Drive and Sample Signals

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 3- 1

SystemVerilog Language Basics 3-1


SVTB © 2006
Unit Objectives

After completing this unit, you should be able to:


 Define the structure of a SystemVerilog
program
 Declare variables in a SystemVerilog program
 Describe variable visibility in program,
local blocks and sub-routines
 Use flow control constructs to implement
SystemVerilog verification testbench

3- 2

SystemVerilog Language Basics 3-2


SVTB © 2006
SystemVerilog Testbench Code Structure
 Test code is embedded inside program block
 program code is instantiated in the top-level harness file
program automatic router_test ( … );
// root global variables initial begin
program [automatic] name(interface); $vcdpluson;
// `include files reset();
// program global variables end From Lab 1:
initial begin task reset();
// local variables router.reset_n <= 1'b0;
// top-level test code router.cb.frame_n <= ~('b0);
end ...
task task_name(…); endtask
// local variables endprogram
// code
endtask module router_test_top;
endprogram router_io top_io(SystemClock);
router_test test(top_io);
router dut(.reset_n (top_io.reset_n),
.clock (top_io.clock),
.… (top_io.…));
…;
endmodule
3- 3

SystemVerilog Language Basics 3-3


SVTB © 2006
SystemVerilog Lexical Convention
 Same as Verilog
 Case sensitive
 White Spaces are ignored except within strings

 Comments:
 // …
 /* … */ (Do not nest!) /* /* */ */
 Number Format:
<size>’<base><number>
’b (binary) :[01xXzZ]
’d (decimal) :[0123456789]
’o (octal) :[01234567xXzZ]
’h (hexadecimal) :[0123456789abcdefABCDEFxXzZ]
 Can be padded with ‘_’ for readability:
16’b_1100_1011_1010_0010
32’h_beef_cafe
3- 4

SystemVerilog Language Basics 3-4


SVTB © 2006
2-State Data Types (1/2)
 2 state logic (0, 1)
 Variable initialized to ’0 if initial_value is not specified
 Defaults to 0 for x or z values

bit [msb:lsb] variable_name [=initial_value];


 Sized as specified
 Defaults to unsigned

byte variable_name [=initial_value];


 8-bit data type
 Defaults to signed

Examples:
bit flag; bit[15:0] sample, temp = 16’hdeed;
byte a = -55, b;
byte unsigned ref_data = ’hff;
3- 5
Explicit 2-state variables allow more compiler optimizations, giving better performance.
BUT – they will not propagate X or Z, so keep away from DUT

SystemVerilog Language Basics 3-5


SVTB © 2006
2-State Data Types (2/2)

shortint variable_name [=initial_value];


 16-bit data type
 Defaults to signed

int variable_name [=initial_value];


 32-bit data type
 Defaults to signed

longint variable_name [=initial_value];


 64-bit data type
 Defaults to signed

Examples:
shortint temp = 256;
int sample, ref_data = -9876;
longint a, b; longint unsigned testdata;
3- 6

SystemVerilog Language Basics 3-6


SVTB © 2006
4-State Data Types (1/2)

 4 state logic (0, 1, x or z)


 Variable initialized to ’x if initial_value is not specified
reg [msb:lsb] variable_name [=initial_value];
 Sized as specified
 Defaults to unsigned

 Used when 4-state retention for sampled signal is required

integer variable_name [=initial_value];


 32-bit data type
 Defaults to signed

Examples:
integer temp = ’1, ref_data = ’x;
reg[15:0] sample;
sample = router.cb.dout[da];
3- 7

SystemVerilog Language Basics 3-7


SVTB © 2006
4-State Data Types (2/2)
logic [msb:lsb] variable_name [=initial_value];
 Sized as specified
 Defaults to unsigned

 Used for general I/O connections

time variable_name [=initial_value];


 64-bit unsigned integer
Examples:
interface router_io(input logic clock);
logic reset_n;
logic [15:0] din; ...;
endinterface
time start_time = $time;

3- 8
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 a new name logic. It can not have multiple
drivers – use a wire.

SystemVerilog Language Basics 3-8


SVTB © 2006
Floating Point Data Type

 Real number variables:


 Variable initialized to 0.0 if initial_value is not specified
real variable_name [=initial_value];
(Equivalent to double in C)
 Used as functional coverage return value

Example:
real alpha, beta, coverage_result;
alpha = 100.3;
beta = alpha;
coverage_result = $get_coverage();
if (coverage_result == 100) ...;

3- 9

SystemVerilog Language Basics 3-9


SVTB © 2006
String Data Type
 Strings:
 Variable initialized to “” if initial_value is not specified
string variable_name [=initial_value];
 Can be created with $psprintf() VCS system function
 Built-in operators and methods:
 ==, !=, compare() and icompare()
 itoa(), atoi(), atohex(), toupper(), tolower(), etc.

 len(), getc(), putc(), substr() (See manual for more)

Example:
string name, s = “Now is the time”;
for (int i=0; i<4; i++) begin
name = $psprintf(“string%0d”, i);
$display(“%s, upper: %s”, name, name.toupper());
end
s.putc(s.len()-1, s.getc(0)); // change e->s
$display(s.substr(s.len()-4, s.len()-1)); 3- 10
The resulting print out on terminal is:

string0, upper: STRING0


string1, upper: STRING1
string2, upper: STRING2
string3, upper: STRING3
tims

SystemVerilog Language Basics 3-10


SVTB © 2006
Enumerated Data Types
 Create enumerated data types:
 Data type defaults to int
 Variable initialized to ’0 if initial_value is not specified
 enum variables can be displayed as ascii with .name property
typedef enum [data_type] {named constants} enumtype;
 Create enum variables: Variable creation Type creation
enum [data_type] {named constants} enumvar, …;
enumtype variable_name [=initial_value];
Example:
typedef enum {IDLE, TEST, START} state;
enum bit[2:0] {S0=’b001, S1=’b010, S2=’b100} st;
state c_st, n_st = IDLE;
$display(“st = %3b, n_st = %s”, st, n_st.name);
What will be displayed on screen?
3- 11
What’s printed to screen:

st = 0, n_st = IDLE

The reason st is printed as 0 is because enum variables default to 0 if not initialized or assigned an
enum value.

SystemVerilog Language Basics 3-11


SVTB © 2006
Data Arrays (1/4)
 Fixed-size Arrays:
type array_name[size] [=initial_value];
 Out-of-bounds write ignored
 Out-of-bounds read returns ’0 for 2state, ’x for 4state arrays
 Multiple dimensions are supported
Examples:
integer numbers[5]; // array of 5 integers, indexed 0 – 4
int b[2] = {3,7}; // ( b[0] = 3, b[1] = 7)
int c[2][3] = {{3,7,1},{5,1,9}};
bit[31:0] a[2][3] = c; // array copy
for(int i=0; i<$dimensions(a)) Returns dimension
$display($size(a, i+1)); // 2 3 32
Returns size of particular dimension
3- 12
$dimensions (array_name)
Returns the # of dimensions in the array
$size (array_name, dimension)
Returns the total # of elements in the specified dimension ($high - $low +1)

dimension numbers

3 1 2

bit [3:0] Bytes [0:2][0:5];

same as:

bit [3:0] Bytes [3][6];

SystemVerilog Language Basics 3-12


SVTB © 2006
Data Arrays (2/4)

 Dynamic Arrays:
type array_name[] [=initial_value];
 Array size allocated at runtime with constructor
 Out-of-bounds read/write results in simulation error
 Single dimension only
Examples:
reg[7:0] ID[], array1[] = new[16];
reg[7:0] data_array[]; Returns size of array
ID = new[100]; // allocate memory
data_array = new[ID.size()] (ID); // copy
data_array = new[$size(ID)] (ID); // copy
data_array = ID; // copy
ID = new[ID.size() * 2] (ID); // double the size
data_array.delete(); // de-allocate memory
3- 13

SystemVerilog Language Basics 3-13


SVTB © 2006
Data Arrays (3/4)

 Queues:
type array_name[$] [=initial_value];
 Array memory allocated and de-allocated at runtime with:
 push_back(), push_front(), insert()
 pop_back(), pop_front(), or delete()

 Array memory can not be allocated with new[]


 bit[7:0] ID[$] = new[16]; // Compilatin error!
 Index 0 refers to lower (first) index in queue
 Index $ refers to upper (last) index in queue
 Out-of-bounds read/write results in simulation error
 Can be operated on as an array, FIFO or stack
 Single dimension only

3- 14

SystemVerilog Language Basics 3-14


SVTB © 2006
Queue Manipulation Examples
int j = 2, q[$] = {0,1,3,6}, b[$] = {4,5};
q.insert(2, j); // {0,1,2,3,6}
// same as q = { q[0:1], 2, q[2:$] };
q.insert(4, b); // {0,1,2,3,4,5,6}
// same as q = { q[0:3], b, q[4:$] };
q.delete(1); // {0,2,3,4,5,6}
// same as q = { q[0], q[2:$] };
q.push_front(7); // {7,0,2,3,4,5,6}
// same as q = { 7, q };
j = q.pop_back(); // {7,0,2,3,4,5} j = 6
// same as j = q[$]; q = q[0:$-1];
q.push_back(8); // {7,0,2,3,4,5,8}
// same as q = { q, 8 };
$display($size(q)); // 7
q.delete(); // delete all elements
// same as q = { };
$display(q.size()); // 0 3- 15

SystemVerilog Language Basics 3-15


SVTB © 2006
Data Arrays (4/4)
 Associative Arrays:
type array_name[index_type]; // indexed by specified type
type array_name[*]; // indexed by any type
 Index type can be any numerical, string or class type
 Dynamically allocated and de-allocated
integer ID_array[*];
ID_array[71] = 99; // allocate memory
ID_array.delete(71); // de-allocate one element
ID_array.delete(); // de-allocate all elements
 Array can be traverse with:
 first(), next(), prev(), last()
 Number of allocated elements can be determined with num()
 Existence of a valid index can be determined with exists()
 Out-of-bounds read returns ’0 for 2state, ’x for 4state arrays
 Single dimension only
3- 16
function int num();
Returns the number of entries in the array. If the array is empty, it returns 0:
function void delete( [input index] );
Deletes a specified element or the entire array.
function int exists( input index );
Returns 1 if element exists, otherwise returns 0:
function int first( ref index );
Returns the index of the first valid index of an array via a pass by reference int variable. If the
array contains at least one element, the function return value will be 1 and the argument variable
will be modified to reference the first valid index. If the array is empty, the function return value
will be 0 and the argument variable is left unmodified:
function int last( ref index );
Similar to first except the last valid index is returned instead of first:
function int next( ref index );
Returns the index of the next valid element. If there is a next valid element after the index
argument, the argument variable will be modified to contain the index of the next valid element
and the return value of the function will be 1. Otherwise, the argument variable is left alone and
the return value of the function will be 0:
function int prev( ref index );
Similar to next except the prev valid index is returned:

SystemVerilog Language Basics 3-16


SVTB © 2006
Associate Array Examples

byte b_array[string], t[*], a[*]; int index;


b_array[“byte0”] = -8; // create index “byte0” memory
for (int i=0; i<10; i++)
t[i<<i] = i; // create 10 array elements
a = t; // array copy
$display("size of t array is: %0d", t.num()); // array size
if (t.first(index)) begin // locate first valid index
$display("t[%0d] = %0d", index, t[index]);
while(t.next(index)) // locate next valid index
$display("t[%0d] = %0d", index, t[index]);
end

3- 17

SystemVerilog Language Basics 3-17


SVTB © 2006
Array Loop Support

 Loop support for all array types: foreach


program test;
int unsigned array_size, data[];
array_size = $random;
array_size = (array_size % 3) + 2;
data = new[array_size];
foreach(data[i]) begin
data[i] = $random % 256;
$display(“data[%0d] = %0d”, i, data[i]);
end
endprogram

3- 18
Compile and simulate the above code, you will see something like the following result:

data[0] = 172
data[1] = 29
data[2] = 191
data[3] = 201

SystemVerilog Language Basics 3-18


SVTB © 2006
Array Locator Methods (1/4)

function array_type[$] array.find()


with (expression)
 Finds all the elements satisfying the with expression
 Matching elements are returned as a queue
function int_or_index_type[$] array.find_index()
with (expression)
 Finds all the indices satisfying the with expression
 Matching indices are returned as a queue
 item references the array elements during search
 Empty queue is returned when match fails

3- 19

SystemVerilog Language Basics 3-19


SVTB © 2006
Array Locator Methods (2/4)

Example:
program test_program;
bit[7:0] SQ_array[$] = {2, 1, 8, 3, 5};
bit[7:0] SQ[$];
int idx[$];
SQ = SQ_array.find() with ( item > 3 );
// SQ[$] contains 8, 5
idx = SQ_array.find_index() with ( item > 3 );
// idx[$] contains 2, 4
endprogram

3- 20

SystemVerilog Language Basics 3-20


SVTB © 2006
Array Locator Methods (3/4)

function array_type[$] array.find_first()


[with (expression)]
 First element satisfying the with expression is returned
 If with expression is omitted, first element is returned
 First matching element is returned in array_type[0]
function int_or_index_type[$]
array.find_first_index() [with (expression)]
 First index satisfying the with expression is returned
 If with expression is omitted, first index is returned
 First matching index is returned in int_or_index_type[0]
 item references the array elements during search
 Empty queue is returned when match fails
3- 21

SystemVerilog Language Basics 3-21


SVTB © 2006
Array Locator Methods (4/4)

Example:
program test_program;
int array[] = new[5];
int idx[$], Value[$];
foreach(array[i])
array[i] = 4 – i;
Value = array.find_first() with ( item > 3 );
// Value[0] = 4
idx = array.find_first_index() with ( item < 0 );
// idx.size() = 0;
endprogram

More array methods are available See LRM

3- 22
Examples of other array methods are: (please check release note and LRM for support)
.find_last()
.find_last_index()
.unique()
.unique_index()
.sum()
.product()
.and()
.or()
.xor()
.min()
.max()
.reverse()
.sort()
.rsort()
.shuffle()

SystemVerilog Language Basics 3-22


SVTB © 2006
Recommended Usage Model
 Fixed-size Arrays:
 Size known at compile time
 Contiguous data
 Multi-dimensional arrays
 Dynamic Arrays:
 Size unknown at compile time
 Contiguous data
 Queues:
 FIFO/Stack
 Associative Arrays:
 Sparse data – memories
 Index by number or string
3- 23

SystemVerilog Language Basics 3-23


SVTB © 2006
System Functions: Randomization

 $random: Return an 32-bit signed random number


 $urandom: Return a 32-bit unsigned random number
 $urandom_range(max, min): specify range of
unsigned random number
 $srandom(seed): Set random seed
 Or use run-time switch: +ntb_random_seed=seed_value
 randcase: Select a weighted executable statement
randcase
10 : f1();
20 : f2(); // f2() is twice as likely to be executed as f1()
50 : x = 100;
30 : randcase … endcase; // randcase can be nested
endcase

3- 24
File I/O (from Verilog 2001):
program test();
/* Assume file contains:
0123
4567
89
*/
initial begin
int i, file;
file = $fopen("stimulus.txt", "r");
while (! $feof(file)) begin
if ($fscanf(file, "%d", i) == 0) break;
$display("i = %0d", i);
end
$fclose(file);
end
endprogram

SystemVerilog Language Basics 3-24


SVTB © 2006
User Defined Types and Type Cast

 Use typedef to create a synonym for another type


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

 Use <type>’(<value>|<variable>) to dynamically


convert data types
Example:
typedef bit [31:0] uint;
bit[7:0] payload[];
int temp = $random;
payload = new[(temp % 3) + 2];
payload = new[(uint’(temp) % 3) + 2];
payload = new[(unsigned’(temp) % 3) + 2];

What are the possible sizes of the array?


3- 25
payload = new[(temp % 3) + 2]; will result in possible size of 0, 1, 2, 3 or 4 because
temp % 3 have the following possible values: -2, -1, 0, 1 and 2.

payload = new[(uint’(temp) % 3) + 2]; will result in possible size of 2, 3 or 4


because uint’(temp) % 3 have the following possible values: 0, 1 and 2.

payload = new[(unsigned’(temp) % 3) + 2]; will result in possible size of 2, 3 or


4 because unsigned’(temp) % 3 have the following possible values: 0, 1 and 2.

$cast() can also be used to convert data types.

SystemVerilog Language Basics 3-25


SVTB © 2006
Operators
+ - * / arithmetic ~ bitwise negation
% modulus division & bitwise and
++ -- increment, decrement &~ bitwise nand
> >= < <= relational |~ bitwise nor
! logical negation | bitwise inclusive or
&& logical and ^ bitwise exclusive or
|| logical or ^~ bitwise exclusive nor
== logical equality
!= logical inequality & unary and
=== case equality ~& unary nand
!== case inequality | unary or
==? wildcard case equality ~| unary nor
!=? wildcard case inequality ^ unary exclusive
<< shift left ~^ unary exclusive nor
>> shift right ?: conditional (ternary)

{} concatenation

Assignment:
= += -= *= /= %= <<= >>= &= |= ^= ~&= ~|= ~^=
3- 26

SystemVerilog Language Basics 3-26


SVTB © 2006
Know Your Operators!

Example pitfall to watch out for:


What is printed to console with following code?
reg[3:0] sample, ref_data;
sample = dut.cb.dout[3:0];
if (sample != ref_data) $display(“Error!”);
else $display(“Pass!”);
 When sample = 4’b1011 & ref_data = 4’b1010?
 When sample = 4’b101x & ref_data = 4’b1010?
 When sample = 4’b101x & ref_data = 4’b101x?
Avoid false positives by checking for pass condition!
sample = dut.cb.dout[3:0]; RTL
TB Good Bad
if (sample == ref_data) ;
else $display(“Error!”); Pass √
Tape out!
???
Debug Debug
Fail testbench RTL code

3- 27
In Verilog, the == and != operator will return x as the result if any operand contains x or z. The if
statement then treats x as a failure. Therefore, in the example above, if either sample or ref contains
x or z, the else condition will always execute.

SystemVerilog Language Basics 3-27


SVTB © 2006
Sequential Flow Control

 Conditional:
 if (x==7) a=7; else a=8;
 a = (x == y) ? 7 : 8;
 case statements

 Loops:
 repeat(…) begin … end
 for(…) begin … end

 foreach() begin … end


 while(…) begin … end

 do begin … end while (…);


 break to terminate loop

 continue to terminate current loop iteration

3- 28

SystemVerilog Language Basics 3-28


SVTB © 2006
Subroutines (task and function)
 Tasks can block
Pass by reference
 Functions can not block
task print_sum(ref integer a[], input int start=0);
automatic int sum = 0;
for (int j=start; j<a.size(); j++)
Default value
sum += a[j];
$display(“Sum of array is %0d”, sum);
endtask
… task does not return value
print_sum(my_array);

Subroutines in program
block defaults to static
can be made automatic function automatic int factorial(int n);
Subroutines in class static int id = 0;
defaults to automatic int my_id = id++; Pass by value
if (n < 2) factorial = 1;
Subroutine variables else factorial = n * factorial(n-1);
defaults to subroutine endfunction
scope and lifetime. Can be … function name returns value
made automatic or static Result = factorial(my_value);

3- 29
Since functions can not block, you will not be able to call a task within a function.

To make your subroutines as flexible as possible (usable in both function and task), you should
develop your subroutines are functions if you know for sure that time passage will not be required.

SystemVerilog Language Basics 3-29


SVTB © 2006
Subroutine Arguments

 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, makes the argument variable the
same as the calling variable
 Changes to argument variable will change calling variable
immediately
 const ref – pass by reference but read only
 Saves time and memory for passing arrays to tasks & functions

Default dir is input, a, b: input logic Read-only pass


default type is logic u, v: output bit [15:0] via reference

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

3- 30

SystemVerilog Language Basics 3-30


SVTB © 2006
Test For Understanding

 What’s the direction and data type of each argument?


task T3(ref byte a[], reg[15:0] b, c, output u, v);
b = c;
foreach(a[i]) dir is ref, dir is ? dir is ?
a[i] = i; type is byte type is ? type is ?
endtask

program test();
initial begin
reg[15:0] B = 100, C = 0, D = 0, E = 0;
byte A[] = {1,3,5,8,13};
T3(A, B, C, D, E);
foreach(A[i])
$display(A[i]);
$display(B, C, D, E);
end
endprogram What will be displayed on screen?

3- 31
Argument direction type
a[] ref byte
b ref bit[15:0]
c ref bit[15:0]
u output bit[15:0]
v output bit[15:0]

The program test results is as follows:


0
1
2
3
4
0 0 X X

To make b and c pass via value, change the declaration to:

Task T3(ref byte a[], input bit[15:0] b, c, output u, v);

SystemVerilog Language Basics 3-31


SVTB © 2006
Scope and Lifetime Of Variables
am
pr ogr
i n side lt and
ed u nd
data declared de clar by defa asks a
t m
outside of int max = 10; data static by all rogra
is e at p
ibl
program is static int n;
c c ess ns in th
a
and global program top; ctio
int n; fun
initial begin : top_initial
i is automatic and
automatic int i;
local to this block n = 1;
for (i=2; i<=max; i++)
n += i;
my_test();
n is sta Code blocks can be labeled
t end : top_initial
local to ic and task my_test(); (useful for debugging)
my_tes
t() int n = 1;
for (int i=2; i<=max; i++)
Root global n n += i; Ro
can only be set $root.n <= n; ma ot g
g x v l ob
with non-blockin
end loc
al a ri a l
endprogram ab
assignment n le
3- 32
Any data declared outside a module, interface, task, or function, is global in scope (can be used
anywhere after its declaration) and has a static lifetime (exists for the whole elaboration and
simulation time).
SystemVerilog data declared inside a module or interface but outside a task, process or function is
local in scope and static in lifetime (exists for the lifetime of the module or interface). This is
roughly equivalent to C static data declared outside a function, which is local to a file.
Data declared in an automatic task, function or block has the lifetime of the call or activation and a
local scope. This is roughly equivalent to a C automatic variable. Data declared in a static task,
function or block defaults to a static lifetime and a local scope.
Verilog-2001 allows tasks and functions to be declared as automatic, making all storage within the
task or function automatic.
SystemVerilog allows specific data within a static task or function to be explicitly declared as
automatic. Data declared as automatic has the lifetime of the call or block, and is initialized on each
entry to the call or block. SystemVerilog also allows data to be explicitly declared as static. Data
declared to be static in an automatic task, function or block has a static lifetime and a scope local to
the block. This is like C static data declared within a function.
SystemVerilog adds an optional qualifier to specify the default lifetime of all variables declared in
task, function or block defined within a module, interface or program. The lifetime qualifier is
automatic or static. The default lifetime is static.

SystemVerilog Language Basics 3-32


SVTB © 2006
Code Block Lifetime Controls
 Execution of the program ends
 When all initial blocks in program reaches end of code block
 Or, when $finish is executed
 Simulation ends when all programs end
 Execution of a subroutine ends
 When the associated end statement is encountered:
 endtask, endfunction
 Or, when return is executed

 Execution of a loop ends


 When the associated end statement is encountered
 end
 Or, when break is executed
 When continue is executed, the current loop execution
ends, simulation advances loop to next iteration
3- 33

SystemVerilog Language Basics 3-33


SVTB © 2006
Unit Objectives Review

Having completed this unit, you should be able to:


 Define the structure of a SystemVerilog program
 Declare variables in a SystemVerilog program
 Describe variable visibility in program,
local blocks and sub-routines
 Use flow control constructs to implement
SystemVerilog verification testbench

3- 34

SystemVerilog Language Basics 3-34


SVTB © 2006
Appendix

Advanced SystemVerilog Constructs


Import and Export subroutines
Packed array
Struct
Union

SystemVerilog Language Basics 3-35


SVTB © 2006
Import and Export Subroutines
// Root level subroutine
task root_task(); $display("I'm Root Task"); endtask
module bfm(router_io.BFM bfm_io); // BFM’s that implement I/O via SystemVerilog interface
// Subroutine to be accessed by test program
task bfm_io.bfm_task(); $display("I'm BFM task"); endtask
endmodule
module vip(…); // BFM’s that do not implement I/O via SystemVerilog interface
// Subroutine to be accessed by test program
task vip_task(); $display("I'm VIP task"); endtask
endmodule
interface top_io(); // SystemVerilog Interface to be used by test program
// Subroutine to be accessed by test program
task interface_task(); $display("I'm Interface task"); endtask
// Wrapper for non-SystemVerilog BFM’s
task vip_task();
test_top.VIP.vip_task(); // XML reference via top-level instance
endtask
modport TB(import task interface_task(), import task bfm_task2(), import task vip_task());
modport BFM(export task bfm_task());
endinterface
program automatic TB(top.TB test);
initial begin module test_top;
$root.root_task(); // direct $root access top_io IO(…);
test_top.VIP.vip_task(); // VIP XML access via top module tb TB(IO);
test_top.BFM.bfm_task(); // BFM XML access via top module router DUT(IO);
test.vip_task(); // interface VIP access bfm BFM(IO);
test.bfm_task(); // interface BFM access vip VIP(…);
test.interface_task(); // interface access endmodule
end
endprogram

3- 36

SystemVerilog Language Basics 3-36


SVTB © 2006
Packed Arrays
 Defines a packed array structure

type [msb:lsb] [msb:lsb] name [constant];

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

Bytes[0][3] Bytes[0][1][6]
Bytes[0] 7 65 4 3 21 0 7 65 4 3 21 0 7 65 4 3 21 0 7 65 4 3 21 0
Bytes[1] 7 65 4 3 21 0 7 65 4 3 21 0 7 65 4 3 21 0 7 65 4 3 21 0
Bytes[2] 7 65 4 3 21 0 7 65 4 3 21 0 7 65 4 3 21 0 7 65 4 3 21 0

Bytes[2][2][5:4] = Bytes[1][3][4:3]; Bytes[1][0] = Bytes[2][1];

Bytes[2] = 32’hbeef_deed;
Bytes[2] 1 01 1 1 11 0 1 11 0 1 11 1 1 10 1 1 11 0 1 11 0 1 10 1

3- 37

SystemVerilog Language Basics 3-37


SVTB © 2006
Array Querying System Functions
 $dimensions (array_name)
 Returns the # of dimensions in the array
 $left (array_name, dimension)
 Returns MSB of specified dimension
 $right (array_name, dimension)
 Returns LSB of specified dimension dimension numbers
 $low (array_name, dimension) 3 4 1 2
 Returns the min of $left and $right
bit [3:0][7:0] Bytes [0:2][0:5];
 $high (array_name, dimension)
 Returns the max of $left and $right
 $increment (array_name, dimension)
 returns 1 if: $left is >= $right,
 returns –1 if: $left is < $right.
 $size (array_name, dimension)
 Returns the total # of elements in the specified dimension
($high - $low +1)

3- 38

SystemVerilog Language Basics 3-38


SVTB © 2006
Array Querying System Functions Examples
int c[2], a[2][2];
bit[31:0] b[0:2][0:1]={{3,7},{5,1},{0,4}};
$display($dimensions(a));
for (int i=1; i<=$dimensions(a); i++) begin
$display("a dimension %0d size is %0d", i, $size(a, i));
$display("a dimension %0d left is %0d", i, $left(a, i));
$display("a dimension %0d right is %0d", i, $right(a, i));
$display("a dimension %0d low is %0d", i, $low(a, i));
$display("a dimension %0d high is %0d", i, $high(a, i));
$display("a dimension %0d increment is %0d", i, signed'($increment(a, i)));
end
$display($dimensions(b));
for (int i=1; i<=$dimensions(b); i++) begin
$display("b dimension %0d size is %0d", i, $size(b, i));
$display("b dimension %0d left is %0d", i, $left(b, i));
$display("b dimension %0d right is %0d", i, $right(b, i));
$display("b dimension %0d low is %0d", i, $low(b, i));
$display("b dimension %0d high is %0d", i, $high(b, i));
$display("b dimension %0d increment is %0d", i, signed'($increment(b, i)));
end
See note section below for print out
3- 39
3 3
a dimension 1 size is 2 b dimension 1 size is 3
a dimension 1 left is 0 b dimension 1 left is 0
a dimension 1 right is 1 b dimension 1 right is 2
a dimension 1 low is 0 b dimension 1 low is 0
a dimension 1 high is 1 b dimension 1 high is 2
a dimension 1 increment is -1 b dimension 1 increment is -1
a dimension 2 size is 2 b dimension 2 size is 2
a dimension 2 left is 0 b dimension 2 left is 0
a dimension 2 right is 1 b dimension 2 right is 1
a dimension 2 low is 0 b dimension 2 low is 0
a dimension 2 high is 1 b dimension 2 high is 1
a dimension 2 increment is -1 b dimension 2 increment is -1
a dimension 3 size is X b dimension 3 size is 32
a dimension 3 left is X b dimension 3 left is 31
a dimension 3 right is X b dimension 3 right is 0
a dimension 3 low is X b dimension 3 low is 0
a dimension 3 high is X b dimension 3 high is 31
a dimension 3 increment is X b dimension 3 increment is 1

SystemVerilog Language Basics 3-39


SVTB © 2006
Data Structure
 Defines a wrapper for a set of variables
 Similar to C struct or VHDL record
typedef struct { struct {
data_type variable0; data_type variable0;
data_type variable1; data_type variable1;
} struct_type [, …]; } struct_variable [, …];
Example: Example:
typdef struct { struct {
int my_int; int my_i;
real my_real; real my_r;
} my_struct; } my_var0, my_var1;
my_struct var0, var1; my_var0 = { 32, 100.2 };
var0 = { 32, 100.2 }; my_var1 = { default:0 };
var1 = { default:0 }; my_var1.my_i = my_var0.my_i;
var1.my_int = var0.my_int;
3- 40

SystemVerilog Language Basics 3-40


SVTB © 2006
Data Union
 Overloading variable definition
 Similar to C union
typedef union { union {
data_type variable0; data_type variable0;
data_type variable1; data_type variable1;
} unio_type; } union_variable;
Example: Example:
typdef union { union {
int my_int; int my_i;
real my_real; real my_r;
} my_struct; } my_var0, my_var1;
my_struct var0, var1; my_var0.my_i = 32;
var0.my_int = 32; my_var1.my_r = 100.3;
var1.my_real = 100.3; my_var1.my_i = my_var0.my_i;
var1.my_int = var0.my_int;
3- 41

SystemVerilog Language Basics 3-41


SVTB © 2006
This page was intentionally left blank.

SystemVerilog Language Basics 3-42


SVTB © 2006
Agenda

DAY
1
1 The Device Under Test (DUT)

2 SystemVerilog Verification Environment

3 SystemVerilog Language Basics

4 Drive and Sample DUT Signals

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 4- 1

Drive and Sample DUT Signals 4-1


SVTB © 2006
Unit Objectives

After completing this unit, you should be able to:


 Drive DUT signals in Device Driver routines
 Sample DUT signals in Device Monitor routines
 Synchronize to known point in simulation

4- 2

Drive and Sample DUT Signals 4-2


SVTB © 2006
Driving & Sampling DUT Signals

 DUT signals are driven in the device driver


 DUT signals are sampled in the device monitor

Configure

Generator Coverage

Transactor Self Check Transactor

Driver Monitor

DUT

4- 3

Drive and Sample DUT Signals 4-3


SVTB © 2006
SystemVerilog Testbench Timing
 Program code defaults to Cycle-based Simulation
for synchronous drives and samples:
 Events occur at interface clock-block clock edges
router.test_top.sv
router.v router.tb.sv
router.if.sv

modport
modport

Collection
async signals SVTB
DUT DUT signals
of signals clock block
program

SystemClock

SystemVerilog Testbench (SVTB)


Synchronous program code execution
Simulation Time
Sample
Drive
clock
t0 – input skew t0 t0 + output skew
4- 4

Drive and Sample DUT Signals 4-4


SVTB © 2006
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

clock

data

REGION Prepone Active Observed Reactive Postpone

ACTIVITY sample design assertions testbench $monitor

Previous Current Next


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

Drive and Sample DUT Signals 4-5


SVTB © 2006
Synchronous Drive Statements
[##num] interface.cb.signal <= [##num] <value | expression>;
 Drive must be non-blocking
 ##num specified clock cycle delays
 Driving of input signal is not allowed
##1 router.cb.din[3] <= var_a;
clock

var_a
din[3]

expression evaluates
Statement executes here
Apply drive here
Next statement executes
router.cb.din[3] = 1’b1; //error
##1 router.cb.dout[3] <= 1’b1; //error
##2 router.din[3] <= 1’b1; //error
4- 6
##2 router.cb.din <= var_a; next_statement; is similar to:
#2 router.cb.din <= var_a; next_statement;
In that, time advances first, var_a is then evaluated, the assignment is scheduled for the non-blocking
region (+output delay) and next_statement is executed.

router.cb.din <= ##2 var_a; next_statement; is similar to:


router.cb.din <= #2 var_a; next_statement;
In that, var_a is evaluated immediate, the assignment is scheduled for the second valid clock edge
from now (+output delay) and next_statement is executed without time advancing.

Explanation for the errors:


The first error is due to driving using blocking assignment.
The correction is to make the drive a non-blocking assignment:
router.cb.din[3] <= 1’b1;
The second error is an illegal drive of input signal. No correction is possible
The third error is caused by forgetting to drive via the clocking block.
The correction is to reference the clocking block:
##2 router.cb.din[3] <= 1’b1;

Drive and Sample DUT Signals 4-6


SVTB © 2006
Synchronous Drive Example

##1 router.cb.din[3] <= 1;


Example:
var_a = var_b;
Current clock edge ##3 router.cb.din[3] <= var_b;

clock

var_b

var_a
variables
signal driven after delay
router.din[3]

1 3
cycle cycles

var_a = var_b executed after one clock cycle

4- 7

Drive and Sample DUT Signals 4-7


SVTB © 2006
Sampling Synchronous Signals

variable = interface.cb.signal;
 No delay attribute (## num)
 Variable is assigned the sampled value
 Sampling of output signal is not allowed
Examples:
data[i] = router.cb.dout[7];
all_data = router.cb.dout;
@(negedge router.frameo_n[7]); //error
$display(“din = %b\n”, router.cb.din); //error
if(router.cb.din[3] == 1’b0) begin … end //error

4- 8

Drive and Sample DUT Signals 4-8


SVTB © 2006
Signal Synchronization

 Synchronize to clock edge specified in clocking block

@(router.cb); // continue on next clock edge specified in cb


repeat (3) @(router.cb); // Wait for 3 cb clock cycles

 Synchronize to any edge of signal

@(router.cb.frameo_n[7]); // continue on any edge


@(posedge router.cb.frameo_n[7]); // continue on posedge
@(negedge router.cb.frameo_n[7]); // continue on negedge
wait (router.cb.valido_n==0); // wait for expression
// no delay if already true

4- 9

Drive and Sample DUT Signals 4-9


SVTB © 2006
Test For Understanding (1/2)

On what edge is the following detected?


@(negedge router.cb.frameo_n[7]);

Current clock edge


A B C D E
clock

router.cb.frameo_n[7]

Does this work for when monitoring output of DUT?

4- 10
The negedge will be detected at clock edge D (not C).

This is the edge that you need your monitor transactors to be at when observing the output of the
DUT. The monitoring routines at clock edge D acts as the capture flip-flop for the signals launched
by clock edge C.

Drive and Sample DUT Signals 4-10


SVTB © 2006
Test For Understanding (2/2)
Complete the timing diagram for the following:
initial begin
router.reset_n <= 0;
#100 router.cb.reset_n <= 1;
router.cb.frame_n <= ’1;
router.cb.valid_n <= ##3 ’1;
##2 router.cb.frame_n <= ’0;
repeat(3) @(router.cb);
end
A B C D E

clock
0 100 200 300 400 500

reset_n
frame_n
valid_n

4- 11
SystemVerilog’s behavior is exactly the same as Verilog.
Non-blocking assignments does not advance time for the next line.
##0 means current simulation time. ##1 means next valid clock edge.
In either case, synchronous signals can only be driven at a valid clock edge + output skew.

Drive and Sample DUT Signals 4-11


SVTB © 2006
Lab 2 Introduction

Develop Generator, Transactor


& Device Drivers to drive one
packet through the router
Generator, Transactor
90 min & Device Drivers

Generator,
Transactor & reset()
Device Drivers Compile & Simulate
Generator

Transactor
Check Result with GUI
Driver

DUT

4- 12

Drive and Sample DUT Signals 4-12


SVTB © 2006
Unit Objectives Review

Having completed this unit, you should be able to:


 Drive DUT signals in Device Driver routines
 Sample DUT signals in Device Monitor routines
 Synchronize to known point in simulation

4- 13

Drive and Sample DUT Signals 4-13


SVTB © 2006
This page was intentionally left blank.

Drive and Sample DUT Signals 4-14


SVTB © 2006
Agenda

DAY
2
5 Concurrency

6 Inter-Process Communications

Object Oriented Programming (OOP)


7 – Encapsulation

Object Oriented Programming (OOP)


8 – Randomization

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 5- 1

Concurrency 5-1
© 2006
SVTB
Unit Objectives

After completing this unit, you should be able to:


 Divide a testbench into multiple current
processes to execute parallel tasks

5- 2

Concurrency 5-2
© 2006
SVTB
Day 1 Review

Phases of verification
Preliminary Broad-Spectrum Corner-case
Verification Verification Verification

Goal
% Coverage

Directed
Verification

Time

Build verification
environment

5- 3

Concurrency 5-3
© 2006
SVTB
Day 1 Review (Building Testbench Files)

router.v

ntb_template -t router router.v

Discard
router.test_top.v router.vr.tmp router.if.vrh

router.test_top.sv router.if.sv router.tb.sv


Top level harness Interface Test program

vcs –sverilog router.test_top.sv router.tb.sv router.if.sv router.v

simv

5- 4

Concurrency 5-4
© 2006
SVTB
Day 1 Review (Testbench Architecture)

Checks Checks
Configure
completeness correctness

Generator Coverage Identifies


transactions
Test
Transactor Self Check Transactor program
Top level
harness file
Driver Observes data Monitor
from DUT

DUT interface

5- 5

Concurrency 5-5
© 2006
SVTB
Concurrency in Simulators

What does concurrency mean?


In all concurrent processes, events scheduled for the
current time will execute before any event scheduled for
a future time executes.
t0 t1 t2
process 1 statement 1;

process 2 statement a;

process 3 statement 2; statement b;

process 4 statement 3; statement c;

Ready events
Future events
5- 6

Concurrency 5-6
© 2006
SVTB
Creating Concurrent Processes

 Concurrent processes are created in a fork - join block:

int a, b, c;
fork
statement0;
begin
statement1;
statement2;
end
join_all | join_any | join_none
statement3;

 Statements enclosed in begin-end in a fork-join block are


executed sequentially as a single concurrent child process
 No pre-determined execution order for concurrent processes
 All child processes share the parent variables
5- 7

Concurrency 5-7
© 2006
SVTB
How Many Child Processes?

fork
fork begin
begin C:
A: recv();
recv(); send();
end end
begin join
send();
end
join
fork
begin
D: begin
fork send();
recv(); recv();
B: send(); end
join check();
end
join

5- 8

Concurrency 5-8
© 2006
SVTB
Join Options

fork fork fork


fork
statement1;
statement2;
join_all | join_any | join_none
statement3;
join_all join_any join_none

all -child processes execute and all child processes must


complete before statement3 is executed
any -child processes execute and one child process must
complete before statement3 is executed
none -statement3 executes, child processes are queued
but not executed until the parent process
encounters a wait statement or completes

5- 9

Concurrency 5-9
© 2006
SVTB
Process Execution

 Once a process executes, it continues to execute until a


wait statement is encountered:
 Child processes generated by the executing process are queued
 When the executing process encounters a wait statement,
a queued ready process executes
 Time advances when all processes are in a wait state
Wait statements examples:
@(router.cb);
##1 router.cb.din <= 4’hf;
join_any
join_all

5- 10

Concurrency 5-10
© 2006
SVTB
Process Execution Model
 One executing process, all other processes reside on queues
 READY - to be executed at current simulation time
 WAIT - blocked from execution until wait condition is met
 When the executing process goes into a wait state, it moves
to a WAIT queue, the next READY process then executes
 Simulation time advances when all processes are in WAIT

Executing thread
At start of simulation: process blocked process
program READY WAIT
process blocked process

child process blocked process

Schedule for execution Moves to READY queue when


at current simulation time wait condition is met
5- 11

Concurrency 5-11
© 2006
SVTB
Subtleties in Concurrency (1/5)

a = 0;
fork
begin
while ( a != 5 )
if ( $time > MAX_TIME )
$finish;
end

begin
##5 bus.reg <= 1’b1;
a = 5;
end
join

Will this work?

5- 12

Concurrency 5-12
© 2006
SVTB
Subtleties in Concurrency (2/5)

In multi-threaded programs, all threads must


be finite or advance the clock!
a = 0;
fork
begin
while ( a != 5 )
if ( $time > MAX_TIME )
$finish;
else
@(bus.cb);
end
begin
##5 bus.reg <= 1’b1;
a = 5;
end
join
5- 13

Concurrency 5-13
© 2006
SVTB
Subtleties in Concurrency (3/5)
Child processes share the same parental variables
program fork_join1;
initial begin Can the child process assess a and b?
integer a=0, b=1;
fork What are the final values of a and b?
begin
integer d=3;
a = b + d;
end
begin
integer e=4;
b = a + e;
end
join
$display(“a = %0d”, a);
$display(“b = %0d”, b);
end
endprogram
5- 14

Concurrency 5-14
© 2006
SVTB
Subtleties in Concurrency (4/5)

automatic.sv Desired output:


program test; Driving port 0
initial begin Driving port 1
for (int i = 0; i < 16; i++) begin Driving port 2
fork Driving port 3
send(i); Driving port 4
join_none Driving port 5
end Driving port 6
end Driving port 7
task send(int i); ...
$display(“Driving port %0d”, i);
while (1) begin
#1;
break;
end
endtask
endprogram

5- 15

Concurrency 5-15
© 2006
SVTB
Subtleties in Concurrency (5/5)

 Simulation output:
Driving port 16
Driving port 16 What happened to ports 0-15?
Driving port 16 Why did simulation stop at time 0?
Driving port 16

Simulation stopped at time 0

5- 16

Concurrency 5-16
© 2006
SVTB
Unroll the for-loop

program test;
initial begin
int i = 0; { send(i) }
fork READY
send(i); { send(i) }
join_none
i++; // i = 1; { send(i) }
fork
send(i);
join_none
i++; // i = 2;
{ send(i) }
fork
send(i);
join_none
Scheduled for execution
i++; // i = 3; at current simulation time
… (repeated 16 times total) But i = 16 before they execute
end
endprogram Simulation terminates when all procedural
code inside program block reaches end

5- 17

Concurrency 5-17
© 2006
SVTB
Solution (1/2): automatic Variable
 automatic variables:
Copied from parent when the child process is queued


 Once created, variables are local to the child thread

// program automatic test; Desired output:


program test;
Driving port 0
initial begin
Driving port 1
for (int i = 0; i < 16; i++) begin
Driving port 2
automatic int index = i;
Driving port 3
fork
Driving port 4
send(index);
Driving port 5
join_none
Driving port 6
end
Driving port 7
end
...
task send(int i);
$display(“Driving port %0d”, i);
...
endtask
Simulation terminates when all procedural
endprogram code inside program block reaches end
5- 18

Concurrency 5-18
© 2006
SVTB
Solution (2/2): Wait Control

 wait fork suspends process until all children


have completed execution
program automatic test;
initial begin
for (int i = 0; i < 16; i++) begin
int index = i;
fork
send(index);
join_none
end Blocking statement to control
wait fork; proper termination of
end simulation (more in later units)
task send(int i);
$display(“Driving port %0d”, i);
...
endtask
endprogram

5- 19
Another mechanism you can use is wait(…) or @(…). Example:

program automatic router_test(router_io.TB router);


int done = 0;
initial begin
for (int i=0; i<16; i++) begin
int j = i;
fork
send(j);
join_none
end
wait(done >= 16);
end
task send(int i);
$display("Driving port %0d", i);
while(1) begin
#1;
done++;
end
endtask
endprogram

Concurrency 5-19
© 2006
SVTB
Disable Forked Processes
 Watch-dog timer:
 disable fork terminates all child processes
program automatic test;
task recv();
fork: recv_wd_timer
begin
@(negedge router.cb.frameo_n[da]);
end
begin
repeat(1000) @(router.cb);
$display(“Timed out!”);
error_handler(); // user subroutine
end
join_any: recv_wd_timer
disable fork; // kill all child processes
// disable recv_wd_timer; // kill children in named block
get_payload();
endtask
endprogram
5- 20
The consequence of disable fork is to kill ALL child processes. This include all other fork-join
constructs within the executing process. This may not be desirable. One way to manage this is to
label the fork-join construct and disable just the named fork-join block. Example:

program automatic router_test(router_io.TB router);


initial begin
fork
begin #100 $display($time); end
join_none
fork: test1
begin $display("This is a test"); end
begin #10 $display("Did I execute?"); end
join_any : test1
disable test1;
// disable fork;
wait fork;
$display($time);
end
endprogram

Concurrency 5-20
© 2006
SVTB
Helpful Debugging Features

What to print for debugging?


 Use %m and $display() to print the simulation time,
and location of call
task check(); Indicate message type
int status;
(ERROR, DEBUG, etc.)
string message;
status = compare(message);
case (status) Simulation time
0: begin
$display("[ERROR]%0t: %s\n%m\n", $time, message);
$finish;
end Source code location
...
endcase
$display("[ERROR]%0d: Unsupported status %0d\n%m\n", $time, status);
endtask

5- 21

Concurrency 5-21
© 2006
SVTB
Unit Objectives Review

Having completed this unit, you should be able to:


 Divide a testbench into multiple current processes
to execute parallel tasks

5- 22

Concurrency 5-22
© 2006
SVTB
Agenda

DAY
2
5 Concurrency

6 Inter-Process Communications

Object Oriented Programming (OOP)


7 – Encapsulation

Object Oriented Programming (OOP)


8 – Randomization

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 6- 1

Inter-Process Communications 6-1


SVTB © 2006
Unit Objectives

After completing this unit, you should be able to:


 Establish order of execution using event flag
 Avoid resource collision with Semaphores
 Pass data via Mailbox

6- 2

Inter-Process Communications 6-2


SVTB © 2006
Inter-Process Communications (IPC)

 Concurrent processes require communication to


establish control for sequence of execution
 Three types are covered in this unit

Event based thread event thread


1 2

Resource sharing thread thread


resource
1 2

Data passing thread thread


IPC
1 2

6- 3

Inter-Process Communications 6-3


SVTB © 2006
Event Based IPC

process event process


1 2

 Synchronize operation of concurrent processes via


event variables:
 Process waits for event to be triggered
 Higher priority process triggers the event to enable the
waiting process to be placed into the READY queue
 Mainly used to control sequence of execution

6- 4

Inter-Process Communications 6-4


SVTB © 2006
Event Based IPC Example

Controlling order of execution.


program sync_trigger;
event A;
fork Parent my_func1 my_func2
my_func1(); fork
my_func2(); …
join
join
wait(A.triggered) …
task my_func1();
wait(A.triggered); $display …
$display(“Print 2nd”); ->A; …
}
endtask
$display …
task my_func2(); }
$display(“Print 1st”);
}
->A;
endtask
endprogram

6- 5

Inter-Process Communications 6-5


SVTB © 2006
Event Wait Syntax

 Wait until event has been triggered (one shot):


@(event_var [, event2]);
 Will be satisfied by events which occur after the execution
of this statement
 Wait until event has been triggered (persistent):
wait(event_var.triggered);
 Similar to @(event_var), but will also be satisfied by events
which happens during later during same simulation time
 Can be used to eliminate potential race condition

6- 6

Inter-Process Communications 6-6


SVTB © 2006
Trigger Syntax

->eventN;
 event variables are handles
 Assigning an event to another makes both event the
same event
Example:
event a, b, c;
a = b;
-> c;
-> a; // also triggers b
-> b; // also triggers a
a = c;
b = a;
-> a; // also triggers b and c
-> b; // also triggers a and c
-> c; // also triggers a and b

6- 7

Inter-Process Communications 6-7


SVTB © 2006
Controlling Termination of Simulation
program automatic router_test(router_io.TB router);
event DONE;
initial begin
fork
gen();
check();
join_none
for (int i=0; i<16; i++)
fork
send(i);
recv(i);
join_none
wait(DONE.triggered); Blocking statement to
end prevent termination of
task check(); simulation until done
while(1) begin
if (($get_coverage() == 100) || ...)
->DONE;
... Trigger event when
end termination condition
endtask is detected
endprogram
6- 8

Inter-Process Communications 6-8


SVTB © 2006
Resource Sharing IPC

Process Process
1 resource 2

 Synchronize operation of concurrent Processes via


access to shared resources:
 Process requests for a shared resource before executing a
critical section of code
 Process waits if the requested resource is unavailable

 Process resumes execution when the requested resource


becomes available

6- 9

Inter-Process Communications 6-9


SVTB © 2006
Semaphores

 Each Semaphore is a set of buckets in which keys can


be deposited and removed:
 A process tries to acquire keys from a semaphore bucket
 Process execution waits until keys requested are available in
the semaphore bucket
 When the requested keys becomes available, process
execution resumes and the requested keys removed from
the semaphore bucket
 Mainly used to prevent multiple processes from
accessing the same hardware signal or using same
software resource

6- 10

Inter-Process Communications 6-10


SVTB © 2006
Semaphores

 Semaphores are supported via built-in semaphore class:

class semaphore;
function new(int keyCount = 0);
task put(int keyCount = 1);
// the following is blocking:
task get(int keyCount = 1);
// the following is non-blocking: 1 for success 0 for failure
function int try_get(int keyCount = 1);
endclass

6- 11

Inter-Process Communications 6-11


SVTB © 2006
Creating Semaphores

 Each semaphore bucket is an semaphore object


semaphore sem[];
sem = new[4];
foreach (sem[i]) begin
sem[i] = new(3);
end
sem[0] sem[1] sem[2] sem[3]

T T T T
T T T T T T T T

6- 12

Inter-Process Communications 6-12


SVTB © 2006
Acquiring Semaphore Keys

sem[0]
Before
T
T T

sem[0].get(2);
sem[0]
After

T
if (!sem[0].try_get(2)) // does not block
$display(“Failed”);
sem[0].get(2); // blocks until two keys are available
6- 13

Inter-Process Communications 6-13


SVTB © 2006
Returning/Creating Semaphore Keys

sem[0]

Before
T

sem[0].put(2);
sem[0]

T After
T T

6- 14

Inter-Process Communications 6-14


SVTB © 2006
Arbitration Example

program automatic router_test(router_io.TB router);


semaphore sem[];
Create semaphore array to
...;
represent each output port
sem = new[16];
foreach(sem[i])
sem[i] = new(1);
Construct each individual
...;
semaphore bucket
task send();
sem[da].get(1);
send_addrs(); Block if others are driving
send_pad(); the chosen output port
send_payload();
sem[da].put(1); Re-deposit keys when
endtask done with driving port
...;
endprogram

6- 15

Inter-Process Communications 6-15


SVTB © 2006
Mailbox

process process
1 data 2

 Messages are passed between processes via mailbox:


 A process sends data by putting messages a mailbox
 A process retrieves data by getting messages from the mailbox
 If a message is not available, the process can wait until there is
a message to retrieve
 Process resumes execution once the message becomes
available
 Mainly used for passing data between processes

6- 16

Inter-Process Communications 6-16


SVTB © 2006
Mailboxes

 Mailboxes are supported via built-in semaphore class:

class mailbox #(type T = dynamic_singular_type);


function new(int bound = 0);
function int num(); // return # of messages
task put(T message); // wait if exceed bound
task get(ref T message); // wait if no message
task peek(ref T message);
function int try_put(T message);
function int try_get(ref T message);
function int try_peek(ref T message);
endclass

6- 17
#(type T = dynamic_singular_type) is not yet supported.
Bounded size is not yet supported.
try_put() is not yet supported.

Inter-Process Communications 6-17


SVTB © 2006
Creating Mailboxes

typedef mailbox #(string) my_mbox;


mailbox mbx[]; // messages can be any type
my_mbox mbx_typed = new(); // messages must be string type
mbx = new[4];
for (int i=0; i<mbx.size(); i++) begin
mbx[i] = new(i+2); // mbx[i] bound to max of i+2 messages
end

mbx[0] mbx[1] mbx[2] mbx[3] mbx_typed


string

unbounded

string

6- 18
Typed mailbox is not yet supported.
Bounded mailbox is not yet supported.

Inter-Process Communications 6-18


SVTB © 2006
Putting Messages into Mailboxes
task put(message); // block if exceeds bound
function int try_put(message); // non-blocking
Example:
int status;
bit[15:0] test_data = 16’hcafe
mailbox mbox = new();
mbox.put(test_data);
mbox.put(“café”);

mbox
16’hcafe
“café”

6- 19
try_put() is not yet supported.

Inter-Process Communications 6-19


SVTB © 2006
Retrieve Messages from Mailboxes (1/2)
task get(ref message); // block if mailbox is empty
// simulation error if message type mismatches
function int try_get(ref message); // non-blocking
// return 1 if successful, 0 if no message, -1 if mismatch
Example:
int status;
mbox
bit[15:0] test_data = 16’hcafe

16’hcafe
mailbox mbox = new();

“café”
mbox.put(test_data);
mbox.put(“cafe”);
mbox.get(test_data);
$display(“test_data = %0h”, test_data); // test_data = cafe
status = mbox.try_get(test_data); // status = -1
mbox.get(test_data); // simulation error!

6- 20

Inter-Process Communications 6-20


SVTB © 2006
Retrieve Messages from Mailboxes (2/2)
task peek(ref message); // block if mailbox is empty
function int try_peek(ref message); // non-blocking
// return number of message in mailbox if successful,
// 0 if no message, -1 if mismatch
Example: mbox
int status; bit[15:0] test_data = 16’hcafe;

16’hcafe
“café”
string s;
mailbox mbox = new();
mbox.put(test_data);
mbox.put(“café”);
$display(“# of message = %0d”, mbox.num()); // 2 messages
mbox.peek(test_data); // still 2 messages left
status = mbox.try_peek(test_data); // still 2 messages
mbox.get(test_data);
mbox.get(s);
status = mbox.try_peek(test_data); // status = 0;
mbox.peek(s); // blocks, if new message is not string, type error!
6- 21

Inter-Process Communications 6-21


SVTB © 2006
Lab 3 Introduction

Add Concurrent
Monitor & Self-check
Add Monitor & Self-Check
90 min
Self-check

reset() Compile & Simulate

gen() Self Check

send() Transactor
Validate self-check
Driver Monitor

DUT

6- 22

Inter-Process Communications 6-22


SVTB © 2006
Unit Objectives Review

Having completed this unit, you should be able to:


 Establish order of execution using event flag
 Avoid resource collision with Semaphores
 Pass data via Mailbox

6- 23

Inter-Process Communications 6-23


SVTB © 2006
This page was intentionally left blank.

Inter-Process Communications 6-24


SVTB © 2006
Agenda

DAY
2
5 Concurrency

6 Inter-Process Communications

Object Oriented Programming (OOP)


7 – Encapsulation

Object Oriented Programming (OOP)


8 – Randomization

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 7- 1

OOP Encapsulation 7-1


SVTB © 2006
Unit Objectives

After completing this unit, you should be able to:


 Raise level of abstraction by building data
structure with self-contained functionality:
 OOP encapsulation
 Protect integrity of data in OOP data structure:
 OOP data hiding
 Simplify data initialization process:
 OOP constructor

7- 2

OOP Encapsulation 7-2


SVTB © 2006
Abstraction Enhances Re-Usability of Code

Project A Project B

Tests-A Re-usable Tests-B

Configure Configure

Generator Coverage Generator Coverage

Re-usable
Transactor Self Check Transactor Transactor Self Check Transactor

Driver Monitor Driver Monitor

DUT A DUT B

Create OOP representations

7- 3

OOP Encapsulation 7-3


SVTB © 2006
OOP Encapsulation (OOP Class)
 Similar to a module, an OOP class encapsulates:
 Variables (properties) used to model a system
 Subroutines (methods) to manipulate the data
 Properties & methods are called members of class
class DriveXactor;
string name;
bit[3:0] sa, da; Class properties are global inside the class
bit[7:0] payload[];
task send();
send_addrs();
send_pad();
send_payload();
endtask
task send_addrs(); ... endtask
task send_pad(); ... endtask
task send_payload(); ... endtask
endclass

7- 4

OOP Encapsulation 7-4


SVTB © 2006
Creating OOP Objects

 OOP objects are created from class definitions:


 Similar to instance creation from module definition
 Object memory is allocated by calling new()

program Main;
class DriveXactor; Handle
driver1
DriveXactor driver1; Handle
DriveXactor driver2; driver2
driver2 = new();
… Memory
endprogram
Handle
class Packet; obj_hdl
Packet obj_hdl = new();

Memory

7- 5
Classes can be declared inside the program block or outside the program block ($root). When
declared inside the program block, the class definition is only visible within the program block in
which the class is declared. When declared outside the program block, the class definition is
accessible by all program blocks.

With VCS2005.06-SP1, when compiling SystemVerilog code in which classes are declared at the
$root scope, the “–ntb_opts svp” compile switch must be set.

OOP Encapsulation 7-5


SVTB © 2006
Accessing Object Members

 Object members are accessed via the object handle:


 Similar to accessing instance signals and subroutines

program Main;
class DriveXactor;
bit[3:0] sa, da;
byte payload[];
task send();
...
endclass
DriveXactor driver;
initial begin
driver = new();
driver.sa = 3; // access property
driver.da = 7; // access property
driver.send(); // access method
end
endprogram

7- 6

OOP Encapsulation 7-6


SVTB © 2006
Initialization of Object Properties
 Define constructor new() to initialize properties:
 No return type in declaration
 Executes immediately after object memory is allocated
 Not accessible via dot (.) notation
program Main
class Packet;
bit[3:0] sa, da;
bit[7:0] payload[];
“this” keyword function new(bit[3:0] sa, da, int payload_size);
unambiguously refers this.sa = sa;
to class properties or this.da = da;
methods of the this.payload = new[payload_size];
endfunction
current instance.
endclass
initial begin
Packet pkt1 = new(3, 7, 2);
pkt1.new(5, 8, 3); // syntax error!
end
endprogram

7- 7

OOP Encapsulation 7-7


SVTB © 2006
OOP Data Hiding (Integrity of Data)
 Unrestricted access of object properties can cause
unintentional data corruption
program Main;
class rectangle;
int width, length, area, perimeter;
task print_area();
$display(“area = %0d\n”, area);
endtask
function new();
width = 0; length = 0; area = 0; perimeter = 0;
endfunction
endclass
initial begin
rectangle recObj = new();
recObj.width = 20; // directly set width
recObj.length = -5; // directly set length
recObj.area = recObj.width * recObj.length;
recObj.print_area(); // correct area value?
end
endprogram Are all class data correct?
7- 8

OOP Encapsulation 7-8


SVTB © 2006
Protect Against Unintentional Corruption

 Hide properties & methods via “local”:


 Object members are public by default
 “local” members of object can not be accessed directly
 Constructor new() can not be local
program Main;
class rectangle;
local int width, length, area, perimeter;
local task print_area(); …
function new(); …
endclass
initial begin
rectangle recObj = new();
recObj.width = 20; // Compile error!
recObj.length = 5; // Compile error!
recObj.print_area(); // Compile error!
end
endprogram How can “local” members be accessed?

7- 9

OOP Encapsulation 7-9


SVTB © 2006
Protect Against Data Corruption
 Create public class method to access local members
 Ensure data integrity within the method
program Main;
class rectangle;
local int width, length, area, perimeter;
function new(); …
function int set_width(int w);
if (w <= 0) begin Ensure integrity
set_width = 0; return; of subroutine call
Execute
end
functionality else set_width = 1;
width = w;
area = width * length;
if (length != 0) Ensure integrity
perimeter = 2 * (width + length); of object data
endfunction
endclass
initial begin
rectangle recObj = new();
if(!recObj.set_width(20)) $display(“[ERROR]”);
end
endprogram
7- 10

OOP Encapsulation 7-10


SVTB © 2006
Working with Objects – Handle Assignment

What happens when one object handle is assigned to


another?
Like any variable, the target takes on the value of the source.
class Packet; pkt1
int payload_size;
...
endclass pkt2
Memory

Packet pkt1 = new();
Packet pkt2 = new();
Memory

pkt1 = pkt2;
pkt1.payload_size = 5; // whose payload_size is set ?

What happens to the pkt1 object memory?

7- 11
See next slide for answer.

OOP Encapsulation 7-11


SVTB © 2006
Working with Objects – Garbage Collection
 VCS garbage collector reclaims memory automatically:
 When an object memory is no longer accessible
 And, the object has no scheduled event
 Object can be manually de-referenced pkt1 = null;

 Making an exact duplication of object memory:


class Packet;
int count;
...
endclass

Packet packet1 = new();
Packet packet1_copy; // handle only

packet1_copy = new packet1; // shallow copy
// deep copy not support in SVTB

7- 12
Every time a constructor task new() is called, new memory is allocated. The handle is removed
from the old memory and re-assigned to the new memory. If there are no events scheduled in the old
memory, the old object memory is reclaimed by the garbage collector.

OOP Encapsulation 7-12


SVTB © 2006
Working with Objects – Static Properties
 Static properties:
 Associated with the class, not the object
 Shared by all objects of that class
program router;
class Packet;
static int count = 0;
string str_var;
...
endclass
initial begin
Packet packet1 = new();
Packet packet2 = new();
...
packet1.count++;
packet2.count++;
...
$display(“Count: %0d”, packet1.count);
$display(“Count: %0d”, packet2.count);
end
endprogram What values get printed?
7- 13

OOP Encapsulation 7-13


SVTB © 2006
Best Practices (1/2)

 Methods can be placed outside of the class block:


 Inside class block, declare a extern prototype
 Outside class block, use a pair of colons :: to associate
the method with its class
 Double-colon is a scope/name resolution operator

class node; class node;


static int count = 0; static int count = 0;
string str; string str;
node next; node next;
... ...
task ping(); extern task ping(); // prototype
... endclass
endtask task node::ping();
endclass ...
endtask

Place class name and double-colons before method name


7- 14

OOP Encapsulation 7-14


SVTB © 2006
Best Practices (2/2)

 Useful methods for Data classes:


 display()
 Print object variables to console
 Helpful for debugging

 compare()
 Returns match, mismatch and other status base on results
of comparing object variables to variables of another object
 Simplifies self-check

 copy()
 Copy selected variables or nested objects
 Useful when exact duplication is not desirable

7- 15

OOP Encapsulation 7-15


SVTB © 2006
Unit Objectives Review

Having completed this unit, you should be able to:


 Raise level of abstraction by building data structure
with self-contained functionality:
 OOP encapsulation
 Protect integrity of data in OOP data structure:
 OOP data hiding
 Simplify data initialization process:
 OOP constructor

7- 16

OOP Encapsulation 7-16


SVTB © 2006
Appendix

SystemVerilog Virtual Interface

OOP Encapsulation 7-17


SVTB © 2006
Virtual Interfaces
Advanced
 Allow grouping of signals by function topic
 Create a handle to an interface
 Virtual interfaces can be passed via routine argument
 Promotes reuse by separating testbench from
implementation names
din1[15:0]
16x16
frame_n1[15:0] ROUTER
valid_n1[15:0]
router_1
16x16
ROUTER
din3[15:0]
16x16
frame_n3[15:0]
valid_n3[15:0]
router_3 ROUTER

16x16
ROUTER
reset_n
SystemClock

7- 18

OOP Encapsulation 7-18


SVTB © 2006
Virtual Interfaces

 STEP 1: Define a physical interface


 Similar to creating interface for just the single instance
 The difference is that common connections are removed
interface router_io(input logic clock);
// logic reset_n;
logic [15:0] din, frame_n, valid_n;
logic [15:0] dout, valido_n, frameo_n;
clocking cb @(posedge clock);
default input #1 output #1;
output din, frame_n, valid_n;
input dout, valido_n, frameo_n;
endclocking
modport TB(clocking cb);
// instead of modport TB(clocking cb, output reset_n);
endinterface

7- 19

OOP Encapsulation 7-19


SVTB © 2006
Virtual Interfaces
 STEP 2: Connect the interface
module router_test_top;
logic SystemClock;
logic reset_n;
router_io io_0(SystemClock);
router_io io_1(SystemClock); One interface
router_io io_2(SystemClock); per instance
router_io io_3(SystemClock);
router_test test(io_0, io_1, io_2, io_3, reset_n);
router dut(
.clock (SystemClock);
.reset_n (reset_n); Connect common
.din0 (io_0.din), signals separately
.frame_n0 (io_0.frame_n),
.valid_n0 (io_0.valid_n),
Connect unique signals with
...
.din1 (io_1.din), a specific interface object
.frame_n1 (io_1.frame_n),
.valid_n1 (io_1.valid_n),
...
);
endmodule
7- 20

OOP Encapsulation 7-20


SVTB © 2006
Virtual Interfaces
Requires –ntb_opts svp switch
 STEP 3: Pass virtual interface in via constructor
 STEP 4: Drive/Sample signals with virtual interface
 This class is now re-useable for any router instance
class DriverClass; Create virtual
string name;
virtual router_io.TB router; interface instance
...
function new(string name = "Driver",
virtual router_io.TB router);
this.name = name;
this.router = router; Pass virtual connections
endfunction via constructor argument
virtual task send_addrs();
router.cb.frame_n[sa] <= 1'b0;
for(int i=0; i<4; i++) begin
router.cb.din[sa] <= da[i];
@(router.cb);
end
endtask Drive/Sample signals
endclass using virtual interface
7- 21

OOP Encapsulation 7-21


SVTB © 2006
Virtual Interfaces
 STEP 5: Connect Virtual to physical
program automatic router_test(router_io.TB r0, r1, r2, r3
output logic reset_n);
class BFM_environment;
DriverClass driver[16];
function new(virtual router_io.TB router);
...
endfunction
endclass
BFM_environment bfm[4]; Connect Virtual to physical
initial begin
bfm[0] = new(r0);
bfm[1] = new(r1);
bfm[2] = new(r2);
bfm[3] = new(r3);
... module router_test_top;
logic SystemClock, reset_n;
end router_io io_0(…),io_1(…),io_2(…),io_3(…);
task reset(); router_test test(io_0, io_1, io_2, io_3, reset_n);
reset_n <= 1’b0; ...; router dut(...);
...
endtask endmodule
endprogram
7- 22

OOP Encapsulation 7-22


SVTB © 2006
Agenda

DAY
2
5 Concurrency

6 Inter-Process Communications

Object Oriented Programming (OOP)


7 – Encapsulation

Object Oriented Programming (OOP)


8 – Randomization

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 8- 1

OOP Randomization 8-1


SVTB © 2006
Unit Objectives

After completing this unit, you should be able to:


 Explain why randomization is needed in
verification
 Randomize variables
 Constrain randomization of variables

8- 2

OOP Randomization 8-2


SVTB © 2006
Why Randomization?

How long will simulation run if exhaustive testing of


a 32-bit adder is required?
Assume that one set of input and output can be verified
every 1ns.
A[31:0]
32 SUM[31:0]

B[31:0]
+ 32
32

A day?
A week?
A year?

8- 3
It will take over 500 years to verify this simple adder.

The point is that exhaustive simulation testing is impossible!

OOP Randomization 8-3


SVTB © 2006
Alternatives to Exhaustive Testing?

What is the goal of verification if exhaustive testing


is unachievable?
Answer:
Verify with sufficient set of vectors to gain a level of
confidence that product will ship with a tolerable field-
failure rate.

 The best known mechanism is randomization:


 Randomization of data

8- 4

OOP Randomization 8-4


SVTB © 2006
When Do We Apply Randomization?
Broadly Narrowly
Constrained Constrained
Randomization Randomization
Trivial Broad-Spectrum Corner-case
Directed* Verification Verification Verification

Goal
% Coverage

Difficult to reach
Corner-case
Verification

Directed*
Time

Build verification
environment

8- 5

OOP Randomization 8-5


SVTB © 2006
OOP Based Randomization

 Two types of random properties are supported:


 rand
 randc

 rand and randc properties are randomized when the


class method randomize() is called:
 Randomize property value to full range of data type
 randomize() is built-in with every class

 1 is returned if successful, 0 if randomization failed

 rand properties can assume any legal value:


 Values can repeat without exhausting all possible values
 randc properties can be up to 16 bits:
 Exhaust all values before repeating any individual value
 For non-repeating bit values > 16 bits, use concatenation

8- 6

OOP Randomization 8-6


SVTB © 2006
Randomization Example
program automatic router_test;
class Packet;
randc bit[3:0] sa, da; Declare random
rand bit[7:0] payload[]; properties in class
endclass
Packet randomized_obj = new(); Create an object to
mailbox out_box = new(); be randomized
int run_for_n_packets = 2000;
initial begin
reset();
gen();
...
end
Randomize content
task gen(); of object
Packet pkt;
for (int i=0; i<run_for_n_packets; i++) begin
if (!randomized_obj.randomize()) $display(“ERROR”);
pkt = new randomized_obj;
out_box.put(pkt);
... What would happen with:
end Pass copy of randomized out_box.put(randomized_obj);
endprogram object to next transactor
8- 7

OOP Randomization 8-7


SVTB © 2006
Issues with Randomization
 How do you control
 The value range for sa and da?
 The size of payload[]?
program automatic router_test;
class Packet;
rand bit[3:0] sa, da;
rand bit[7:0] payload[];
function void display();
$display(“sa = %0d, da = %0d”, sa, da);
$display(“size of payload array = %0d”, payload.size());
foreach(payload[i])
$display(“payload[%0d] = %0d”, i, payload[i]);
endclass
initial begin
Packet pkt = new();
pkt.randomize();
pkt.display(); What does pkt.display() show
end for sa, da and payload.size()?
endprogram
What if sa, da are int type?
rand int sa, da;
8- 8
Since sa and da are unsigned four bit type, the sa and da values will be in { 0:15 }.

Because memory for payload array is not allocated, the size of payload array will always be 0.

If sa and da were to be changed to int type, then the full range of integer values will be possible.
This means that there is a 50% chance for sa and da values to be negative numbers.

OOP Randomization 8-8


SVTB © 2006
Distributed Constraints (1/2)
 Class properties are constrained in a constrain block
 Use operator or distribution specification
 Arrays can be constraint with aggregates like size()
 For distribution specification:
 Distributed over a specified range with keyword inside:
constraint Limit1 {
sa inside { [5:7], 10, 15 } ;
// 5,6,7,10,15 equally weighted probability
payload.size() >= 2;
payload.size() <= 4;
}

 Excluded from a specified range with !:


constraint Limit2 {
!( sa inside { [1:10], 15 } );
// not 1 through 10 or 15
!( payload.size() inside { [100:200] } );
}
8- 9

OOP Randomization 8-9


SVTB © 2006
Distributed Constraints (2/2)

 Constraint values can also be weighted over a


specified range using keyword dist and:
 := (apply the same weight to all values in range)
 :/ (divide the weight among all values in range)
constraint Limit { constraint Limit {
sa dist {[5:7]:=10, 9:=20}; da dist {[5:7]:/60, 9:=40};
} }
// 5 = weight 10 // 5 = weight 20
// 6 = weight 10 // 6 = weight 20
// 7 = weight 10 // 7 = weight 20
// 9 = weight 20 // 9 = weight 40

equal weights divided weights

8- 10

OOP Randomization 8-10


SVTB © 2006
Array Constraint Support
 Members can be constrained within foreach loop
 Aggregates can be used to constraint array
 size(), sum() and more (see release notes)
 Set membership can be used to reference content
class rectangle;
rand byte array[10];
rand bit drivers_in_use[16];
rand int num_of_drivers, one_element_of_array;
constraint limit {
num_of_drivers inside { [1:16] };
drivers_in_use.sum() == num_of_drivers;
foreach(array[i])
(i >= 3) -> array[i] == i;
one_element_of_array inside array;
}
endclass Requires –ntb_opts new_constraints switch
8- 11

OOP Randomization 8-11


SVTB © 2006
Implication and Order Constraints
 Implication operators:
 ->
 if ( … ) … [ else … ]
 Bidirectional implication
 One side being true implies the other side is true.
typedef enum { low, mid, high } AddrType;
class MyBus;
rand bit[7:0] addr;
rand AddrType atype;
constraint addr_range {
(atype == low ) -> addr inside { [0:15] };
(atype == mid ) -> addr inside { [16:127] };
(atype == high) -> addr inside { [128:255] };
// same as:
// if (atype == low) addr inside { [0:15] };
// if (atype == mid) addr inside { [16:127] };
// if (atype == high) addr inside { [128:255] };
}
endclass
8- 12

OOP Randomization 8-12


SVTB © 2006
Constraint Solver Order

 randc properties are solved before rand properties


 Can not constraint randc properties with rand property
 Use solve – before construct to set solving order
 Can not be used to force rand property to be solved
before randc properties
class MyBus;
rand bit flag;
rand int addr;
constraint addr_range {
if ( flag == 0 ) addr == 0;
else addr inside { [1:1024] };
solve flag before addr;
// solve addr before flag; // what’s the difference?
}
endclass

8- 13

OOP Randomization 8-13


SVTB © 2006
Can randomize() Fail?
class demo;
What if high equals 0? byte high = 9;
rand int x;
constraint Limit
{ x > 0; x <= high; }
task new();
int status;
randomize() produces status = randomize();
endtask
this simulation warning: endclass
Solver failed when solving following set of constraints
integer high = 0;
rand integer x; // rand_mode = ON
constraint Limit // (constraint_mode = ON)
{
( x > 0 ) ;
( x < high ) ;
}
Constraint solver failed - Constraints are inconsistent
and cannot be solved.

and returns a status value of 0.


8- 14

OOP Randomization 8-14


SVTB © 2006
VCS Will Find Value if Solution Exist

 Constraint limits can be random variables:


class demo;
rand byte high;
rand int x;
constraint Limit {
x > 0;
x <= high;
}
endclass

What random values are generated for high?


randomize() will eliminate values <= 0 from possible
values for high.
If there is no legal value for high, then randomize()
prints warning and returns a 0. (variables left unchanged)

8- 15

OOP Randomization 8-15


SVTB © 2006
Effects of Calling randomize()

 When randomize() executes, three events occur:


 pre_randomize() is called class Packet;
rand bit[3:0] sa, da;
 Randomization is executed rand bit[7:0] payload[];
bit[15:0] crc;
 post_randomize() is called
constraint LimitA {
 pre_randomize() sa inside { [0:7] };
da inside { [0:7] };
 Optional payload.size() inside { [2:4] };
}
 Set/Correct constraints
before randomization function void pre_randomize();
payload.delete();
 post_randomize() endfunction

 Optional function void post_randomize();


gen_crc();
 Make corrections endfunction
after randomization endclass
 Example: CRC
8- 16

OOP Randomization 8-16


SVTB © 2006
Applying pre_randomize()
 Use pre_randomize() to:
 Set/Correct constraints before randomization
 Reset effects of prior randomizations
program automatic router_test;
class Packet;
rand bit[3:0] sa, da;
rand bit[7:0] payload[];
constraint LimitA { payload.size() inside {[2:10]}; }
function void pre_randomize();
payload.delete(); What will $display() show
endfunction after a few iteration of
endclass
initial begin
randomization if
int status payload.delete() is not
Packet pkt = new(); executed?
for(int i=0; i<10; i++)
if(!pkt.randomize())
$finish;
else $display(“Size of payload = %0d”, pkt.payload.size());
end
endprogram
8- 17
The randomize() method can allocate new memory if the existing memory size of the array is
insufficient to accommodate the randomized payload.size() values. However, if the existing memory
of the array is large enough to accommodate the randomized payload.size() value, then the existing
memory will be used. The effect is as illustrated below:

Let’s assume that the first randomization of the pkt object above resulted in picking payload.size() to
be 5. Since, in the beginning there are no memory already allocated for pkt.payload, therefore
randomize() will allocate payload array to payload = new[5] and populate all five indices with
random value.

For the second randomization, let’s assume that payload.size() is picked to be 7. Since the existing
memory size is insufficient, randomize() will allocate payload array to payload = new[7] (payload)
and populate all seven indices with random value.

For the third randomization, let’s assume that payload.size() is picked to be 3. Since there is
sufficient memory, randomize() will simply randomize the contents of indices 0 through 2. If you
were to display the size of the payload array at this point, the payload.size() will be 7 NOT 3. For
many applications, this will lead to errors.

To prevent this behavior from becoming a problem, you should de-allocate the payload array before
randomization. The proper place to do this is in the pre_randomize() method.

OOP Randomization 8-17


SVTB © 2006
Applying post_randomize()
 Use post_randomize() to:
 Make necessary corrections after randomization
 Print debug messages
program automatic router_test;
class Packet; Does it make sense to
rand bit[3:0] sa, da;
rand bit[7:0] payload[]; randomize crc?
bit[15:0] crc; rand bit[15:0] crc;
constraint LimitA { … }
function void pre_randomize(); … endfunction
function void post_randomize();
crc = gen_crc();
endfunction
endclass
initial begin
int status
Packet pkt1 = new();
status = pkt1.randomize();
...
end
endprogram
8- 18
It does not make sense to randomize crc of a packet. However, if crc is left undefined after
randomize() method completes, the Packet object now contains invalid information. The simple way
around this is to update all dependent variables (like crc) in post_randomize() method.

OOP Randomization 8-18


SVTB © 2006
Inline Constraints

 Individual invocations of randomize() can be


customized
 syntax: obj.randomize( ) with { <new constraints> };
program automatic test;
class demo;
local rand int x, y, z;
constraint Limit1 { x > 0; x <= 5; }
...
endclass
initial begin
int status;
demo obj_a = new();
status = obj_a.randomize() with { x > 3 && x < 10; };
...
end
endprogram

8- 19
Sometime, the constraint defined within the object being randomized is insufficient to get the desired
result. The with { … } construct allows one to solve this problem without the need to go back and
modify the original definition of the class. The constraints specified with the with { … } construct is
added to the constraints already defined in the original class definition.

For this construct to work effectively, the constraints defined within the original class definition
should be as broad as possible within the limits of the DUT spec.

OOP Randomization 8-19


SVTB © 2006
Controlling rand Property Randomization
 Turning randomization for properties on or off with:
task/function int object_name.property.rand_mode ( 0 | 1 );

1 - enable constraint (default )


0 - disable constraint
When called as function return state of constraint (0 or 1)
program automatic test;
class Node;
rand int x, y, z;
constraint Limit1 {
x inside {[0:16]}; y inside {[23:41]};
z < y; z > x;
}
endclass
initial begin
Node obj1 = new();
obj1.x.rand_mode(0);
if (!obj1.randomize()) ...;
end
endprogram
8- 20

OOP Randomization 8-20


SVTB © 2006
Selective Randomization of Properties

 Randomize selected properties in class by


embedding properties in randomize() argument
 The arguments designate the complete set of random
variables within that object to be randomized
 All other variables in the object are considered state
variables and not randomized
class CA;
rand byte x, y;
byte v, w;
constraint c1 { x < v && y > w );
endclass

CA a = new();
a.randomize(); // random variables: x, y state variables: v, w
a.randomize( x ); // random variables: x state variables: y, v, w
a.randomize( v, w ); // random variables: v, w state variables: x, y
a.randomize( w, x ); // random variables: w, x state variables: y, v
8- 21

OOP Randomization 8-21


SVTB © 2006
Controlling Constraint at Runtime

 Control constraints blocks with:


task/function int object_name.constraint_block_name.constraint_mode ( 0 | 1 );

0 - enable constraint (default )


1 - disable constraint
When called as function return state of constraint (0 or 1)
program automatic test;
class demo;
local rand int x, y, z;
constraint Limit1 { x > 0; x <= 16; }
static constraint Limit2 { x > 3; x <= 32; }
endclass
initial begin
demo obj_a = new();
obj_a.Limit1.constraint_mode(0);
if (!obj_a.randomize()) ...;
end
endprogram

8- 22
If a constraint block is declared as static, then calls to constraint_mode() shall affect all instances of
the specified constraint in all objects. Thus, if a static constraint is set to OFF, it is off for all
instances of that particular class.

OOP Randomization 8-22


SVTB © 2006
Nested Objects with Random Variables

randomize( ) will follow a linked list of object handles,


randomizing each linked object to the end of the list.
program automatic test;
class Node;
rand int x, y, z;
constraint Limit1 { x >= 0; x <= 16; }
rand Node next;
Node previous;
...
endclass
initial begin
Node pkt1 = new();
Node pkt2 = new();
...
pkt1.next = pkt2;
...
status = pkt1.randomize( );
end
endprogram This will randomize objects pkt1 and pkt2

8- 23

OOP Randomization 8-23


SVTB © 2006
Lab 3 Introduction

Encapsulate data
in Packet Class

90 min
configure Encapsulate data
in Packet Class
gen() Packet object

send() Self Check recv() Compile & Simulate

Driver Monitor

DUT

8- 24

OOP Randomization 8-24


SVTB © 2006
Unit Objectives Review

Having completed this unit, you should be able to:


 Explain why randomization is needed in verification
 Randomize variables
 Constrain randomization of variables

8- 25

OOP Randomization 8-25


SVTB © 2006
This page was intentionally left blank.

OOP Randomization 8-26


SVTB © 2006
Agenda

DAY
3 Object Oriented Programming (OOP)
9 – Inheritance

10 Functional Coverage

11 SystemVerilog RVM (VMM) Overview

CS Customer Support

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 9- 1

OOP Inheritance 9-1


© 2006
SVTB
Unit Objectives

After completing this unit, you should be able to:


 Create OOP extended classes
 Access class members in inheritance hierarchy

9- 2

OOP Inheritance 9-2


© 2006
SVTB
Object Oriented Programming: Inheritance

 Object-oriented programming
packet
 New classes derived from original (base) class
 Inherits all contents of base class
class MyPacket extends Packet; my_packet

DA task display();
SA UML
...
DATA endtask
Packet CRC
function bit[31:0] compute_crc();
...
endfunction
Can override
MyPacket methods
in base class
is_good function bit[31:0] compute_crc()
crc = super.compute_crc();
if (!is_good) crc = $random;
endfunction
Can call overridden
behavior

9- 3

OOP Inheritance 9-3


© 2006
SVTB
Object Oriented Programming: Inheritance

 Derived classes compatible with base class


 Can reuse code
Base class
Packet pkt = ...;
transmit(pkt); Packet

MyPacket my_pkt = ...; Compatible


Use
transmit(my_pkt); $cast()

MyPacket
Compatible Derived class

OK pkt = my_pkt;
task transmit(Packet pkt);
...
Error my_pkt = pkt;
endtask

OK $cast(my_pkt, pkt);

9- 4

OOP Inheritance 9-4


© 2006
SVTB
OOP: Polymorphism

 Which method gets called?


p
MyPacket extends Packet

DA
function bit[31:0] compute_crc();
SA ...
DATA endfunction
CRC

is_good function bit[31:0] compute_crc();


...
endfunction

Packet p1 = new();
MyPacket p2 = new();
function bit[31:0] crc(Packet pkt);
p1.crc = p1.compute_crc();
crc = pkt.compute_crc();
P2.crc = p2.compute_crc();
endfunction
p1.crc = crc(p1);
p2.crc = crc(p2);

9- 5

OOP Inheritance 9-5


© 2006
SVTB
OOP: Polymorphism

 If compute_crc() is virtual
p
my_packet extends packet

DA
virtual
SA function bit[31:0] compute_crc();
DATA ...
CRC endfunction

is_good virtual
function bit[31:0] compute_crc();
...
endfunction

Packet p1 = new();
MyPacket p2 = new();
function bit[31:0] crc(Packet pkt);
p1.crc = p1.compute_crc();
crc = pkt.compute_crc();
P2.crc = p2.compute_crc();
endfunction
p1.crc = crc(p1);
p2.crc = crc(p2);

9- 6

OOP Inheritance 9-6


© 2006
SVTB
Data Protection: Local

 Local members of a base class are not accessible


in the derived class
MyPacket extends Packet

local int DONE;

DA task display();
SA ...
DATA endtask
Packet CRC
function bit[31:0] compute_crc();
...
MyPacket endfunction

Good/Bad function bit[31:0] compute_crc();


crc = super.compute_crc();
if (!is_good) crc = $random;
DONE = 1’b1;
endfunction Error

9- 7

OOP Inheritance 9-7


© 2006
SVTB
Data Protection: Protected

 Protected members of a base class are accessible


in the derived class, but not to external code
MyPacket extends Packet

protected int DONE;

DA task display();
SA ...
DATA endtask
Packet CRC
function bit[31:0] compute_crc();
...
MyPacket endfunction

Good/Bad function bit[31:0] compute_crc();


crc = super.compute_crc();
if (!is_good) crc = $random();
DONE = 1’b1;
endfunction Good

9- 8

OOP Inheritance 9-8


© 2006
SVTB
Test For Understanding
 Will the following code compile?
 Which one of the task new() is executed?
class A;
protected int a;
function int get_a(); begin get_a = a; endfunction
function new(int b); begin a = b; endfunction
endclass
class B extends A;
int b = 1000;
task print_a(); begin $display("a is %d", get_a()); endtask
endclass
class C extends B;
int a;
function new(int c); begin a = c; endfunction
endclass
program test;
C test_c = new();
test_c.print_a();
endprogram

9- 9

OOP Inheritance 9-9


© 2006
SVTB
Test For Understanding: Answer
 VCS will attempt to execute every task new()
 If task new is not defined, VCS inserts one:
function new(); begin super.new(); endfunction
 Resulting in syntax error:

class A;
protected int a;
function int get_a(); begin get_a = a; endfunction
function new(int b) begin a = b; endfunction
endclass
class B extends A; Mismatching argument list
int b = 1000;
task print_a(); begin $display("a is %d", get_a()); endtask
function new(); begin super.new(); endfunction
endclass
class C extends B;
int a;
function new(int c); begin super.new(); a = c; endfunction
endclass ...

9- 10

OOP Inheritance 9-10


© 2006
SVTB
Test For Understanding: Solution
 Always call super.new() as the first statement in
constructor
 If super.new() is called anywhere except as the first
statement, a syntax error will also result
 In the super.new() call, provide the correct argument set
class A;
protected int a;
function int get_a(); begin get_a = a; endfunction
function new(int b); begin a = b; endfunction
endclass
class B extends A;
int b = 1000;
task print_a(); begin $display("a is %d", get_a()); endtask
function new(int a); begin super.new(a); endfunction
endclass
class C extends B;
int a;
function new(int c); begin super.new(c); a = c; endfunction
endclass ...

9- 11

OOP Inheritance 9-11


© 2006
SVTB
Unit Objectives Review

Having completed this unit, you should be able to:


 Create OOP extended classes
 Access class members in inheritance hierarchy

9- 12

OOP Inheritance 9-12


© 2006
SVTB
Agenda

DAY
3 Object Oriented Programming (OOP)
9 – Inheritance

10 Functional Coverage

11 SystemVerilog RVM (VMM) Overview

CS Customer Support

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 10- 1

Functional Coverage 10-1


© 2006
SVTB
Unit Objectives

After completing this unit, you should be able to:


 Define functional coverage structures
 Specify the coverage sample mechanisms
 Define signals and variables to be sampled
 Specify the expected values that indicate
functionality
 Utilize parameterization to make coverage instances
unique
 Use coverage attributes to customize individual
coverage structures
 Measure coverage dynamically

10- 2

Functional Coverage 10-2


© 2006
SVTB
Phases of Verification
 How do you know
 When verification goal has been reached?
 When to switch to corner-case Verification?
 When to write directed tests for difficult to reach corner-
case Verification?
Broad-Spectrum Corner-case
Verification Verification
Goal
% Coverage

Preliminary
Verification Difficult to reach
Corner-case
Verification

Time
Build verification
environment
10- 3
The process of reaching the verification goal starts with the definition of the verification goal.
What does it mean to be done with testing? Typically, the answer lie in the functional coverage
spec within a verification plan. The goal is then to reach 100% coverage of the defined functional
coverage spec in the verification plan.
Once the goal has been defined, the first step in constructing the testbench is to build the
verification environment.
To verify the the environment is set up correctly, preliminary verification tests are usually
executed to wring out the preliminary RTL and testbench errors.
When the testbench environment is deemed to be stable, broad-spectrum verification based on
random stimulus generation is utilized to quickly detect and correct the majority of the bugs in
both RTL code and testbench code.
Based on functional coverage analysis, the random-based tests are then constrained to focus on
corner-cases not yet reached via broad-spectrum testing.
Finally, for the very difficult to reach corner cases, customized directed tests are used to bring the
coverage up to 100%.
Verification is complete when you reach 100% coverage as defined in the verification plan.

Functional Coverage 10-3


© 2006
SVTB
The Testbench Environment/Architecture

 Implement functional coverage to answer these


questions

Configure Are we there yet?

Generator Coverage

Transactor Self Check Transactor

Driver Monitor

DUT

10- 4

Functional Coverage 10-4


© 2006
SVTB
Combinational Logic Example

Goal: Check all combinations of input and output patterns

In[1] In[0] Out[3] Out[2] Out[1] Out[0]

0 0 0 0 0 1 O u t[ 0 ]

0 1 0 0 1 0 In [0 ] 2 to 4 O u t[ 1 ]

In [1 ] D ecod er O u t[ 2 ]
1 0 0 1 0 0
O u t[ 3 ]
1 1 1 0 0 0

 Create state coverage bins to track input & output bit


patterns
 Define sample timing for coverage bins
 Track state coverage bin results

10- 5

Functional Coverage 10-5


© 2006
SVTB
State Transition Example

Goal: Check temporal state transitions


RESET

S1

1
0

1
S4 S2 1

1 0
S3

 Create state coverage bins to monitor states


 Create transition coverage bins to monitor state transitions
S1 ⇒ S2 ⇒ S3 ⇒ S1 ⇒ S4 ⇒ S2 ⇒ S2 ⇒ S3 ⇒ S1

 Define sample timing for coverage bins


 Track transition coverage bin results
10- 6

Functional Coverage 10-6


© 2006
SVTB
Cross Correlation Example

Goal: Check all input ports have driven all output ports

Input port Output port Router

0 0
0 1
0 2
… …
15 14
15 15

 Create cross coverage bins to correlate activities of


input ports with respect to output ports
 Define sample timing for coverage bins
 Track cross coverage bin results

10- 7

Functional Coverage 10-7


© 2006
SVTB
Functional Coverage in SystemVerilog

 Create a coverage group which encapsulates:


 Coverage bins definitions
 State
 Transition

 Cross correlation

 Coverage bins sample timing definition


 Coverage attributes
 Example: coverage goal
 Instantiate coverage object(s) from coverage group
 Query coverage object to determine progress of
verification
 Scope of variable visibility is same as subroutines

10- 8

Functional Coverage 10-8


© 2006
SVTB
Functional Coverage Example

Create coverage group

covergroup fcov(bit[3:0] sa, bit[3:0] da, event port_event) @(port_event);


coverpoint sa { bins input_ports[] = { [0:15] }; }
coverpoint da { bins output_ports[] = { [0:15] }; }
cross sa, da;
option.goal = 100;
endgroup Instantiate and construct
program router_test; coverage object
byte sa, da;
event port_event;
fcov port_fc = new(sa, da, port_event);
...
while (!($get_coverage() == 100)) begin
...
sa = pkt_ref.sa; Query coverage result
da = pkt_ref.da;
->port_event;
// port_fc.sample(); // alternative form of updating of bins
end
...
endprogram

10- 9
The covergroup can also be embedded inside a class. The advantage of creating the covergroup
inside the class definition is that the covergroup automatically has access to all properties of the
class without having an I/O argument. The down side is that, this covergroup can not be re-used.
class Scoreboard;
Packet pkt2send, pkt2cmp;
bit[3:0] sa, da;
covergroup router_cov;
coverpoint sa;
coverpoint da;
cross sa, da;
option.goal = 100;
endgroup
function new(...);
router_cov = new(); // still need to be constructed
endfunction
task check();
...
if (pkt2send.compare(pkt2cmp, message)) begin
sa = pkt2send.sa;
da = pkt2send.da;
router_cov.sample();
coverage_result = $get_coverage();
if ((coverage_result == 100) || (...)
->DONE;
end
endtask
endclass

Functional Coverage 10-9


© 2006
SVTB
State Bin Creation (Automatic)

 SystemVerilog automatically creates state bins

covergroup cov1 @(posedge router.clock);


coverpoint sa;
coverpoint da;
port_comp: coverpoint (sa > da);
port_comb: coverpoint {sa, da} {
option.auto_bin_max = 256;
}
endgroup

 Bin name is “auto[value_range]”


 The value_range are the value range which triggered that bin

 By default, VCS create 64 bins. Values are equally distributed


in each bin
 Can be controlled using the auto_bin_max attribute

 Bins are allocated with equal number of states


10- 10

Functional Coverage 10-10


© 2006
SVTB
Measuring Coverage

Without auto binning:


 Coverage is:

# of bins covered (have at_least hits)


# of total bins

With auto binning:


auto_bin_max limit the number of bins used in the
coverage calculation
 Coverage is:
# of bins covered (have at_least hits)
min( possible values for data type | auto_bin_max)

10- 11

Functional Coverage 10-11


© 2006
SVTB
Automatic State Bin Creation Example
bit[3:0] x, y;
covergroup cov1 @(router.cb);
coverpoint x;
coverpoint y;
option.auto_bin_max = 2; // maximum of 2 auto-created bins
endgroup
… Var Bin #Hit
cov1 = new(); x auto[0:7] 1
x = 1;
y = 8; y auto[8:f] 1

@(router.cb);
(50% covered)
$display(“%0d covered”, $get_coverage());
x = 9; Var bin #Hit Var bin #Hit
y = 9; auto[0:7] 1 auto[0:7] 2
@(router.cb); x x
auto[8:f] 1 auto[8:f] 1

x = 3; (75% covered)
y auto[8:f] 2 auto[0:7] 1
y = 5; y
@(router.cb); auto[8:f] 2

(100% covered)
$display(“%0d covered”, $get_coverage());
10- 12

Functional Coverage 10-12


© 2006
SVTB
State and Transition Bin Creation (User)

 Define state bins using ranges of values


 Define transition bins using state transitions
covergroup MyCov() @(cov_event);
coverpoint port_number {
bins s0 = { [0:7] }; // creates one state bin
bins s1[] = { [8:15] }; // creates 8 state bins
// s1_0 through s1_f
ignore_bins ignore = { 16, 20 }; // ignore if hit
illegal_bins bad = default; // terminates simulation if hit
// default refers to undefined values
bins t0 = ([0:7], 9 => [8:15] => 0); // creates one transition bin
bins t1[] = (8, [0:7] => [8:15]); // creates 72 transition bins
bins other_trans = default sequence; // all other transitions
// illegal_bins bad_trans = default sequence; // terminates simulation
}
endgroup

10- 13

Functional Coverage 10-13


© 2006
SVTB
Cross Coverage Bin Creation (Automatic)

 VCS automatically creates cross coverage bins


covergroup cov1 @(posedge router.cb);
coverpoint sa;
coverpoint da;
cross sa, da {
option.cross_auto_bin_max = 256;
}
endgroup

 Cross bins are create automatically as each set of


unique cross values is seen
 Can be controlled with cross_auto_bin_max
 defaults to all possible combinations

10- 14

Functional Coverage 10-14


© 2006
SVTB
Specifying Sample Event Timing

covergroup definition_name [(argument_list)] [@(sample_event)];


coverpoint coverage_point { ... }
}

 Define sample_event in coverage_group


 Valid sample_event_definition:
 @([specified_edge] signals | variables)
 Bins are updated asynchronously as the
sample_event occurs
 Can also use cov_object.sample() to update the bins
 Can be made to update bins at end of simulation time
slot by setting option.strobe = 1 in covergroup

10- 15

Functional Coverage 10-15


© 2006
SVTB
Determining Coverage Progress

 $get_coverage() returns testbench coverage percentage


as a real value
covergroup cov1(int x, int y) @(posedge router.cb);
mode1: coverpoint x {
bins S_1[] = { [34:78], [1:27] };
}
endgroup
program Main;
int a;
real cov_percent;
cov1 c_obj1 = new(a, b);
while (1) begin
cov_percent = $get_coverage();
$display(“%0d covered\n”, cov_percent);
...
end
endprogram

10- 16

Functional Coverage 10-16


© 2006
SVTB
Coverage Measurement Example

 Each covergroup contributes equally


 Within covergroup, each coverpoint/cross block
contributes equally
For the coverpoint definition in Group 2,
 Attributes change
If there are 10 bins with the default weight of 1,
contributions when 6 bins have at_least hits, the definition’s
contribution to the covergroup is:
.33 x .6 x 1 = .198
Cover Group 1 Cover Group 2 If the cross definitions set weight to 0, they
contribute zero, Group 2 will contribute:
coverpoint .33 (.198 + 0 + 0) x .5 = .1
.5 coverpoint to the total coverage.
cross .33

.5 coverpoint Group 1 % x 0.5 + Cover Group 2


cross .33 Group 2 % x 0.5 =
Coverage Percent sample % x .33 +
cross % x .33 +
cross % x .33 =
group coverage %

10- 17

Functional Coverage 10-17


© 2006
SVTB
Coverage Attributes

 Coverage attributes are defined for entire coverage groups or for


individual sample definitions
 Attributes at the coverage group level are overridden at the sample
and cross level
 Attributes may be different for each instance of a coverage object
by passing arguments

covergroup cov1(int var1) @(cov_event);


option.auto_bin_max = var1; // entire group

coverpoint x {
option.auto_bin_max = 4; // just for x
bins lower = { [1:8] };
...
endgroup

10- 18

Functional Coverage 10-18


© 2006
SVTB
Major Coverage Options (1/2)

 at_least (1):
 Minimum number of times for a bin to be hit to be
considered covered
 auto_bin_max (64):
 Maximum number of bins that can be created
automatically
 Each bin contains equal number of values
 goal (90):
 Percentage as an integer for a coverage group,
cross, or sample to be considered covered
 weight (1):
 Multiplier for coverage bins

10- 19

Functional Coverage 10-19


© 2006
SVTB
Major Coverage Options (2/2)

 cross_auto_bin_max (231-1):
 Maximum number of bins that can be created
automatically
 Beyond this number, hits are dropped

 per_instance (0):
 Specifies whether to collect coverage statistics
cumulatively or per instance for a coverage group

10- 20

Functional Coverage 10-20


© 2006
SVTB
Coverage Result Reporting Utilities

 VCS writes coverage data to a binary database file


 The database file is named <program_name>. db
 Convert to HTML:
ntbCovReport –cov_report <file|directory>
 Convert to Text:
ntbCovReport –cov_text_report <file|directory>
 If file, generate report for the single coverage database file
 If directory, then the data in all coverage database files in
that directory are merged and reported

10- 21

Functional Coverage 10-21


© 2006
SVTB
Sample HTML Report

10- 22

Functional Coverage 10-22


© 2006
SVTB
Lab 6 Introduction

Implement Functional Coverage

configure
30 min Functional
build()
Coverage
Implement
reset()
functional coverage

gen() coverage

sendClass check() recvClass


Compile & Simulate
Driver Monitor

DUT

Stop simulation
if coverage goal is met

10- 23

Functional Coverage 10-23


© 2006
SVTB
Unit Objectives Review

Having completed this unit, you should be able to:


 Define functional coverage structures
 Specify the coverage sample mechanisms
 Define signals and variables to be sampled
 Specify the expected values that indicate functionality
 Utilize parameterization to make coverage instances
unique
 Use coverage attributes to customize individual coverage
structures
 Measure coverage dynamically

10- 24

Functional Coverage 10-24


© 2006
SVTB
Agenda

DAY
3 Object Oriented Programming (OOP)
9 – Inheritance

10 Functional Coverage

11 SystemVerilog RVM (VMM) Overview

CS Customer Support

Synopsys 50-I-052-SSG-001 © 2006 Synopsys, Inc. All Rights Reserved 11- 1

RVM-SV (VMM) Overview 11-1


© 2006
SVTB
Unit Objectives

After completing this unit, you should be able to:


 Describe the RVM-SV testbench architecture
 Describe the RVM-SV environment execution
sequence
 Describe the RVM-SV testcase development
Methodology

11- 2

RVM-SV (VMM) Overview 11-2


© 2006
SVTB
Coverage-Driven Verification

Phases of random stimulus based verification


Preliminary Broad-Spectrum Corner-case
Verification Verification Verification

Goal
% Coverage

Difficult to reach
Corner-case
Verification

Time

Build verification
environment

11- 3
The process of reaching the verification goal starts with the definition of the verification goal.
What does it mean to be done with testing? Typically, the answer lie in the functional coverage spec
within a verification plan. The goal is then to reach 100% coverage of the defined functional
coverage spec in the verification plan.
Once the goal has been defined, the first step in constructing the testbench is to build the verification
environment.
To verify the the environment is set up correctly, preliminary verification tests are usually executed
to wring out the preliminary RTL and testbench errors.
When the testbench environment is deemed to be stable, broad-spectrum verification based on
random stimulus generation is utilized to quickly detect and correct the majority of the bugs in both
RTL code and testbench code.
Based on functional coverage analysis, the random-based tests are then constrained to focus on
corner-cases not yet reached via broad-spectrum testing.
Finally, for the very difficult to reach corner cases, customized directed tests are used to bring the
coverage up to 100%.
Verification is complete when you reach 100% coverage as defined in the verification plan.

RVM-SV (VMM) Overview 11-3


© 2006
SVTB
The Testbench Environment/Architecture

Testcase Configures testbench and DUT

Creates Checks Checks


Configure
random completeness correctness
transactions
Generator Coverage Identifies
transactions
Executes
transactions Testbench
Transactor Self Check Transactor

Drive DUT
Driver Observes data Monitor
from DUT

Interfaces DUT RTL

11- 4

RVM-SV (VMM) Overview 11-4


© 2006
SVTB
Testbench Considerations: Abstraction

Create individual
Test Cases Testcase

Creates Configure
Test Scenarios

Generator Coverage

Transactors
Transactor Self Check Transactor

Device Drivers
Driver Monitor
and Monitors

Signals
(interface) DUT

11- 5

RVM-SV (VMM) Overview 11-5


© 2006
SVTB
Testbench Considerations: Re-Use
 Encapsulate testbench components in OOP Class
Goal
Test
Testcase program;

% Coverage
Generator Coverage Configure
Time

Transactor Self Check Transactor Environment


Class

Driver Monitor

DUT

11- 6

RVM-SV (VMM) Overview 11-6


© 2006
SVTB
What Does RVM-SV Provide?

 Philosophy
Base Classes
 One environment many tests
Coding Guidelines

 Coverage-driven
 Modeling Approach  Coding Standards
 Transactions  Data & Transactions
 Variant Data  Transactors
 Transactor Control  Verification Environments
 Transactor Interfacing
 Simulation Control  Building Blocks
 Transaction Interface
Class Library
 Message Service
 Event Notification

11- 7

RVM-SV (VMM) Overview 11-7


© 2006
SVTB
RVM-SV Base Classes and Macros

Provided in the vmm.sv library file:


 Base classes:  Macros:
 vmm_env  `vmm_channel
 vmm_data  `vmm_atomic_gen
 vmm_xactor  `vmm_scenario_gen
 `vmm_callback
 Class libraries:
 `vmm_fatal
 vmm_log
 `vmm_error
 vmm_notify
 `vmm_warning
 vmm_broadcast
 `vmm_note
 vmm_scheduler
 `vmm_trace
 `vmm_debug
 `vmm_verbose
11- 8

RVM-SV (VMM) Overview 11-8


© 2006
SVTB
RVM Guiding Principles

 Top-down implementation methodology


 Emphasizes “Coverage Driven Verification”
 Maximize design quality
 More testcases
 More checks Constrainable Many runs,
different seeds
 Less code Random Generation

 Approaches Directed
 Reuse Add Testcase Functional
constraints Coverage
 Across tests
 Across blocks Minimal Code Identify
Modifications holes
 Across systems

 Across projects
 One verification environment, many tests
 Minimize test-specific code
11- 9

RVM-SV (VMM) Overview 11-9


© 2006
SVTB
Implementing RVM Testbench

 Need a class to encapsulate verification environment


 Reused by all tests
vmm_env
 Instantiates env.run(); program;
 Generators
gen_cfg();
 Transactors Configuration
build();
 Scoreboard reset_dut();
 Coverage model cfg_dut();
Generator Coverage

 Signal Interfaces start();

wait_for_end();
 Controls stop();
Transactor Self Check Transactor

 Configuration cleanup();
Driver Monitor
 Start of simulation report();

 End of simulation
DUT
 Pass/Fail report
11- 10

RVM-SV (VMM) Overview 11-10


© 2006
SVTB
Environment Execution Flow
Randomize test
 Conceptually... class dut_env extends vmm_env;
virtual function void gen_cfg(); configuration descriptor
program automatic test; ...
initial begin endfunction
virtual function void build(); Allocate and connect
dut_env env = new(); ... environment components
env.run(); endfunction
end virtual task reset_dut(); Reset DUT
endprogram ...
endtask
virtual task cfg_dut(); Download test
task vmm_env::run();
... configuration into DUT
this.gen_cfg(); endtask
virtual task start(); Start components
this.build(); ...
endtask
this.reset_dut();
virtual task wait_for_end(); End-of-test detection
this.cfg_dut(); ...
endtask
this.start(); virtual task stop(); Stop data generators &
... Wait for DUT to drain
this.wait_for_end();
endtask
this.stop(); virtual task cleanup(); Check recorded stats &
... sweep for lost data
this.cleanup(); endtask
this.report(); virtual task report();
... Report simulation results
endtask endtask
endclass
11- 11

RVM-SV (VMM) Overview 11-11


© 2006
SVTB
Execution Flow – Under the hood
 Methods in base class manage extern class vmm_env {
sequencing by ensuring the static int CFG_GENED;
static int BUILT;
previous one has been called static int DUT_RESET;
static int DUT_CFGED;
 "state" registers records how far static int STARTED;
simulation has progressed static int RESTARTED;
static int ENDED;
 run() calls cleanup() static int STOPPED;
followed by report() static int CLEANED;
task run();// Do not override
...
gen_cfg() }
build()
If a call to super.method()
reset_dut() run_t()
is left out, the chain is broken
cfg_dut()
start()
wait_for_end()
stop()
If already been called by
testcase, will not called again cleanup()
(same for all methods) report()
11- 12

RVM-SV (VMM) Overview 11-12


© 2006
SVTB
Example: Basic RVM Environment Extend from
class dut_env extends vmm_env;
vmm_env
virtual function void gen_cfg(); super.gen_cfg(); endfunction
virtual function void build(); super.build(); endfunction
virtual task reset_dut(); super.reset_dut(); endtask
virtual task cfg_dut(); super.cfg_dut(); endtask
virtual task start(); super.start(); endtask
virtual task stop(); super.stop(); endtask
virtual task wait_for_end(); super.wait_for_end(); endtask
virtual task cleanup(); super.cleanup(); endtask
virtual task report(); super.report(); endtask
function new(string name=“Environment”); super.new(name); endfunction
endclass
program automatic router_test;
extern class vmm_env; `include “vmm.sv”
vmm_log log; `include “dut_env.sv”
vmm_notify notify; initial begin
...// event flags dut_env env = new();
function new(string name = “Verif Env"); env.run();
task run(); // Do not override end
virtual function void gen_cfg(); endprogram Instantiate environment
virtual function void build(); object in program
virtual task reset_dut(); gen_cfg();
virtual task cfg_dut(); build(); then execute run()
virtual task start(); reset_dut(); Generator
virtual task wait_for_end(); cfg_dut();
virtual task stop(); start();
virtual task cleanup(); wait_for_end();
virtual task report(); stop();
...// other optional methods cleanup();
endclass report();

DUT
11- 13
The first step in constructing a SystemVerilog RVM testbench is to build the environment class.
This class must inherit from the vmm_env base class.

Within the environment class, 9 methods must be overriden: gen_cfg(), build(), reset_dut(),
cfg_dut(), start(), wait_for_end(), stop(), cleanup(), report().

Within the overriden methods, the super class method must be called first.

Once this skeleton structure is built, it can be instantiated and tested immediately within a
SystemVerilog program block.

RVM-SV (VMM) Overview 11-13


© 2006
SVTB
Testing Basic RVM Environment

program automatic router_test;


`include “vmm.sv”
`include “dut_env.sv”
initial begin
dut_env env = new();
env.build();
env.log.set_verbosity(vmm_log::TRACE_SEV);
env.run();
end
Trace[INTERNAL] on Environment() at 0:
endprogram Reseting DUT...
Trace[INTERNAL] on Environment() at 0:
Configuring...
Trace[INTERNAL] on Environment() at 0:
Starting verification environment...
Trace[INTERNAL] on Environment() at 0:
Saving RNG state information...
Trace[INTERNAL] on Environment() at 0:
Waiting for end of test...
Trace[INTERNAL] on Environment() at 0:
Stopping verification environment...
Trace[INTERNAL] on Environment() at 0:
Cleaning up...
Simulation PASSED on /./ (/./) at 0 (0 warnings, 0 demoted errors & 0 demoted warnings)
$finish at simulation time 0

11- 14
If the program block consists only of:
program automatic router_test;
`include “vmm.sv”
`include “dut_env.sv”
initial begin
dut_env env = new();
env.run();
end
endprogram

Simulation will run and finish at time 0 with the following message:
Simulation PASSED on /./ (/./) at 0 (0 warnings, 0 demoted errors & 0 demoted warnings)
$finish at simulation time 0

If you want to trace the method executions for debugging purposes, then through the default log
instance in the vmm_env class, you can turn on tracing and see the result as shown in slide. (Note:
this should be done after the build() phase of the RVM environment is executed.

env.log.set_verbosity(vmm_log::TRACE_SEV);

RVM-SV (VMM) Overview 11-14


© 2006
SVTB
Example: RVM Test Configuration
program automatic router_test; class dut_cfg; Create
`include “vmm.sv” string name Configuration
`include “dut_cfg.sv” rand int run_for_n_packets;
`include “dut_env.sv” rand reg drivers_in_use[];
initial begin rand reg receivers_in_use[];
dut_env env = new(); rand int num_of_drivers;
env.run(); rand int num_of_receivers;
end constraint valid {
endprogram run_for_n_packets >= 0;
num_of_drivers inside {[1:16]};
gen_cfg();
Configuration num_of_receivers inside {[1:16]};
build();
drivers_in_use.sum() == num_of_drivers;
reset_dut();
receivers_in_use.sum() == num_of_receivers;
cfg_dut();
}
start();
wait_for_end(); function new(string name = “Configuration”);
stop(); this.name = name;
cleanup(); drivers_in_use = new[16];
report(); receivers_in_use = new[16];
end function
class dut_env extends vmm_env;
dut_cfg cfg; DUT function void display(string prefix = “”);
function new(string name=“Environment”); ...
super.new(name); endfunction
this.cfg = new(); endclass
endfunction
virtual function void gen_cfg();
super.gen_cfg();
if (!this.cfg.randomize()) `vmm_fatal(…);
endfunction
...
endclass Randomize Configuration object
11- 15
The configuration class is intended to define the parameter for a given testcase. You should test the
working of the configuration class immediately after creation.

RVM-SV (VMM) Overview 11-15


© 2006
SVTB
Testing RVM Configuration

program automatic router_test;


`include “vmm.sv”
`include “dut_cfg.sv”
`include “dut_env.sv”
initial begin
dut_env env = new();
env.gen_cfg();
env.cfg.display();
env.run();
end
endprogram

[Configuration] run_for_n_packets = 363730487, num_of_drivers = 9, num_of_receivers = 9


[Configuration] valid input ports: 0, 1, 3, 5, 6, 9, 10, 11, 13,
[Configuration] valid output ports: 0, 1, 2, 3, 5, 7, 8, 9, 10,

Simulation PASSED on /./ (/./) at 0 (0 warnings, 0 demoted errors & 0 demoted warnings)
$finish at simulation time 0

11- 16
If the program block consists only of:
program automatic router_test;
`include “vmm.sv”
`include “dut_cfg.sv”
`include “dut_env.sv”
initial begin
dut_env env = new();
env.run();
end
endprogram

Simulation will run and finish at time 0 with the following message:
Simulation PASSED on /./ (/./) at 0 (0 warnings, 0 demoted errors & 0 demoted warnings)
$finish at simulation time 0

If you want to see what the configuration object contains, you can use the display() method of the
configuration object: (Note: this should be done after the gen_cfg() phase of the RVM environment
is executed.

env.cfg.display();
RVM-SV (VMM) Overview 11-16
© 2006
SVTB
Set Specific RVM Testcase Configuration
 RVM philosophy: one environment, many tests
 Limit modification to the program block
program automatic router_test;
`include “vmm.sv”
`include “dut_cfg.sv”
`include “dut_env.sv”
initial begin
dut_env env = new();
env.cfg.run_for_n_packets.rand_mode(0);
env.cfg.num_of_drivers.rand_mode(0);
env.cfg.num_of_receivers.rand_mode(0);
env.cfg.run_for_n_packets = 16;
env.cfg.num_of_drivers = 16;
env.cfg.num_of_receivers = 16;
env.gen_cfg();
env.cfg.display();
env.run(); [Configuration] run_for_n_packets = 16, num_of_drivers = 16, num_of_receivers = 16
end [Configuration] valid input ports: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
endprogram [Configuration] valid output ports: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,

Simulation PASSED on /./ (/./) at 0 (0 warnings, 0 demoted errors & 0 demoted warnings)
$finish at simulation time 0

11- 17
Although the properties within the configuration object are all set to be random variables, you can
still set these properties to ones of your choosing in the program block.
One way is as shown in the slide: disable randomization then set the properties to your chosen value.
The second way it can be done is to extend from the existing configuration class, modify the
constraint, then replace the configuration object in the environment object with the new
configuration object as shown below:
program automatic router_test;
`include "vmm.sv"
`include “dut_cfg.sv"
`include “dut_env.sv"
class testConfig extends dut_cfg;
constraint test {
run_for_n_packets == 16;
num_of_drivers == 16;
num_of_receivers == 16;
}
endclass
initial begin
dut_env env = new();
testConfig cfg = new();
env.cfg = cfg;
env.gen_cfg();
env.cfg.display();
env.run();
end
endprogram

RVM-SV (VMM) Overview 11-17


© 2006
SVTB
Example: RVM Stimulus Generation
Create Transaction class Packet_atomic_gen extends vmm_xactor;
int stop_after_n_insts, DONE, GENERATED;
Packet randomized_obj; Packet_channel out_chan;
class Packet extends vmm_data; task main(); fork super.main(); join_none
rand reg[3:0] sa, da; while (stop_after_n_insts …) begin
rand reg[7:0] payload[*]; Packet obj;
constraint valid { ... } if (!randomized_obj.randomize()) begin ...; end
...; $cast(obj, randomized_obj.copy());
endclass out_chan.put_t(obj);
`vmm_channel(Packet) this.notify.indicate(this.GENERATED, obj);
`vmm_atomic_gen(Packet) end
this.notify.indicate(this.DONE); Macro
endtask
program automatic router_test; endclass automatically
initial begin class Environment extends vmm_env; ...
creates generator
Environment env = new(); Packet_atomic_gen gen;
env.run(); virtual function void build(); ...
end gen = new(“Generator”, 0);
endprogram gen.stop_after_n_insts = cfg.run_for_n_packets;
gen.out_chan.sink();
gen_cfg(); endfunction
Configuration virtual task start(); ...;
Instantiate, build
build();
reset_dut(); gen.start_xactor(); and start
cfg_dut(); Generator endtask Generator object
start(); virtual task wait_for_end(); ...;
wait_for_end(); gen.notify.wait_for(Packet_atomic_gen::DONE);
stop(); endtask
cleanup(); virtual task stop(); ...;
report(); gen.stop_xactor();
endtask
endclass
DUT
11- 18

RVM-SV (VMM) Overview 11-18


© 2006
SVTB
Testing RVM Atomic Generator
 One environment, many tests applies here also
program automatic router_test;
class Packet extends vmm_data;
`include “vmm.sv” rand reg[3:0] sa, da;
`include “dut_cfg.sv” rand reg[7:0] payload[*];
`include “Packet.sv” constraint valid { ... }
`include “dut_env.sv” ...;
class testPacket extends Packet; endclass
function void post_randomize(); `vmm_channel(Packet)
`vmm_atomic_gen(Packet)
super.post_randomize();
this.display(“Randomized Packet”);
endfunction [Randomized Packet] Packet #0.0.0: sa = 6, da = 3 payload.size() = 1
endclass [Randomized Packet] Packet #0.0.0: payload[0] = 197
initial begin
[Randomized Packet] Packet #0.0.1: sa = 15, da = 2 payload.size() = 5
dut_env env = new(); [Randomized Packet] Packet #0.0.1: payload[0] = 69
testPacket pkt = new(); [Randomized Packet] Packet #0.0.1: payload[1] = 244
env.build(); [Randomized Packet] Packet #0.0.1: payload[2] = 108
env.gen.randomized_obj = pkt; [Randomized Packet] Packet #0.0.1: payload[3] = 103
[Randomized Packet] Packet #0.0.1: payload[4] = 140
env.run();
end [Randomized Packet] Packet #0.0.2: sa = 15, da = 8 payload.size() = 3
[Randomized Packet] Packet #0.0.2: payload[0] = 217
endprogram [Randomized Packet] Packet #0.0.2: payload[1] = 169
[Randomized Packet] Packet #0.0.2: payload[2] = 170

11- 19
If the program block consists only of:
program automatic router_test;
`include “vmm.sv”
`include “dut_cfg.sv”
`include “Packet.sv”
`include “dut_env.sv”
initial begin
dut_env env = new();
env.run();
end
endprogram

Simulation will run and finish at time 0 with the following message:
Simulation PASSED on /./ (/./) at 0 (0 warnings, 0 demoted errors & 0 demoted warnings)
$finish at simulation time 0

If you want to see what the generator created, you can modify the post_randomize() method in
randomized_obj with a call to the display() method. To do this, first, extend the existing Packet class
with a new testPacket class defintion and add the new post_randomize() method. Then, instantiate
and replace the randomize_obj in the generator with the newly created one. (Note: this should be
done after the build() phase of the RVM environment is executed)

RVM-SV (VMM) Overview 11-19


© 2006
SVTB
Example: RVM Transactor Class
class DriveXactor extends vmm_xactor;
Packet pkt2send;
Create input transactor from
Packet_channel in_chan; vmm_xactor base class
function new(...); ...
task send_packet(); ...
Embed functionality
virtual protected task main();
fork super.main(); join_none
in main() method
while(1) begin
wait_if_stopped_or_empty(in_chan);
in_chan.get(pkt2send);
`vmm_callback(DriveXactor_callbacks, pre_transaction(pkt2send));
send();
begin Callback for
Packet pkt; error injection
if (!$cast(pkt, pkt2send.copy()) `rvm_fatal(...);
`vmm_callback(DriveXactor_callbacks, post_transaction(pkt));
end
end Callback for
endtask
...
coverage, scoreboard
endclass pass copied object

11- 20

RVM-SV (VMM) Overview 11-20


© 2006
SVTB
Example: RVM Coverage (Callbacks)
 RVM philosophy: coverage-driven verification
 Implementing functional coverage is a four step process:
 Insert callback method in transactor with `vmm_callback macro
 Build callback façade class

 Define callback class functionality

 Register callback objects in environment


Step 1 is already done for
class Packet_atomic_gen extends vmm_xactor; you when you use
virtual protected task main(); ... `vmm_atomic_gen macro
while (...) begin
Packet obj;
if (!randomized_obj.randomize()) ...
if (!$cast(obj, randomized_obj.copy()) ...
Name of
begin callback façade
bit drop = 0; class
out_chan.put(obj);
`vmm_callback(Packet_atomic_gen_callbacks, post_inst_gen(this, obj, drop));
this.notify.indicate(this.GENERATED, obj);
end
callback method
end
endtask Callback
endclass macro

11- 21

RVM-SV (VMM) Overview 11-21


© 2006
SVTB
RVM Coverage Continued
Step 2 is already done for
 Step 2: build callback façade class you when you use
`vmm_atomic_gen macro
class Packet_atomic_gen_callbacks extends vmm_xactor_callbacks;
virtual task post_inst_gen(Packet_atomic_gen gen, Packet obj, ref bit drop);
endtask
endclass Callback method prototype
with empty body

 Step 3: define callback class functionality


class Packet_gen_cov_callbacks extends Packet_atomic_gen_callbacks;
bit[3:0] sa, da;
covergroup gen_port_cov; Create coverage bins
coverpoint sa;
coverpoint da;
cross sa, da; Construct coverage object
endgroup
function new(); gen_port_cov = new(); endfunction
virtual task post_inst_gen(Packet_atomic_gen gen, Packet pkt, ref bit drop);
this.sa = pkt.sa;
this.da = pkt.da; Define callback functionality
gen_port_cov.sample(); callback method
endtask
endclass Trigger coverage bin update
11- 22

RVM-SV (VMM) Overview 11-22


© 2006
SVTB
RVM Coverage Continued

 Step 4: register callback objects in environment


class dut_env extends vmm_env;
dut_cfg cfg;
Packet_atomic_gen gen;
Packet_gen_cov_callbacks gen_cov_cb; Create callback
function new(); ... coverage object
virtual function void gen_cfg(); ...
virtual function void build();
super.build();
gen = new("gen", 0);
gen.stop_after_n_insts = cfg.run_for_n_packets;
gen.out_chan.sink();
gen_cov_cb = new(); Construct callback
gen.append_callback(gen_cov_cb); coverage object
endfunction
virtual task reset_dut(); Register callback
... coverage object
endclass

 Once registered, the callback method for functional


coverage will be executed every time the generator
deposits an object into out_chan
11- 23

RVM-SV (VMM) Overview 11-23


© 2006
SVTB
Testing RVM Coverage
program automatic router_test; class Packet_gen_cov_callbacks
`include "vmm.sv" ...
`include “dut_cfg.sv" covergroup gen_port_cov;
`include "packet.sv" coverpoint sa;
`include “gen_cov_cb.sv" coverpoint da;
`include “dut_env.sv" cross sa, da;
endgroup
initial begin ...
dut_env env = new(); endclass
env.run();
end

endprogram

./simv | tee log


ntbCovReport -cov_report ./

11- 24

RVM-SV (VMM) Overview 11-24


© 2006
SVTB
Example: Implementing RVM Scoreboard
class dut_sb extends vmm_xactor;
Inherit from vmm_xactor
static int DONE;
static int pkts_generated = 0, pkts_sent = 0, pkts_received = 0, pkts_checked = 0;
Packet sentPkts[$];
function new(...);
virtual function void deposit_sentpkt(Packet pkt); Scoreboard track
virtual function void deposit_receivedPkt(Packet pkt); matrix variables
virtual function void deposit_genpkt(Packet pkt);
string message;
Methods for transactors to
genPkts.push_back(pkt);
pkts_generated++; deposit objects to scoreboard
if (check_coverage(message))
this.notify.indicate(this.DONE);
$display(message);
endfunction
virtual function bit check_coverage(ref string message); Detecting terminating
coverage_result = $get_coverage(); conditions
if ( coverage_result == 100 || ... ) begin
message = $psprintf(“Coverage = %0d", coverage_result));
check_coverage = 1;
end
else ...; Indicates terminating condition found
end
endfunction
virtual task final_check();
virtual function void report(); Cleanup and report
endclass
methods
11- 25

RVM-SV (VMM) Overview 11-25


© 2006
SVTB
Example: RVM Scoreboard Continued
 Then, link scoreboard to transactors via callbacks
 Same four step process:
 Insert callback method in transactor with `vmm_callback macro
 Build callback façade class

 Define callback class functionality

 Register callback objects in environment

class Packet_atomic_gen extends vmm_xactor;


virtual protected task main(); ...
while (...) begin
Packet obj;
if (!randomized_obj.randomize()) ... Do nothing in step 1 if you
if (!$cast(obj, randomized_obj.copy()) ... have already inserted
begin callbacks for coverage
bit drop = 0;
out_chan.put(obj);
`vmm_callback(Packet_atomic_gen_callbacks, post_inst_gen(this, obj, drop));
this.notify.indicate(this.GENERATED, obj);
end
end
endtask
endclass

11- 26

RVM-SV (VMM) Overview 11-26


© 2006
SVTB
RVM Scoreboard Callbacks

 Step 2: Build callback façade class


 Already done if coverage was implemented
class Packet_atomic_gen_callbacks extends vmm_xactor_callbacks;
virtual task post_inst_gen(Packet_atomic_gen gen, Packet obj, ref bit drop);
endtask
endclass

 Step 3: Define callback class functionality


Build scoreboard
callback class

class Packet_gen_sb_callbacks extends Packet_atomic_gen_callbacks;


dut_sb sb;
function new(dut_sb sb); Pass in scoreboard
this.sb = sb; handle in constructor
endfunction
virtual task post_inst_gen(Packet_atomic_gen gen, Packet pkt, ref bit drop);
sb.deposit_genpkt(pkt);
endtask Pass object to scoreboard
endclass via scoreboard handle

11- 27

RVM-SV (VMM) Overview 11-27


© 2006
SVTB
RVM Scoreboard Callbacks
 Step 4: register callback objects in environment
class dut_env extends vmm_env;
...;
Packet_atomic_gen gen;
Packet_gen_cov_callbakcs gen_cov_cb;
dut_sb sb; Create scoreboard
Packet_gen_sb_callbacks gen_sb_cb; and callback object
function new(); ...
virtual function void gen_cfg(); ...
virtual function void build();
...;
gen = new("gen", 0);
...;
sb = new("sb", "class", cfg);
gen_cov_cb = new(); Construct scoreboard
gen_sb_cb = new(); callback object
gen.append_callback(gen_cov_cb);
gen.append_callback(gen_sb_cb);
endfunction
Register scoreboard
virtual task wait_for_end();
sb.notify.wait_for(sb.DONE); callback object
endtask
endclass

11- 28

RVM-SV (VMM) Overview 11-28


© 2006
SVTB
Summary: RVM Guiding Principles

 Top-down implementation methodology


 Emphasizes “Coverage Driven Verification”
 Maximize design quality
 More testcases
 More checks Constrainable Many runs,
different seeds
 Less code Random Generation

 Approaches Directed
 Reuse Add Testcase Functional
constraints Coverage
 Across tests
 Across blocks Minimal Code Identify
Modifications holes
 Across systems

 Across projects
 One verification environment, many tests
 Minimize test-specific code
11- 29

RVM-SV (VMM) Overview 11-29


© 2006
SVTB
Unit Objectives Review

Having completed this unit, you should be able to:


 Describe the RVM-SV testbench architecture
 Describe the RVM-SV environment execution
sequence
 Describe the RVM-SV testcase development
Methodology

11- 30

RVM-SV (VMM) Overview 11-30


© 2006
SVTB
Appendix

RVM-OV vs. RVM-SV

RVM-SV (VMM) Overview 11-31


© 2006
SVTB
RVM-OV vs. RVM-SV

 Classes
RVM-
RVM-OV RVM-
RVM-SV

rvm_log vmm_log
rvm_env vmm_env
rvm_data vmm_data
rvm_channel_class vmm_channel
rvm_xactor vmm_xactor
rvm_notify vmm_notify
rvm_broadcast vmm_broadcast
rvm_scheduler vmm_scheduler

11- 32

RVM-SV (VMM) Overview 11-32


© 2006
SVTB
RVM-OV vs. RVM-SV

 Macros RVM-
RVM-OV RVM-
RVM-SV

rvm_fatal `vmm_fatal
rvm_error `vmm_error
rvm_warning `vmm_warning
rvm_note `vmm_note
rvm_trace `vmm_trace
rvm_debug `vmm_debug
rvm_verbose `vmm_verbose
rvm_channel `vmm_channel
rvm_atomic_gen `vmm_atomic_gen
rvm_scenario_gen `vmm_scenario_gen
rvm_OO_callback `vmm_callback

11- 33

RVM-SV (VMM) Overview 11-33


© 2006
SVTB
RVM-OV vs RVM-SV

 Functions are nonblocking in SV function

RVM-
RVM-OV RVM-
RVM-SV task
rvm_env::gen_cfg() vmm_env::gen_cfg() No "_t"
rvm_env::build() vmm_env::build()
rvm_env::reset_dut_t() vmm_env::reset_dut()
rvm_env::cfg_dut_t() vmm_env::cfg_dut() "_t" -> task
rvm_env::start_t() vmm_env::start()
rvm_env::wait_for_end_t() vmm_env::wait_for_end()
rvm_env::stop_t() vmm_env::stop()
rvm_env::cleanup_t() vmm_env::cleanup()
rvm_env::report() vmm_env::report()

Changed from function to task

11- 34

RVM-SV (VMM) Overview 11-34


© 2006
SVTB
RVM-OV vs RVM-SV

 Input channels (RVM-OV)


Functions
tr = in_chan.get_t();
tr = in_chan.peek_t();
tr = in_chan.activate_t();
Functions are
nonblocking in SV
 Becomes (RVM-SV)
Tasks
in_chan.get(tr);
in_chan.peek(tr);
in_chan.activate(tr);

11- 35

RVM-SV (VMM) Overview 11-35


© 2006
SVTB
RVM-OV vs RVM-SV

 Class-level symbolic values (RVM-OV)


log.set_verbosity(log.DEBUG_SEV);

Static class property


in OV

 Becomes (RVM-SV)
log.set_verbosity(vmm_log::DEBUG_SEV);

Class-
Class-level enum
in SV

11- 36

RVM-SV (VMM) Overview 11-36


© 2006
SVTB
RVM-OV vs RVM-SV

Does not
exist
 Waiting for next transaction (RVM-OV)
vmm_xactor::next_transaction(chan)
rvm_xactor::next_transaction_t(chan)
Deprecated
 Use (RVM-SV)
vmm_xactor::wait_if_stopped_or_empty(chan);
chan.peek(tr);

rvm_xactor::wait_if_stopped_or_empty_t(chan);
tr = chan.peek_t();
Notifications automatically handled
(XACTOR_IDLE, XACTOR_BUSY)

11- 37

RVM-SV (VMM) Overview 11-37


© 2006
SVTB
RVM-OV vs RVM-SV

 Time unit display


 Part of format string in OV
 Time unit defined by Vera shell timescale
 Uses built-in %t formatter in SV
 Use %t and $timeformat()
 Time unit globally defined
 Also applies to RVM-OV in NTB

11- 38

RVM-SV (VMM) Overview 11-38


© 2006
SVTB
RVM-OV vs RVM-SV

 Physical interfaces
 In OV
 Define interface for each clocking domain, connect using
hdl_node
 Define virtual port

 Bind interface signals to virtual port instance

 Class written using virtual port

 Pass virtual port instance to class via constructor

11- 39

RVM-SV (VMM) Overview 11-39


© 2006
SVTB
RVM-OV vs RVM-SV

 Physical interfaces
 In SV
 Define interface for each signal bundle
– Signals defined as wire
– One clocking block per clocking domain
– One modport per agent
 Instantiate interface in top-level module, connect using
continuous assign
 Class written using virtual modport

 Pass modport instance to class via constructor

11- 40

RVM-SV (VMM) Overview 11-40


© 2006
SVTB
Planning for RVM-SV

 When using RVM-OV


 Keep all functions nonblocking
 Only block tasks
 Do not wait on clock edges
 Use void expects or drive

11- 41

RVM-SV (VMM) Overview 11-41


© 2006
SVTB
This page was intentionally left blank.

RVM-SV (VMM) Overview 11-42


© 2006
SVTB
Customer Support

© 2005 Synopsys, Inc. All Rights Reserved 20050516

Customer Support CS-1


© 2005
Synopsys Support Resources

1. Build Your Expertise:


Customer Education Services
 www.synopsys.com
 Workshop schedule and registration
 Download materials (SolvNet id
required)

2. Empower Yourself:
solvnet.synopsys.com
 Online technical information and
access to support resources
 Documentation & Media

3. Access Synopsys Experts:


Support Center

CS- 2

Customer Support CS-2


© 2005
SolvNet Online Support Offers
 Immediate access to the
latest technical
information
 Thousands of expert-
authored articles, Q&As,
scripts and tool tips
 Enter-a-call online
Support Center access
 Release information
 Online documentation
 License keys
 Electronic software
downloads
 Synopsys
announcements (latest
tool, event and product
information)

CS- 3

Customer Support CS-3


© 2005
SolvNet Registration is Easy
1. Go to solvnet.synopsys.com/
ProcessRegistration
2. Pick a username and password.
3. You will need your “Site ID” on
the following page.
4. Authorization typically takes
just a few minutes.

CS- 4

Customer Support CS-4


© 2005
Support Center: AE-based Support

 Industry seasoned Application Engineers:


 50% of the support staff has > 5 years applied experience
 Many tool specialist AEs with > 12 years industry experience
 Access to internal support resources
 Great wealth of applied knowledge:
 Service >2000 issues per month
 Remote access and debug via ViewConnect

Fastest access
 Contact us:
 Web: Enter A Call from solvnet.synopsys.com
 See http://www.synopsys.com/support
for local support resources
CS- 5

Customer Support CS-5


© 2005
Other Technical Sources

 Application Consultants (ACs):


 Tool and methodology pre-sales support
 Contact your Sales Account Manager for more information
 Synopsys Professional Services (SPS) Consultants:
 Available for in-depth, on-site, dedicated, custom consulting
 Contact your Sales Account Manager for more details
 SNUG (Synopsys Users Group):
 www.snug-universal.org

CS- 6

Customer Support CS-6


© 2005
Summary: Getting Support

 Customer Education Services


 SolvNet
 Support Center
 SNUG

CS- 7

Customer Support CS-7


© 2005
This page was intentionally left blank.

Customer Support CS-8


© 2005

Potrebbero piacerti anche