Sie sind auf Seite 1von 360

Verilog-XL

Verilog-XL Training Manual


Version 2.2
Training Manual
Version 2.2

Educational Services Group (ESG)


Educational Services Group (ESG) June 29, 1995
June 29, 1995
Table of Contents Verilog-XL

1990-95 Cadence Design Systems, Inc. All rights reserved. Table of Contents
Printed in the United States of America.
No part of this publication may be reproduced in whole or in part by any means (including photocopying or storage in an information Verilog-XL
storage/retrieval system) or transmitted in any form or by any means without prior written permission from Cadence Design Systems, Inc.
(Cadence).
Information in this document is subject to change without notice and does not represent a commitment on the part of Cadence. The information
contained herein is the proprietary and confidential information of Cadence or its licensors, and is supplied subject to, and may be used only Module 1 Getting Started
by Cadences customer in accordance with, a written agreement between Cadence and its customer. Except as may be explicitly set forth in
such agreement, Cadence does not make, and expressly disclaims, any representations or warranties as to the completeness, accuracy or
usefulness of the information contained in this document. Cadence does not warrant that use of such information will not infringe any third Course Objectives .................................................................................................................................... 1-4
party rights, nor does Cadence assume any liability for damages or costs of any kind that may result from use of such information. Course Map.............................................................................................................................................. 1-6
RESTRICTED RIGHTS LEGEND Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subparagraph Training Manual Conventions ............................................................................................................... 1-10
(c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013.
Cadence Design Systems, Inc. 555 River Oaks Parkway, San Jose, CA 95134, USA Getting Help........................................................................................................................................... 1-12
Unpublished rights reserved under the copyright laws of the United States. OpenBook Online Documentation Utility ....................................................................................... 1-14
In this manual the screen representation of Framework and any reference to it connotes Design Framework II software.

Cadence Trademarks Module 2 Introduction and Basic Concepts


Access DF/Signal Integrity PIC Designer Test Generator
Allegro DFTestprep PowerVHDL TestGrade Why Use an HDL?................................................................................................................................... 2-4
Allegro-MCM DF/Thermax PRANCE Test-intelligent Design Series
Amadeus DF/Viable Prance-XL TestScan Key Features of HDLs ............................................................................................................................. 2-6
Analog Artist DIVA Preview Test Simulator Simulation Algorithms............................................................................................................................. 2-8
Analog Workbench DLM Place & Route System Process Manager Test Synthesizer
Analyzer DRACULA Profile ThermoSTATS Time Wheel in Event-Driven Simulation .............................................................................................. 2-10
ASIC Workbench EDGE RapidPART Transcribe
AXL RapidSIM ValidCOMPILER
Different Levels of Abstraction ............................................................................................................. 2-12
Ensemble
BitGrade GDSII RapidTEST ValidFrame Bottom-Up Design Flow........................................................................................................................ 2-14
Cadence SPICE GED Sage ValidGED
CAEviews HDL Synthesizer SCALDsystem ValidPACKAGER Top-Down Design Flow ........................................................................................................................ 2-16
CheckPlus Hierarchy Manager Simukit ValidSIM Typical Design Flow.............................................................................................................................. 2-18
Communications Manager INSIGHT SKILL ValidTIME
Component Information Workbench Integrators Toolkit Smartpath VDoc 454 Verilog HDL and Verilog-XL Software ................................................................................................ 2-20
Compose LayDe Smoke Alarm Verifault-XL
Composer Spectre Verilog
Verilog HDL .......................................................................................................................................... 2-22
Leapfrog
Concept License Manager SPICE PLUS Verilog-XL Key Language Features.................................................................................................................... 2-24
Confirm Logic Workbench Structure Compiler Veritime
Construct MLM Place & Route System SYMBAD Veritools Verilog Module.......................................................................................................................... 2-24
Dantes ModuleMaker Synergy VHDL Synthesizer Module Ports.............................................................................................................................. 2-26
Design Framework OpenBook SystemPGA VHDL-XL
Design Framework Open HDL Toolkit SystemPLD Virtuoso Module Instances ....................................................................................................................... 2-28
Design Manager System Workbench Warp-4
Design Planner
OpenSim Backplane
Warp Grid
The Verilog-XL Simulator..................................................................................................................... 2-30
Optimizer Tancell
DF/Assembly Opus Tansure XLProcessor Related Products .................................................................................................................................... 2-32
DFFab Team Design Manager

Other Trademarks
FrameMaker is a registered trademark of Frame Technology Corporation.
PostScript is a registered trademark of Adobe Systems.
UNIX is a registered trademark, licensed exclusively by X/Open Company Ltd.
X Window System is a trademark of the Massachusetts Institute of Technology.

6/29/95 Cadence Design Systems, Inc. iii


Verilog-XL Table of Contents Table of Contents Verilog-XL

Module 3 Sample Design Module 5 Verilog Data Types and Logic System
A Simple and Complete Example............................................................................................................ 3-4 4-Value Logic System in Verilog ............................................................................................................ 5-4
Device Under Test ................................................................................................................................... 3-6 The Three Unknown Logic Values.......................................................................................................... 5-6
Test Fixture Template .............................................................................................................................. 3-8 Major Data Type Classes ......................................................................................................................... 5-8
Test Fixture Making an Instance................................................................................................. 3-10 Nets ........................................................................................................................................................ 5-10
Test Fixture Describing Stimulus ............................................................................................... 3-12 Types of Nets ................................................................................................................................... 5-12
Activation Versus Execution of Procedural Blocks................................................................... 3-14 Logic Conflict Resolution with Net Data Types.............................................................................. 5-14
Test Fixture Response Generation .............................................................................................. 3-18 Registers................................................................................................................................................. 5-16
A Complete Test Fixture........................................................................................................................ 3-20 Types of Registers............................................................................................................................ 5-18
The cWaves Window............................................................................................................................. 3-22 Declaration Syntax of Verilog Nets and Registers ................................................................................ 5-20
Getting Started with cWaves ........................................................................................................... 3-24 Choosing the Correct Data Type............................................................................................................ 5-22
Node Specifiers for cWaves............................................................................................................. 3-26 Common Mistakes in Choosing Data Types ................................................................................... 5-24
Starting cWaves and Opening a Database ....................................................................................... 3-28 Parameters.............................................................................................................................................. 5-26
Saving the cWaves Environment ..................................................................................................... 3-30 Overriding the Values of Parameters............................................................................................... 5-28
Starting the Verilog-XL Software.......................................................................................................... 3-32 Defparam Statement................................................................................................................... 5-28
Lab 1 Getting Started ............................................................................................................................. 3-33 Module Instance Parameter Value Assignment......................................................................... 5-30

Module 4 Lexical Conventions in Verilog Module 6 Structural Modeling


White Spaces and Comments................................................................................................................... 4-4 Structural Modeling ................................................................................................................................. 6-4
Integer and Real Numbers ....................................................................................................................... 4-6 Verilog Primitives.................................................................................................................................... 6-6
Strings ...................................................................................................................................................... 4-8 Primitive Pins Are Expandable.......................................................................................................... 6-8
Identifiers ............................................................................................................................................... 4-10 Conditional Primitives ..................................................................................................................... 6-10
Escaped Identifiers................................................................................................................................. 4-12 Primitive Instantiation............................................................................................................................ 6-12
Case Sensitivity...................................................................................................................................... 4-14 Module Instantiation .............................................................................................................................. 6-14
Special Language Tokens ...................................................................................................................... 4-16 Delay Specification in Primitives .......................................................................................................... 6-16
System Tasks and Functions............................................................................................................ 4-16 Logic Strength Modeling ....................................................................................................................... 6-18
Delay Specification.......................................................................................................................... 4-18 Signal Strength Value System ............................................................................................................... 6-20
Compiler Directives ............................................................................................................................... 4-20 Verilog Resolves Ambiguous Strength.................................................................................................. 6-22
Text Substitution.............................................................................................................................. 4-22 Verilog Model Libraries ........................................................................................................................ 6-24
+define+ ........................................................................................................................................... 4-24 Example of the `uselib Compiler Directive ........................................................................................... 6-34
Text Inclusion .................................................................................................................................. 4-26 Lab 2 Structural Modeling ..................................................................................................................... 6-35
Timescale in Verilog........................................................................................................................ 4-28

iv Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. v
Verilog-XL Table of Contents Table of Contents Verilog-XL

Module 7 Support for Verification Module 9 Behavioral Modeling


Support for Verification........................................................................................................................... 7-4 Behavioral Modeling ............................................................................................................................... 9-4
Reading Simulation Time ........................................................................................................................ 7-6 Procedural Blocks .................................................................................................................................... 9-6
Accessing Time Information.................................................................................................................... 7-8 Timing Control in Procedural Blocks ...................................................................................................... 9-8
Printing Time Information ..................................................................................................................... 7-10 Example ........................................................................................................................................... 9-10
Displaying Signal Values....................................................................................................................... 7-12 Procedural Assignment .......................................................................................................................... 9-12
$display ............................................................................................................................................ 7-12 Operators in Verilog Assignments......................................................................................................... 9-14
$write ............................................................................................................................................... 7-14 Bit-Wise, Unary, and Logical Operators ............................................................................................... 9-16
$strobe.............................................................................................................................................. 7-14 Equality Operators ................................................................................................................................. 9-18
Example ........................................................................................................................................... 7-16 Block Statements ................................................................................................................................... 9-20
Monitoring Signal Values ...................................................................................................................... 7-18 Intra-Assignment Timing Control.......................................................................................................... 9-22
$monitor........................................................................................................................................... 7-18 Intra-Assignment Timing Control Example .......................................................................................... 9-24
File Output in Verilog............................................................................................................................ 7-20 Nonblocking Procedural Assignment .................................................................................................... 9-26
Conditional Statements .......................................................................................................................... 9-30
Module 8 Specify Blocks If and If-Else Statements.................................................................................................................. 9-30
Case Statement................................................................................................................................. 9-32
Features of a Specify Block ..................................................................................................................... 8-4
Looping Statements ............................................................................................................................... 9-34
Delay Modeling Options.......................................................................................................................... 8-6 Repeat Loop ..................................................................................................................................... 9-34
Module Path Delays................................................................................................................................. 8-8
While Loops..................................................................................................................................... 9-36
Parallel Versus Full Connection Module Paths ............................................................................... 8-10
For Loops ......................................................................................................................................... 9-38
Specify Block Parameters ...................................................................................................................... 8-12 Modeling Asynchronous Reset .............................................................................................................. 9-40
Restrictions on Module Paths .......................................................................................................... 8-14 Zero-Delay Loops in Verilog................................................................................................................. 9-42
Inertial Versus Transport Delay Models................................................................................................ 8-16
Importing VHDL Models ...................................................................................................................... 9-44
Path Pulse Control Options.................................................................................................................... 8-18
Lab 4 Behavioral Modeling ................................................................................................................... 9-45
Timing Checks in Verilog...................................................................................................................... 8-22
Notifiers in Timing Checks.................................................................................................................... 8-26
Conditional Timing Checks ................................................................................................................... 8-28
Lab 3 Modeling with Path Delays and Timing Checks ......................................................................... 8-29

vi Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. vii
Verilog-XL Table of Contents Table of Contents Verilog-XL

Module 10 Interactive Debugging in Verilog Module 13 User-Defined Tasks and Functions in Verilog
Running in Batch Mode Versus Interactive Mode ................................................................................ 10-4 Verilog Tasks and Functions ................................................................................................................. 13-4
Verilog in the Interactive Mode............................................................................................................. 10-6 Specifications of a CPU Interface.......................................................................................................... 13-6
Entering the Interactive Mode ............................................................................................................... 10-8 Verilog Task........................................................................................................................................... 13-8
Typical Tasks in Interactive Mode ...................................................................................................... 10-10 Verilog Function .................................................................................................................................. 13-10
Setting Breakpoints........................................................................................................................ 10-10 Named Event........................................................................................................................................ 13-12
Traversing the Design Hierarchy ................................................................................................... 10-12 Named Blocks...................................................................................................................................... 13-14
Decompiling the Design ...................................................................................................................... 10-14 Disabling Named Blocks and Tasks .................................................................................................... 13-16
An Example of Traversing the Design................................................................................................. 10-16 Lab 8 Tasks and Functions in Verilog ................................................................................................. 13-17
Displaying Signal Values............................................................................................................... 10-18 Lab 9 Simulating a Complete System.................................................................................................. 13-17
Circuit Patching ............................................................................................................................. 10-20
$deposit .......................................................................................................................................... 10-22 Module 14 Modeling for Synergy
Tracing Simulation Activity .......................................................................................................... 10-24
Synthesis ................................................................................................................................................ 14-4
Source-Level Debugger in Verilog...................................................................................................... 10-26
Saving and Restarting Verilog Simulation .......................................................................................... 10-28 Modeling Style....................................................................................................................................... 14-6
Combinational Logic ............................................................................................................................. 14-8
Interactive Command History.............................................................................................................. 10-30
Procedural Blocks with Event Sensitivity List .................................................................................... 14-10
Lab 5 Behavioral Modeling and Interactive Debugging...................................................................... 10-31
Case Statement..................................................................................................................................... 14-12
Latched Logic ...................................................................................................................................... 14-14
Module 11 Modeling with Continuous Assignments
Simple Sequential Logic ...................................................................................................................... 14-16
Continuous Assignments ....................................................................................................................... 11-4 Asynchronous Reset............................................................................................................................. 14-18
Conditional Operator ............................................................................................................................. 11-6 Synchronous Reset............................................................................................................................... 14-20
Concatenation and Replication Operators ........................................................................................... 11-10 Explicit Style of Finite State Machines ............................................................................................... 14-22
Lab 6 Modeling with Continuous Assignments .................................................................................. 11-11 Implicit Style of Finite State Machines ............................................................................................... 14-24
An Example of an Implicit FSM.......................................................................................................... 14-26
Module 12 Modeling Memories Library Basics ...................................................................................................................................... 14-28
Overview........................................................................................................................................ 14-28
Memory Declaration .............................................................................................................................. 12-4
Modeling ........................................................................................................................................ 14-30
Memory Addressing............................................................................................................................... 12-6 Specify Blocks ............................................................................................................................... 14-32
Loading a Memory Array ...................................................................................................................... 12-8
File Format for $readmemb and $readmemh....................................................................................... 12-10
Modeling Bidirectional Ports............................................................................................................... 12-12
bufif Primitives .............................................................................................................................. 12-14
Continuous Assignments ............................................................................................................... 12-16
Lab 7 Modeling Memories................................................................................................................... 12-17

viii Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. ix
Verilog-XL Table of Contents Table of Contents Verilog-XL

Module 15 Modeling ASIC Libraries Module 17 Modeling to Achieve Simulation Performance


Verilog Composite Libraries.................................................................................................................. 15-4 The Turbo and the XL Algorithm.......................................................................................................... 17-4
Modeling ASIC Libraries ...................................................................................................................... 15-6 Default Algorithm Flow Chart............................................................................................................... 17-6
Functional Modeling of Library Cells ................................................................................................... 15-8 Controlling Acceleration........................................................................................................................ 17-8
UDPs .............................................................................................................................................. 15-10 The Four Levels of Turbo .................................................................................................................... 17-10
UDP Features ........................................................................................................................... 15-12 Using Turbo with Other Performance Options.............................................................................. 17-12
UDP Examples............................................................................................................................... 15-14 Twin Turbo .......................................................................................................................................... 17-14
Combinational UDP: 2-1 Multiplexer ..................................................................................... 15-14 The XL Algorithm ............................................................................................................................... 17-18
Combinational UDP: Full Adder ............................................................................................. 15-16 Items Unsupported by the XL Algorithm ...................................................................................... 17-20
Level Sensitive Sequential UDP: Latch................................................................................... 15-18 XL Algorithm Performance Considerations ........................................................................................ 17-22
Edge-Sensitive Sequential UDP: D Flip Flop.......................................................................... 15-20 Turbo Algorithm Performance Considerations.................................................................................... 17-24
Modeling Timing for Library Cells ..................................................................................................... 15-22 Achieving Optimal Performance ......................................................................................................... 17-26
Delay Modeling ............................................................................................................................. 15-24 The Behavioral Profiler........................................................................................................................ 17-32
State-Dependent Path Delays (SDPDs) ................................................................................... 15-26 Running the Verilog Profiler ............................................................................................................... 17-34
Delays of X Transitions ........................................................................................................... 15-28
Notifiers in Timing Checks.................................................................................................................. 15-30 Module 18 The Verilog-XL Graphical Environment
Source Protection Mechanism in Verilog ............................................................................................ 15-34
Automatic Protection of All Modules and UDPs ................................................................................ 15-36 Invoking the Environment ..................................................................................................................... 18-4
VCW ...................................................................................................................................................... 18-8
Protecting Selected Regions in a Source Description.................................................................... 15-38
Selecting Objects ........................................................................................................................... 18-10
Lab 10 Modeling ASIC Libraries ........................................................................................................ 15-39
File Menu ....................................................................................................................................... 18-14
Run Menu....................................................................................................................................... 18-16
Module 16 Delay Calculation and Backannotation
Show Menu .................................................................................................................................... 18-18
Why Delay Calculation and Backannotation? ....................................................................................... 16-4 Set Menu ........................................................................................................................................ 18-20
Types of Delay Calculators.................................................................................................................... 16-6 Customize Menu ............................................................................................................................ 18-22
Central Delay Calculator.................................................................................................................. 16-8 Tools Menu .................................................................................................................................... 18-24
Verilog and CDC ........................................................................................................................... 16-10 Help Menu ..................................................................................................................................... 18-26
Standard Delay Format ........................................................................................................................ 16-12 Setting Breakpoints in the VCW.................................................................................................... 18-28
SDF Example ................................................................................................................................. 16-14 The Language Sensitive Editor (LSE) ................................................................................................. 18-30
Running the SDF Annotator .......................................................................................................... 16-20 Invoking the LSE ........................................................................................................................... 18-32
Entry and Analysis Mode............................................................................................................... 18-34
Debug Mode................................................................................................................................... 18-36
Hierarchy Browser ............................................................................................................................... 18-38
The Verilog Results Analyzer (VRA).................................................................................................. 18-44
Lab 11 Using the Graphical Environment ........................................................................................... 18-49

x Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. xi
Verilog-XL Table of Contents

Appendix A Verilog-XL Twin Turbo Mode

Appendix B Statistical Modeling


What Is Statistical Modeling?..................................................................................................................B-4
Top-Down Modeling Levels....................................................................................................................B-6
Queues and Random Functions ...............................................................................................................B-8
A Simple Example .................................................................................................................................B-10
Probabilistic Distribution Functions ......................................................................................................B-12
Initializing a Queue................................................................................................................................B-14
Placing a Job in a Queue........................................................................................................................B-16
Processing a Job from the Queue...........................................................................................................B-18
Statistical Information about the Queue ................................................................................................B-20
Lab A Statistical Modeling ....................................................................................................................B-21

Appendix C Switch-Level Modeling


Advantages of Switch-Level Modeling ...................................................................................................C-4
Verilog Primitive Switches ......................................................................................................................C-6
Switch-Level Networks ...........................................................................................................................C-8
Switch Instantiation ...............................................................................................................................C-10
Delay Timing Models for Switches .......................................................................................................C-12
Strength Reduction.................................................................................................................................C-14
The Switch-XL Algorithm.....................................................................................................................C-16
Timing Model Conversion of Unidirectional Switches.........................................................................C-18
The Switch-XL Strength Model.............................................................................................................C-20
How to Invoke the Switch-XL Algorithm .............................................................................................C-22
The Switch-RC Algorithm.....................................................................................................................C-24
Timing Specification..............................................................................................................................C-28
Model Pull-Up/Pull-Down Ratio ...........................................................................................................C-30
Technical Advantages of Timing Accuracy ..........................................................................................C-32
State Dependent Delay...........................................................................................................................C-34
Delay Due to Side Path Capacitance .....................................................................................................C-36
Slope Dependent Delay..........................................................................................................................C-38
Invoking the Switch-RC Algorithm.......................................................................................................C-40
The Algorithms Major Features ...........................................................................................................C-42
Choosing an Algorithm..........................................................................................................................C-44
Lab B Switch-Level Modeling...............................................................................................................C-45

Appendix D Solution Files for Labs

Index

xii Cadence Design Systems, Inc. 6/29/95


Getting Started 1-1

Getting Started

Objectives
Review the course objectives.
Review the course schedule.
Understand the conventions followed in this book.
Learn about OpenBook, the Cadence online documentation utility.

Terms and Definitions

6/29/95 Cadence Design Systems, Inc. 1-2


Getting Started 1-3

Course Objectives

During this course you will gain knowledge on:


Verilog-HDL and Verilog-XL
Structural-level modeling and simulation
Behavioral modeling and simulation
Timing specification
Stimulus and control specification
Response generation and verification
Interactive debugging
Achieving optimal performance issues
Verilog environment

Course Objectives
These course objectives are mapped with the course schedule on the next page.

6/29/95 Cadence Design Systems, Inc. 1-4


Getting Started 1-5

Course Map

Getting Started Structural Modeling

Support for
Introduction
Verification

Day 1 Day 2
Sample Design Specify Blocks

Lexical Conventions Behavioral Modeling

Data Types Interactive Mode

Course Map

6/29/95 Cadence Design Systems, Inc. 1-6


Getting Started 1-7

Course Map

Continuous Modeling
Assignments ASIC Libraries

Modeling Delay Calculation


Memories Day 3 Day 4

Tasks and Improving


Functions Performance

Modeling for Verilog


Synergy Environment

Course Map

6/29/95 Cadence Design Systems, Inc. 1-8


Getting Started 1-9

Training Manual Conventions

Your training manual contains the materials you will use during the lecture.
It contains a copy of every overhead transparency presented by the
instructor (on the top of the page) along with written information pertaining
to these overheads (on the bottom of the page).
Some self-explanatory overheads may not have any explanation in the
lecture portion below them.
There is plenty of space so you can add your own notes.
The Verilog-XL training manual contains an index.
The term select is used in the training manual to describe clicking on a menu
or an icon with the left mouse button.

Training Manual Conventions

6/29/95 Cadence Design Systems, Inc. 1-10


Getting Started 1-11

Getting Help
You can get help with Cadence software from the following sources:

OpenBook
Customer Response Center (CRC)
You can call the Customer Response Center at 1-800-CADENC2
You can send email to crc_customers@cadence.com
The Verilog bulletin board talkverilog@cadence.com

Getting Help
Online Help
Cadence online reference manuals and online help files for each product are installed
automatically when you install the product. You can also order hard copies of the reference
manuals from Cadence. All these online documents are part of the OpenBook system. You
can access this material online in two ways.
You can quickly view relevant product information by clicking the help button on
windows and forms. The information helps you understand how to complete a form or
what you can do in the window.
You start OpenBook from a UNIX shell and search through all Cadence reference
manuals and online help systems installed with each product. You can also use
OpenBook to print the reference manuals.
Personal Contact
If you cannot find the necessary information using any of the above methods, you can
call the Customer Response Center at 1-800-CADENC2.
Talkverilog is an electronic bulletin board designed for Verilog users. Talkverilog is a
great way to share design tips and experiences with other Verilog users, and is
monitored by Verilog experts from Cadence. You can access talkverilog over the
Internet through the address talkverilog@cadence.com.

6/29/95 Cadence Design Systems, Inc. 1-12


Getting Started 1-13

OpenBook Online Documentation Utility


Displays
Online reference manuals
Known Problems and Solutions (KP&S or KPNS)
Product notes
Postinstallation configurations
Finds information using
Menus
Text search
Index search
Keywords
Allows creation of public or private electronic notes to supplement the
documentation.
Allows bookmarks.
Allows you to add your documents into the documentation hierarchy.

OpenBook Online Documentation Utility


In addition to the OpenBook menu, you can access documents by
Keyword
openbook install
This example opens the Cadence Installation Guide.
You can find the keywords by selecting Documents by Product Names from
OpenBook.
Text search
You can search through the entire document set.
You can restrict search to a group of documents, or a single document.
You can further restrict search by operators to locate groups of text in specific places
such as SENTENCE and PARAGRPAH.
Search examples:
analog AND workbench Find files containing both words, analog and
workbench
plot SENTENCE versa Find files containing both words, plot and versa, in
the same sentence
THESAURUS begin Find words meaning the same as begin

6/29/95 Cadence Design Systems, Inc. 1-14


Getting Started 1-15

OpenBook Online Documentation Utility (continued)


Displays
Online reference manuals
Known Problems and Solutions (KP&S or KPNS)
Product notes
Postinstallation configurations
Finds information using
Menus
Text search
Index search
Keywords
Allows creation of public or private electronic notes to supplement the
documentation.
Allows bookmarks.
Allows you to add your custom documents into the documentation
hierarchy.

OpenBook Online Documentation Utility (continued)


Notes and Bookmarks
You can create notes and attach them to OpenBook pages. Private notes are stored under
your login directory.
Note: Bookmarks and private notes are placed in
<login_directory>/fminit/fmpnotes/<install_dir>/doc/<document_path>/<login_name>
Example: /usr1/mnt/user2/fminit/fmpnotes/cds/doc/openbook/menus/support/user2
To create public notes, you need write access to the documentation hierarchy.

6/29/95 Cadence Design Systems, Inc. 1-16


Introduction and Basic Concepts 2-1

Introduction and Basic Concepts

Objectives
Understand the basics of Hardware Description Language (HDL) and
simulators.
Understand design methodologies.
Understand the Verilog language and the Verilog-XL software.

Terms and Definitions

Hardware Description A programming language that can describe the functionality


Language (HDL) and timing of hardware circuits.
Simulator It reads the HDL and emulates the hardware described by the
HDL.
Bottom-Up Design Flow The design methodology in which you build the low-level
components first and then connect them to make large
systems.
Top-Down Design Flow The design methodology in which you define the system at a
very high level of abstraction and refine it at the lower levels
of abstraction by partitioning the design into logical,
functional, or physical units.

6/29/95 Cadence Design Systems, Inc. 2-2


Introduction and Basic Concepts 2-3

Why Use an HDL?

It is becoming very difficult to design directly on hardware.


Exploring different design options is easier and cheaper.
Reduced time and cost versus prototyping.

Why Use an HDL?


As the complexity of systems increases, it becomes difficult to design directly on
hardware.
Exploring different design options is easier and cheaper, because you only need to
change the HDL description. It is much easier to change the description than to
reconfigure the prototype.
You can try different design options quickly and easily. The time to fix a design problem
is reduced and so is the cost.

6/29/95 Cadence Design Systems, Inc. 2-4


Introduction and Basic Concepts 2-5

Key Features of HDLs

HDLs have high-level programming language constructs and constructs to


describe the connectivity of the circuit.
HDLs allow you to describe the design at various levels of abstraction.
HDLs allow you to describe the functionality as well as the timing.
Concurrency
Time

Key Features of HDLs


Typically an HDL contains some high-level programming language constructs along
with constructs to describe the connectivity of the hardware design.
It allows you to describe the design at various levels of abstractions using Structural or
Behavioral constructs.
HDL allows you to describe the functionality of the hardware along with its timing
constraints.
Concurrency is the ability to perform multiple tasks at the same time. Typically,
programming languages are not concurrent, but in hardware a number of operations
happen at the same time. Thus, an HDL must be concurrent.
Typically, programming languages have no concept of time. In hardware, there are
delays associated in going from an input to an output. To model these delays in an HDL,
it needs to have the concept of time built in to it.

6/29/95 Cadence Design Systems, Inc. 2-6


Introduction and Basic Concepts 2-7

Simulation Algorithms

Time Driven
Event Driven
Demand Driven

The Verilog simulator is event driven.

Simulation Algorithms
Time Driven
Each circuit element is evaluated at each time point, producing a new circuit state at
that point of time.
Inefficient, because at any time only 2 to 10 percent of elements in a circuit need to
be evaluated.
Event Driven
Changes in circuit state are recorded. Only those elements that might cause a change
in circuit state, during a given time, are simulated. The simulation propagates values
forward, through the circuit, in response to input pin events.
Most practical and widely used simulation algorithm.
Efficient, because it evaluates when necessary.
Demand Driven
Further refines evaluates when necessary.
Evaluates nets and gates only when their values are needed to provide simulation
output.
Propagates requests for simulation values, backwards through circuit and time.

6/29/95 Cadence Design Systems, Inc. 2-8


Introduction and Basic Concepts 2-9

Time Wheel in Event-Driven Simulation

Event queues at each time stamp


t

t+1

Current Simulation
t+2 Time
Et
An event Et at time t
schedules another
event at time t+2 t+3

t+4

When the simulator compiles its data structures, it creates the initial queues
for the time wheel based on the HDL.
Time advances only when every event scheduled at that time is executed.
The time wheel can only go forward.

Time Wheel in Event-Driven Simulation


When the simulator compiles its data structures, it creates the initial queues for the time
wheel based on the HDL.
The simulation starts when the current simulation time is 0.
When all the events scheduled at time 0 are executed, the simulation time advances to
the next time step.
Events at each time step can append new events to event queues at a later time.

6/29/95 Cadence Design Systems, Inc. 2-10


Introduction and Basic Concepts 2-11

Different Levels of Abstraction

Architectural/Algorithmic
Register Transfer Logic (RTL)
Gate
Switch

Different Levels of Abstraction


Architectural/Algorithmic
The system is described in the terms of the algorithms it performs.
The aim is to study the data flow of the system and potential bottlenecks.
Register Transfer Logic (RTL)
Describes the flow of data and control signals within and between functional blocks.
Schedules assignments at clock edges.
Gate
Interconnection of switching elements (or gates) to check functionality, performance,
or timing of design.
Switch
Describes logic behavior of transistor circuits.
Evaluates conflicts caused by bidirectional pass transistors, signal strengths of
multiple elements driving a net, and so on.

6/29/95 Cadence Design Systems, Inc. 2-12


Introduction and Basic Concepts 2-13

Design Methodologies
Bottom-Up Design Flow
Design timing, performance,
4 and testability is analyzed.

REGISTER REGISTER
The complete design is
3 modeled and tested. ALU PC

STATE RAM

Intermediate level DFF DFF


...
2 components are modeled at
the gate level and tested.

Lowest level components are DFF


1 modeled at the gate level and
tested.

Bottom-Up Design Flow


Since bottom-up design closely follows the steps involved in breadboarding and building a
system using hardware only, bottom-up design is the traditional method.
The advantages to bottom-up design are:
Many designers already have the software and hardware required to design this way.
Designers are traditionally trained to work this way.
Less time is needed to implement individual pieces of the circuit.
The disadvantages to bottom-up design are:
Typically, there is a poor functional view of the entire system.
You need more time to implement the entire system, because you must complete
individual pieces first. In other words, concurrent engineering is more difficult with
bottom-up design methods.

6/29/95 Cadence Design Systems, Inc. 2-14


Introduction and Basic Concepts 2-15

Design Methodologies
Top-Down Design Flow

The top-level system is


modeled for functionality and
1 performance using a inputs CPU outputs
high-level behavioral
description.

Each major component is


modeled at the behavioral REGISTER REGISTER
2 level and the design is ALU PC
simulated again for STATE RAM
functionality and performance.

Each major component is


modeled at the gate level and REGISTER REGISTER
3 the design is simulated again ALU PC
for timing, functionality and STATE RAM
performance.

Top-Down Design Flow


Top-down design begins with a Verilog functional model of the top-level system. As the
individual partitions are modeled in more detail, they are plugged back into this
top-level functional description.
The advantages of top-down design are:
System analysis is done at the beginning of the design cycle. Therefore, quality and
performance trade-off decisions can be made at the earliest stage.
Strong connection between system-level engineering and implementation-level
engineering.
Concurrent engineering is facilitated. In other words, a number of engineers can work
on different parts of the design at the same time.
Typically, fewer design iterations are required; so time to market is reduced.
Increasingly large designs are easier to handle.
The disadvantages of top-down design are:
There is a learning curve involved, because its not as traditional as bottom-up
design.
Requires software and hardware capable of performing mixed-level simulations.

6/29/95 Cadence Design Systems, Inc. 2-16


Introduction and Basic Concepts 2-17

Design Methodologies
Typical Design Flow
The top-level system is modeled
for functionality and performance
1 using a high-level behavioral inputs CPU outputs

description.

Each major component is REGISTER REGISTER


modeled at the behavioral level
2 and the design is simulated again ALU PC
for functionality and performance. STATE RAM

Synthesis Domain
Each major component is
modeled using library REGISTER REGISTER
3 components or ASICs and the ALU PC
design is re-simulated for timing, STATE RAM
functionality and performance.

Library components are modeled DFF DFF


...
1 at the gate level (using data
books) and tested.

Typical Design Flow


The high-level system is designed using the top-down approach. Leaf cells from the data
book (or library components) are used for the low-level system.
Advantages are:
Using vendor-certified libraries.
All the advantages of bottom-up design and top-down design are utilized.

6/29/95 Cadence Design Systems, Inc. 2-18


Introduction and Basic Concepts 2-19

Verilog HDL and Verilog-XL

Verilog HDL
Hardware description language that allows you to describe circuits at different
levels of abstraction and allows you to mix any level of abstraction in the design.

Verilog-XL Software
High speed, event-driven simulator that reads Verilog HDL and simulates the
description to emulate the behavior of real hardware.

Verilog HDL and Verilog-XL Software

6/29/95 Cadence Design Systems, Inc. 2-20


Introduction and Basic Concepts 2-21

Verilog HDL

Verilog HDL is a functional verification and simulation language for digital


systems.
Verilog HDL was released to public domain in 1990 and is now maintained
by OVI.
Ability to mix different levels of abstraction freely.
One language for all the aspects of design, test, and verification.

Verilog HDL
Verilog HDL is a functional verification and simulation language for digital systems.
The Verilog language was released to the public domain in 1990 and is now controlled
by Open Verilog International (OVI).
It is very difficult to separate Verilog HDL from the Verilog-XL simulator, because
dynamically the language behaves the way the simulator works.
Ability to mix different levels of abstraction freely.
One language for all aspects of design, including test and verification of electronic
designs, therefore, only one language needs to be learned.

6/29/95 Cadence Design Systems, Inc. 2-22


Introduction and Basic Concepts 2-23

Key Language Features


Verilog Module

module SN74LS74 module DFF module ALU

endmodule endmodule endmodule

Key Language Features


Verilog Module
Modules are basic building blocks in hierarchy.
Verilog descriptions or models are placed inside modules.
Modules may represent:
a physical block like an IC or ASIC cell.
a logical block like the ALU portion of a CPU design.
the complete system.
Every module description starts with the keyword module, has a name (SN74LS74,
DFF, ALU, etc.) and ends with the keyword endmodule.
Modules define a new scope (level of hierarchy) in Verilog.

6/29/95 Cadence Design Systems, Inc. 2-24


Introduction and Basic Concepts 2-25

Key Language Features (continued)


Module Ports

module DFF (d, clk, clr, q, qb);


input d, clk, clr;
output q, qb;

d q
DFF

clk
qb

clr

endmodule

Key Language Features (continued)


Module Ports
Module ports are equivalent to the pins in hardware.
Modules communicate with the outside world through ports.
A module can have a list of ports that appear in parentheses after the module name.
You declare ports to be input, output or inout (bidirectional) in the module description.

6/29/95 Cadence Design Systems, Inc. 2-26


Introduction and Basic Concepts 2-27

Key Language Features (continued)


Module Instances

REG4
d clk clr
module REG4(d,clk,clr,q,qb);
output [3:0] q, qb;
input [3:0] d;
d0 d3
input clk, clr;
DFF DFF
...
DFF d0 (d[0],clk,clr,q[0],qb[0]);
DFF d1 (d[1],clk,clr,q[1],qb[1]);
DFF d2 (d[2],clk,clr,q[2],qb[2]);
q qb DFF d3 (d[3],clk,clr,q[3],qb[3]);
endmodule

module DFF (d, clk, clr, q, qb);


....
endmodule

Key Language Features (continued)


Module Instances
You can create larger systems or components by listing instances of other modules and
connecting those instances by their ports.
In this example, REG4 contains four instances of the module DFF. Note that each
module has its own instance name (d0, d1, d2 and d3). The instance name gives a unique
name to every object, and is used so that the internals of the instance can be examined.
Notice that the order of the ports in the instance follows the order in the module
definition. (Refer to the previous slide.)
A module instance is not the same as calling a routine, but each instance is a complete,
independent, and concurrently active copy of the module.

6/29/95 Cadence Design Systems, Inc. 2-28


Introduction and Basic Concepts 2-29

The Verilog-XL Simulator


Verilog-XL is a logic simulator.
The simulator was developed with the Verilog HDL software.
The Verilog-XL simulator offers very powerful debugging capabilities.
Verilog-XL is a very fast simulator at different levels of abstraction due to the
acceleration algorithms it incorporates.

The Verilog-XL Simulator


It is a logic-level simulator that you can use to:
determine feasibility of new design ideas.
try out more than one approach to a design problem.
verify functionality.
identify design errors.
The simulator was developed with the Verilog HDL software.
The Verilog-XL simulator offers very powerful debugging capabilities because it uses
the Verilog HDL as its debugging language.
It is a very fast simulator at different levels of abstraction due to the acceleration
algorithms it incorporates, for example: Turbo Algorithm, XL Algorithm, Switch-XL
Algorithm, caxl Algorithm.For more information about Verilog algorithms, For more
information, see the module "Modeling to Achieve Simulation Performance".

6/29/95 Cadence Design Systems, Inc. 2-30


Introduction and Basic Concepts 2-31

Related Products
Veritime is a timing analysis tool.
Verifault-XL is the fault simulator that uses Verilog HDL.
Synergy is the software that allows synthesis and optimization in a top-down
design process.

Related Products
Veritime is the timing analyzer.
Verifault-XL is the fault simulator that uses the Verilog HDL software.
Synergy is the software that allows synthesis and optimization in a top-down design
process.

6/29/95 Cadence Design Systems, Inc. 2-32


Sample Design 3-1

Sample Design
Objectives
Introduce Verilog structural and behavioral constructs.
Illustrate Verilog in mixed-level simulation.

Terms and Definitions

6/29/95 Cadence Design Systems, Inc. 3-2


Sample Design 3-3

A Simple and Complete Example

Test Fixture

Device Under Test


a
a1
Stimulus Response
and sel
Generation
Control out and
Verification
b b1

A Simple and Complete Example


The system consists of a 2:1 multiplexer described at the gate level, which is the Device
Under Test (DUT) and a test fixture, to provide a test stimulus and a verification
mechanism.
The test fixture will be described behaviorally and the DUT will be described at the gate
level to illustrate mixed-level simulation.

6/29/95 Cadence Design Systems, Inc. 3-4


Sample Design 3-5

Device Under Test

module MUX2_1 (out,a,b,sel);

// Port declarations
output out;
a input a,b,sel;
a1

sel sel_
// The netlist
out not (sel_, sel);
and (a1, a, sel_);
b b1
and (b1, b, sel);
or (out, a1, b1);

endmodule

Device Under Test


a, b and sel are the input ports of the device and out is the output port. All the signals
flow into and out of the module from these ports.
and, or, not are instances of predefined Verilog primitives. For more information on
Verilog primitives, see the module "Structural Modeling".
The keywords module and endmodule totally encompass the 2:1 Multiplexer
implementation.
The module name and the port declarations of the multiplexer are the only things needed
by other modules that use this module. No knowledge of underlying implementation is
necessary. This is an important feature for the top-down design methodology, because
a module implementation can change from behavioral level to gate level without
affecting any of the higher-level modules using it.

6/29/95 Cadence Design Systems, Inc. 3-6


Sample Design 3-7

Test Fixture Template

module testfixture; Why are there no ports for the


Test Fixture?

// Data type declaration

// Instantiate modules

// Apply stimulus

// Display results

endmodule

Test Fixture Template

6/29/95 Cadence Design Systems, Inc. 3-8


Sample Design 3-9

Test Fixture Making an Instance

module testfixture;

//Data type declaration

//MUX instance
MUX2_1 mux (out, a, b, sel);

//Apply stimulus

//Display results

endmodule

Test Fixture Making an Instance

6/29/95 Cadence Design Systems, Inc. 3-10


Sample Design 3-11

Test Fixture Describing Stimulus


(Procedural Blocks)

Procedural blocks are of two types


initial procedural blocks
always procedural blocks

initial c always c
c c
c c
c c
c c
c c
c c
c c

Test Fixture Describing Stimulus


Procedural blocks are used often during behavioral modeling. The stimulus part of the test
fixture also must be specified inside a procedural block. For more information, see the module
"Behavioral Modeling".
Procedural blocks are of two types
initial procedural blocks, which execute only once.
always procedural blocks, which execute in a loop.

6/29/95 Cadence Design Systems, Inc. 3-12


Sample Design 3-13

Activation Versus Execution of Procedural Blocks

All procedure blocks are activated at time 0.


Procedural blocks are not triggered or executed until the enabling condition
evaluates to TRUE.
All procedural blocks execute concurrently.

initial c always c
c c
c c
c c
c c
c c
c c
c c

Conditions of Execution

Activation Versus Execution of Procedural Blocks

All procedure blocks are activated at time 0, waiting to be executed based upon the user
specific conditions.
Procedural blocks are not triggered or executed until the enabling condition evaluates to
TRUE. In absence of the condition, the execution immediately follows the activation.
All procedural blocks execute concurrently, thus allowing you to model the inherent
concurrence in hardware.

6/29/95 Cadence Design Systems, Inc. 3-14


Sample Design 3-15

Test Fixture Describing Stimulus


module testfixture;
//Data type declaration
reg a, b, sel;
//MUX instance
MUX2_1 mux (out, a, b, sel);
//Apply stimulus time values
initial a b sel
begin 0 0 1 0
a = 0; b = 1; sel = 0; 5 0 0 0
#5 b = 0;
#5 b = 1; sel = 1; 10 0 1 1
#5 a = 1; 15 1 1 1
#5 $finish;
end
//Display results
endmodule

Test Fixture Describing Stimulus


In the example above, a, b, and sel are declared as a reg data type. Abstract registers
retain their value until reassigned. For more information on data types, see the module
"Verilog Data Types and Logic System".
#5 is used to specify waiting for 5 time units.
$finish is a system task that ends simulation.

6/29/95 Cadence Design Systems, Inc. 3-16


Sample Design 3-17

Test Fixture Response Generation


Verilog provides you with a number of system tasks and system functions.
$time is a system function that returns the current simulation time.
$monitor is a system task that displays the values of the argument list
whenever any of the arguments change.
$monitor (<<format_specifier>?, argument>+)

For example:
$monitor($time,,out,,a,,b,,sel);
$monitor($time, %b %h %d %o, sig1, sig2, sig3, sig4);

Test Fixture Response Generation


$time is a system function that returns the current simulation time. The $time system
function returns time as a 64-bit integer.
$monitor displays the values of the argument list whenever any of the arguments change
at the end of the time step. It is not, however, triggered by the change in value caused by
$time.
The $monitor system task supports different bases. The default base is decimal, but
other supported bases are binary, hexadecimal and octal.

$monitor (<<format_specifier>?, argument>+)

6/29/95 Cadence Design Systems, Inc. 3-18


Sample Design 3-19

A Complete Test Fixture


module testfixture;
reg a, b, sel;
//MUX instance
MUX2_1 mux (out, a, b, sel);
//Apply stimulus
initial
begin
a = 0; b = 1; sel = 0;
#5 b = 0;
#5 b = 1; sel = 1;
#5 a = 1;
#5 $finish;
end
//Display results
initial
$monitor($time,out=%b a=%b b=%b sel=%b,out,a,b,sel);
endmodule

A Complete Test Fixture


The multiplexer instance consists of
Name of the parent module
Name of the instance
Port list which matches the ports of the parent module
Stimulus is generally applied at the behavioral level. For more information on applying
stimulus and displaying results, see the module "Support for Verification".

6/29/95 Cadence Design Systems, Inc. 3-20


Sample Design 3-21

cWaves
The cWaves Window
Status line

Pull-down
menus

Signal Waves
descriptor region
region
Fixed
menu
icons

Time
region

Baseline Cursor Marker

The cWaves Window


The cWaves window consists of the following:
The status line at the top displays information about the current database, and updates
whenever you open a new database.
The pull-down menu banner below the status line offers editing, viewing and placing
marker commands.
The fixed menu icons along the left edge of the window offer commands to cut and
paste, delete, print, zoom, and move waveforms.
The waves region in the center of the window displays your waveforms.
The signal descriptor region to the left of the waves region is where the signal names
appear.
The time region is at the bottom edge of the window. It is used to display a single time
span from simulation history.

6/29/95 Cadence Design Systems, Inc. 3-22


Sample Design 3-23

Getting Started with cWaves


You enter the system tasks into the Verilog-XL description prior to
simulation.
$shm_open("waves.shm");
$shm_probe();
$shm_close;
$shm_save;

Example:
initial
begin
$shm_open("lab.shm");
$shm_probe();
#1 $stop;// Stop simulation at time 1
end

Getting Started with cWaves


You can use a set of system tasks to open the database, probe signals, and save the results
to the waveform database. You can also use the Verilog environment to probe signals
interactively. For more information on using cWaves with the Verilog environment see
the module "The Verilog-XL Graphical Environment".
You enter the system tasks into the Verilog-XL description prior to simulation.
$shm_open("waves.shm");
Opens the connection to a waveform database.
$shm_probe();
Selects signals whose simulation value changes enter the waveform database.
$shm_close;
Terminates a connection to a database.
$shm_save;
Saves a waveform database to disk.

6/29/95 Cadence Design Systems, Inc. 3-24


Sample Design 3-25

Getting Started with cWaves (continued)

Examples of node specifiers


$shm_probe();
Specifies all the inputs, outputs, and inouts in the current scope.
$shm_probe("A");
Specifies ALL the nodes in the current scope.
$shm_probe(alu,adder);
Specifies all the inputs, outputs, and inouts in the modules alu and adder.
$shm_probe("S", top.alu,"AS");
Specifies:
All the inputs, outputs, and inouts in the current scope, and below,
excluding those in library cells
All the nodes in the top.alu module and below, excluding those in library
cells.

Getting Started with cWaves (continued)

Node Specifiers for cWaves

Node
Signals that Enter the Database
Specifier
none Inputs, outputs, and inouts of the named module instance or the current scope
"A" All nodes contained in the named module instance, or the current scope
(including the inputs, outputs and inouts)
"S" Inputs, outputs, and inouts of the named module instance or the current scope,
and of instantiations lower in the hierarchy than the named module instance,
except for library cells
"C" Inputs, outputs, and inouts of the named module instance or the current scope,
and of instantiations lower in the hierarchy than the named module instance,
including library cells
"AS" All the nodes in the named instance or the current scope (including the inputs,
outputs and inouts), and in all instantiations below it, except inside library
cells
"AC" All the nodes in the named instance or the current scope (including the inputs,
outputs and inouts) and in all instantiations below it, even inside library cells
6/29/95 Cadence Design Systems, Inc. 3-26
Sample Design 3-27

Starting cWaves and Opening a Database


cWaves allows you to display signals in a graphical window.
You can invoke cWaves from:
A UNIX window. This runs cWaves in stand alone mode.
cwaves &
The Verilog environment menus
You can load waveforms into cWaves, with the following menu command:
FileLoad Data

Starting cWaves and Opening a Database


cWaves allows you to display signals in a graphical window.
You can invoke cWaves from:
The UNIX window. This will run cWaves stand-alone.
The Verilog environment menus. For more information on the Verilog environment see
the module "The Verilog-XL Graphical Environment".
You can load waveforms into cWaves from any database created by the SHM (Simulation
History Manager). To load waveforms into cWaves, use the following menu command:
FileLoad Data
Type the path to the SHM database, type the database name, and type the server host name (if
other than the local host).

6/29/95 Cadence Design Systems, Inc. 3-28


Sample Design 3-29

Saving the cWaves Environment

Saving the cWaves Environment


To save the cWaves environment use the FileSave Setup menu command and fill in the
form. The saved file can then be restored later, using the FileRestore Setup menu
command.

6/29/95 Cadence Design Systems, Inc. 3-30


Sample Design 3-31

Starting the Verilog-XL Software

% verilog <command_line_options> <design_files>


<command_line_options>

Command Line Option Action


-f <file_name> Read commands from the file <file_name>.
-d Decompile the Verilog description.

<design_files> are files that contain Verilog descriptions.


Example of the -f command-line option:
run.f
verilog mux.v test.v
or mux.v
verilog -f run.f test.v

Starting the Verilog-XL Software

You start the Verilog-XL software by typing verilog on the command line, along with some
command line options and the names, of the files that you want to simulate.

6/29/95 Cadence Design Systems, Inc. 3-32


Sample Design 3-33

Labs

Lab 1 Getting Started


Using OpenBook to Access Online Documentation
Running Verilog on a Sample Design
Using Stand-alone cWaves with Verilog-XL

6/29/95 Cadence Design Systems, Inc. 3-34


Lexical Conventions in Verilog 4-1

Lexical Conventions in Verilog


Objectives
Understand the lexical conventions used in the Verilog language.
Learn to recognize special language tokens.

Terms and Definitions

white space Any of the following: blank spaces, tabs, newlines.


identifier A name given to a Verilog object such as a module or port.

6/29/95 Cadence Design Systems, Inc. 4-2


Lexical Conventions in Verilog 4-3

White Spaces and Comments


module MUX2_1 (out,a,b,sel);
// Port declarations
output out;
input a,b,sel;
/*
The netlist logic selects input a when sel = 0 and it
selects b when sel = 1
*/
not (sel_,sel);
and (a1,a,sel_), (b1,b,sel);
or (out,a1,b1);

endmodule

White Spaces and Comments


Verilog is a free-format language.
You can use white space to enhance the readability and organization of code.
The Verilog language ignores these characters, except when they serve to separate other
language tokens.
Single-line comments begin with // and end with a new line character.
Multiple-line comments start with /* and end with */.

6/29/95 Cadence Design Systems, Inc. 4-4


Lexical Conventions in Verilog 4-5

Integer and Real Numbers


Numbers can be integers or real numbers.
Integers can be sized or unsized. Sized integers are represented as
<size><base><value>
where
<size> is the size in bits.
<base> can be b(binary), o(octal), d(decimal) or h(hexadecimal)
<value> is any legal number in the selected base and x,z,?

Real numbers can be represented in decimal or scientific format.


12 - unsized decimal
H83a - unsized hexadecimal
8b1100_0001 - 8-bit binary
64hff01 - 64-bit hexadecimal
9O17 - 9-bit octal
2B1? - 2-bit binary number with lsb at high impedance
32bz - 32-bit Z(X and Z values are automatically extended)
6.3 - decimal notation
32e-4 - scientific notation for 0.0032
4.1E3 - scientific notation for 4100.0

Integer and Real Numbers


Underscores (_) in numbers are ignored.
Integers can be sized or unsized for example, the width of the number in bits is specified
in sized integers. In unsized integers, size defaults to 32 bits.
If the <base> is not selected in an unsized number, it defaults to decimal.
Sized integers are represented as
<size><base><value>
where
<size> is the size in bits.
<base> can be b(binary), o(octal), d(decimal) or h(hexadecimal)
<value> is any legal number in the selected base and x,z,?
<base> and <value> are case insensitive.
A question mark (?) in the number is interpreted as a high impedance.
Real numbers can be represented in scientific notation or decimal notation.
Real numbers in scientific notation are represented as
<mantissa>[eE]<exp> which is interpreted as <mantissa> * 10<exp>

6/29/95 Cadence Design Systems, Inc. 4-6


Lexical Conventions in Verilog 4-7

Strings

Strings are enclosed in double quotes and must be specified on one line.
Verilog recognizes normal C escape Characters (\t, \n, \\, \ and %%).
Strings are used frequently to generate formatted output from Verilog.
A new line using a carriage return can not be used in strings.

This is a normal string


This is a string with a \t tab and a new line at the end\n
This is a formatted string: value = %b

Strings
C escape characters
\t = tab
\n = newline
\\ = backslash
\ = quote mark ()
%% = % sign

6/29/95 Cadence Design Systems, Inc. 4-8


Lexical Conventions in Verilog 4-9

Identifiers

Identifiers are user-provided names for Verilog objects within a description.


Identifiers must begin with an alphabetical character (a-z, A-Z) or an
underscore (_) and can contain any alphanumeric character, dollar signs
($), and the underscore.
Identifiers can be up to 1023 characters long.
Names of modules, ports and instances are identifiers.

module MUX2_1 (out,a,b,sel);


output out;
input a,b,sel;
Verilog Identifiers
not not1(sel_,sel);
and and1(a1,a,sel_);
and and2(b1,b,sel);
or or1(out,a1,b1);
endmodule

Identifiers
Examples of legal identifiers
shift_reg_a
busa_index
_bus3
Examples of illegal identifiers
34net // Does not begin with an alphabetical character or _
a*b_net // Contains a non-alphanumeric character
n@238

6/29/95 Cadence Design Systems, Inc. 4-10


Lexical Conventions in Verilog 4-11

Escaped Identifiers

Escaped identifiers start with backslash (\) and end with white space.
They can contain any printable ASCII character.
Backslash and the white space are not part of the identifier.

module \2:1MUX (out,a,b,sel);


output out;
Escaped Identifiers
input a,b,sel;
not not1(\~sel ,sel);
and and1(a1,a,\~sel );
and and2(b1,b,sel);
or or1(out,a1,b1);
endmodule

Escaped Identifiers

Examples of escaped identifiers


\~#@sel
\busa+index
\{A,B}
top.\3inst .net1 //escaped identifer in a hierarchical name.
Important
You must end the escaped identifier with a space.

6/29/95 Cadence Design Systems, Inc. 4-12


Lexical Conventions in Verilog 4-13

Case Sensitivity

Verilog is a case-sensitive language.


All keywords are lowercase.
You can run Verilog in case-insensitive mode by specifying -u at the
command line.

module MUX2_1 (out,a,b,sel);


output out;
input a,b,sel;
not not1(SEL,sel);
and and1(a1,a,SEL);
and and2(b1,b,sel);
or or1(out,a1,b1);
endmodule

What happens if the above model is run in case-insensitive mode?

Case Sensitivity
Verilog is a case-sensitive language. For example, identifiers that do not match in case
are considered unique.
All Verilog keywords are in lower case. For example, you type input, not INPUT.
You can run Verilog in the case-insensitive mode by specifying -u at the command line.
All identifiers are then converted to upper case, but the keywords remain in lower case.

6/29/95 Cadence Design Systems, Inc. 4-14


Lexical Conventions in Verilog 4-15

Special Language Tokens


System Tasks and Functions

$<identifier>
$ sign denotes Verilog system tasks and functions
A number of system tasks and functions are available to perform different
operations such as
Finding the current simulation time ($time)
Displaying/monitoring the values of the signals ($display, $monitor)
Stopping the simulation ($stop)
Finishing the simulation ($finish)

$monitor($time, a = %b, b = %h, a, b);

Note:For more information on system tasks and functions , see the module "Support for
Verification".

Special Language Tokens


System Tasks and Functions
$<identifier>

$monitor($time, a = %b, b = %h, a, b);

Every time signals a or b change value, this system task displays the values of the current
simulation time; signal a in binary format, and signal b in hexadecimal format.
The default base is decimal.

6/29/95 Cadence Design Systems, Inc. 4-16


Lexical Conventions in Verilog 4-17

Special Language Tokens (continued)


Delay Specification

#<delay specification>
The pound sign (#) character denotes the delay specification for both gate
instances and procedural statements.

module MUX2_1 (out,a,b,sel);


output out;
input a,b,sel;
not #1 not1(sel_,sel);
and #2 and1(a1,a,sel_);
and #2 and2(b1,b,sel);
or #1 or1(out,a1,b1);
endmodule
Note:Delay specifications will be discussed in detail later.

Special Language Tokens (continued)


Delay Specification
#<delay_specification>

6/29/95 Cadence Design Systems, Inc. 4-18


Lexical Conventions in Verilog 4-19

Compiler Directives
You indicate compiler directives with a grave accent ().
These directives cause the Verilog-XL compiler to take some special action.
Compiler directives remain active until overridden or deactivated.
Theresetall compiler directive resets all the compiler directives to their
default values (only if there is a default value).


`protect file1.v `protect file1.v

Active
regions
file2.v for protect `endprotect file3.v


`endprotect
file3.v file2.v

Verilog-XL Verilog-XL

Compiler Directives
You indicate compiler directives with a grave accent ().
These directives cause the Verilog-XL compiler to take special action.
Compiler directives remain active across source files.
A compiler directive is active from the point that it is encountered in the source stream
until it is deactivated or overridden by another compiler directive.
A good modeling practice is to have a resetall compiler directive before calling any
other compiler directives, because it resets all the compiler directives to their default
values (only if there is a default value).

6/29/95 Cadence Design Systems, Inc. 4-20


Lexical Conventions in Verilog 4-21

Text Substitution
Thedefine compiler directive provides a simple text-substitution facility.
define <name> <macro_text>
<name> will substitute <macro_text> at compile time.
Typically used to make the description more readable.

define not_delay #1
Definition of not_delay
define and_delay #2
define or_delay #1
module MUX2_1 (out,a,b,sel);
output out; Use of not_delay
input a,b,sel;
not not_delay not1(sel_,sel);
and and_delay and1(a1,a,sel_);
and and_delay and2(b1,b,sel);
or or_delay or1(out,a1,b1);
endmodule

Text Substitution

The `define compiler directive provides a simple text-substitution facility.


`define name macro_text
`name will substitute macro_text at compile time.
macro_text is any arbitrary text specified on the same line as name.
The define compiler directive can be used to:
make the description more readable
define global design parameters, like delays and widths of vectors, in a single place.
The advantage is that to change the configuration, you only need to make changes at
one place.
define shorthand strings to define Verilog commands.
`define vectors_file "/usr/mnt/user1/library/vectors"
`define results_file "/usr/mnt/user1/library/results"
A list of define directives can be placed in a single file and the file is compiled with the
other design files.
verilog definitions.v mux.v
Caution
A syntax error in the text macro gives you an error at the point where the text macro is used.

6/29/95 Cadence Design Systems, Inc. 4-22


Lexical Conventions in Verilog 4-23

+define+
The +define+ command line plus argument can be used to define macro
names as strings.
The option has the following syntax when it defines a macro name as a
string:
+define+<MACRO_NAME>="<MACRO_STRING>"
For example:
verilog +define+gate="or" test.v
module test;
define gate and
reg a,b;
gate (c,a,b);
initial
begin
a=0; b=1;
$monitor ($time,,c,a,b);
$finish;
end
endmodule

+define+
If you simulate the code in the above example with a command line that does not include
a +define+ option, the value of c fluctuates because the compiler directive defines
macro gate as an and gate. If you include the following +define+ option in the command
line, the value of c remains constant because the option defines gate as an or gate.
+define+gate="or"
When a command line +define+ option overrides a `define macro definition,
Verilog-XL displays a warning similar to this.
Warning! Text macro (gate) not-redefined, using value
from command line. (or) [Verilog-TMOVR]
"/net/ashley/home/def1.v", 2:

Note: The warning indicates that the option redefines the macro, regardless of the fact that the text in the warning
is inconclusive.
You can define a macro name to be a string of any length with the +define+ option.
There is no limit on the number of +define+ macros that you define.

6/29/95 Cadence Design Systems, Inc. 4-24


Lexical Conventions in Verilog 4-25

Text Inclusion

Use the include compiler directive to insert the contents of an entire file.
include "global.v"
include "parts/count.v"
include "../../library/mux.v"

Use the +incdir command-line option to specify the search directories for
the file to be included.
+incdir+<directory1>+<directory2>+. . .<directoryN>

You can useinclude to


include global or commonly used definitions.
include tasks without encapsulating repeated code within module
boundaries.

Text Inclusion

You can use theinclude compiler directive to insert the contents of an entire file.
include "<file_name>"
<file_name> is the name of the file that is to be included.
<file_name> can be a relative or full UNIX path.
Search directories, for the file_name to be included, can be specified using the +incdir
command-line option. Verilog will first look for the file in the current directory and then
it will search the directories in the order that they are listed on the command line with
the +incdir option.
You can nestinclude up to a maximum of eight levels.
You can useinclude to
include global or commonly used definitions which can be stored in a separate file.
Typically, the file containingdefine commands is included.
include tasks without encapsulating repeated code within module boundaries, so that
maintenance of the code becomes easier.

6/29/95 Cadence Design Systems, Inc. 4-26


Lexical Conventions in Verilog 4-27

Timescale in Verilog
The timescale compiler directive declares the time unit and its precision.
timescale 1 ns / 100 ps
The timescale compiler directive cannot appear inside a module
boundary.
Simulation speed is greatly affected if there is a large difference between the
time units and precision.
timescale 1 ns / 10 ps
// All the time units are in multiples of 1 nanosecond
module MUX2_1 (out,a,b,sel);
output out;
input a,b,sel;
not #1 not1(sel_,sel);
and #2 and1(a1,a,sel_);
and #2 and2(b1,b,sel);
or #1 or1(out,a1,b1);
endmodule

Timescale in Verilog

The timescale compiler directive declares the time unit and its precision.
timescale <time_unit> / <time_precision>
<time_unit> specifies the units of measurement for delays and time.
<time_precision> tells Verilog how to round delay values before using them in
simulation.
The <time_precision> must be at least as precise as the <time_unit>.
The <time_precision> and <time_unit> both consist of an integer and a character string
representing the magnitude and the unit respectively. The valid integers are 1, 10, and
100. The valid unit strings are s(second), ms(milisecond), ns(nanosecond),
us(microsecond), ps(picosecond), and fs(femtosecond). Any combination of these is
allowed.
The simulation speed is greatly reduced if there is a large difference between the time
units and the precision because the timewheel advances by the multiples of the
precision. For example, if we have timescale 1s/1ps, then to advance 1 second, the
timewheel scans its queues 1012 times versus a timescale 1s/1ms where it needs to scan
these queues only 103 times.

6/29/95 Cadence Design Systems, Inc. 4-28


Lexical Conventions in Verilog 4-29

Timescale in Verilog (continued)

The smallest precision of all the timescale directives determines the time unit of
the simulation.
timescale 1ns/10ps
module1 (. . .);
. . .
Simulation takes place
endmodule
in units of 100fs,
timescale 100ns/1ns that is, the timewheel
module2 (. . .); will advance in
. . . multiples of 100fs.
endmodule

timescale 1ps/100fs
module3 (. . .);
. . .
endmodule

Timescale in Verilog (continued)


The smallest precision of all the timescale directives determines the time unit of the
simulation, because the simulator needs to preserve the smallest precision specified in
the design.
The first timescale indicates that the time units for module1 are in multiples of 1 ns
and it is precise till 10 ps. Thus it sets the smallest timestep for the simulator as 10 ps.
The second timescale directive sets the time units for module2 in multiples of 100 ns
and it is precise till 1 ns. Since 1 ns is greater than 10 ps, the smallest simulator
timestep remains 10 ps.
The third timescale directive sets the time units for module3 in multiples of 1 ps and
it is precise till 100 fs. Since 100 fs is smaller than 10 ps, the smallest simulator
timestep now becomes 100 fs.

6/29/95 Cadence Design Systems, Inc. 4-30


Verilog Data Types and Logic System 5-1

Verilog Data Types and Logic System


Objectives
Learn the Verilog logic value system.
Learn the various classes of data types in Verilog.
Understand how and where each class of data type is used.
Learn the various Verilog strengths.
Learn the declaration syntax.

Terms and Definitions

6/29/95 Cadence Design Systems, Inc. 5-2


Verilog Data Types and Logic System 5-3

4-Value Logic System in Verilog

buf
Zero, Low, False, Logic Low, Ground,
0 VSS, Negative Assertion

buf
One, High, True, Logic High, Power,
1 VDD, VCC, Positive Assertion

X, Unknown: Occurs at Logical


X Conflict Which Cannot be Resolved

bufif1
HiZ, High Impedance, Tri-Stated,
Z Disabled Driver (Unknown)
0

4-Value Logic System in Verilog

6/29/95 Cadence Design Systems, Inc. 5-4


Verilog Data Types and Logic System 5-5

The Three Unknown Logic Values

a
a b s0 s1 out
s0
x x 0 0 z
out
0 x 1 0 0
x 0 0 x L (0 or z)
x 1 0 x H (1 or z)
b
0 1 1 1 x
s1

The Three Unknown Logic Values

Verilog has three unknown logic values


X represents a complete unknown. Value can be logic 1, 0 or Z.
L represents a partial unknown. Value can be logic 0 or Z but not 1.
H represents a partial unknown. Value can be logic 1 or Z but not 0.

6/29/95 Cadence Design Systems, Inc. 5-6


Verilog Data Types and Logic System 5-7

Major Data Type Classes

Nets
Registers
Parameters

Major Data Type Classes


Nets
Represent physical connection between devices.
Registers
Represent abstract storage devices.
Parameters
Declare run-time constants.

6/29/95 Cadence Design Systems, Inc. 5-8


Verilog Data Types and Logic System 5-9

Nets

Nets are continuously driven by the devices that drive them.


Verilog automatically propagates a new value onto a net when the drivers
on the net change value.

a
a1

sel

out

b b1

Nets

Nets
Nets are continuously driven by the devices that drive them. In the example, net out is
driven by the or gate.
Verilog automatically propagates a new value onto a net when the drivers on the net
change value. This means that, whatever value is on the or gate, will be automatically
driven onto the net out.

6/29/95 Cadence Design Systems, Inc. 5-10


Verilog Data Types and Logic System 5-11

Types of Nets
Various net types are available for modeling design-specific and
technology-specific functionality.
Net Types Functionality
wire, tri For standard interconnection wires
(default)
wor, trior For multiple drivers that are Wire-ORed
wand, triand For multiple drivers that are Wire-ANDed
trireg For nets with capacitive storage
tri1 For nets which pull up when not driven
tri0 For nets which pull down when not driven
supply1 For power rails
supply0 For ground rails

Nets that are not declared explicitly default to single bit nets of type wire.
This can be overridden by using the default_nettype <nettype> compiler
directive.

Types of Nets

Various net types are available for modeling design-specific and technology-specific
functionality.
Net types tri and wire are identical in functionality. You can use the different names to
enhance readability. For example, you can use tri for the nets that have multiple drivers.
Another reason to declare a net as a tri is to indicate that this net can be driven to a high
impedance state.
Nets that are explicitly not declared, default to a single-bit wire. You can override this
by using the default_nettype <nettype> compiler directive. With this directive, all the
nets not declared explicitly will default to the <nettype> in the compiler directive.

6/29/95 Cadence Design Systems, Inc. 5-12


Verilog Data Types and Logic System 5-13

Logic Conflict Resolution with Net Data Types

Wire/Tri Wand/Triand Wor/Trior

b b b
a 0 1 x z a 0 1 x z a 0 1 x z
0 0 x x 0 0 0 0 0 0 0 0 1 x 0
1 x 1 x 1 1 0 1 x 1 1 1 1 1 1
x x x x x x 0 x x x x x 1 x x
z 0 1 x z z 0 1 x z z 0 1 x z
y y y

Logic Conflict Resolution with Net Data Types

Verilog has predefined net resolution functions.


Technology dependent logic conflict resolution is supported.
wired-AND for open collector
wired-OR for ECL

6/29/95 Cadence Design Systems, Inc. 5-14


Verilog Data Types and Logic System 5-15

Registers

A register holds its value until a new value is assigned to it.


Registers are used extensively in behavioral modeling and in applying
stimuli.
Values are applied to registers using behavioral constructs.

a
reg_a a1

sel
reg_sel
out

reg_b b1
b

Registers
A register holds its value until a new value is assigned to it.
Registers are used extensively in behavioral modeling and in applying stimuli. In the
example above, reg_a, reg_b and reg_sel are used to apply stimuli to the 2:1
multiplexer.
Values are applied to registers from procedural blocks which are behavioral constructs.

6/29/95 Cadence Design Systems, Inc. 5-16


Verilog Data Types and Logic System 5-17

Types of Registers

The register class consists of four data types.

Register Functionality
Types
reg Unsigned integer variable of varying bit width
integer Signed integer variable, 32-bits wide. Arithmetic
operations produce 2s complement results.
real Signed floating-point variable, double precision
time Unsigned integer variable, 64-bits wide (Verilog-XL
stores simulation time as a 64-bit positive value.)

Register data types are not to be confused with structural storage elements.

Types of Registers

reg is the most common register type. You can declare it to be scalar or vector. A reg is
closely associated with hardware.
You typically use integer for manipulations of quantities that are not regarded as
hardware.
real has the same usage as integer, except that you use it for real numbers.
time stores and manipulates simulation time quantities.

6/29/95 Cadence Design Systems, Inc. 5-18


Verilog Data Types and Logic System 5-19

Declaration Syntax of Verilog Nets and Registers

Net Declaration
<nettype> <range>? <delay_spec>? <<net_name> <, net_name>*>

Register Declaration
<register_type> <range>? <<register_name> <, register_name>*>

Examples
reg a; // A scalar register
wand w; // A scalar net of type wand
reg [3:0] v; // A 4-bit vector register from msb to lsb
reg [7:0] m,n; // Two 8-bit registers
tri [15:0] busa; // A 16-bit tri-state bus
wire [0:31] w1, w2; // Two 32-bit wires with msb = 0

Declaration Syntax of Verilog Nets and Registers


Net Declaration
<nettype> <range>? <delay_spec>? <<net_name> <, net_name>*>
<nettype> is the type of the net.
<range> is the vector range. It is in the following format [msb:lsb]
<delay_spec> defines the delay associated with the net.
<net_name> is the net. You can declare more than one net in the same declaration
by using a list of names separated by commas.

Register Declaration
<register_type> <range>? <<register_name> <, register_name>*>
<register_type> is the type of the register.
<range> is the vector range. It is allowed for reg only.
<register_name> is the register. You can declare more than one register in the same
declaration by using a list of names separated by commas.

6/29/95 Cadence Design Systems, Inc. 5-20


Verilog Data Types and Logic System 5-21

Choosing the Correct Data Type

Module Boundary

Input Port Output Port


net/register net net/register net

net
Inout Port

net

Choosing the Correct Data Type


An input port can be driven by a net or a register, but it can only drive a net.
An output port can be driven by a net or a register, but it can only drive a net.
An inout port can be driven by a net, and it can only drive a net.
If a signal is assigned value from a procedural block, then it must be declared as a
register.

6/29/95 Cadence Design Systems, Inc. 5-22


Verilog Data Types and Logic System 5-23

Common Mistakes in Choosing Data Types

Listed here are common user errors, along with their typical error messages.
When a procedural assignment is made to a net or you forget to declare a
signal as a reg:
Illegal left-hand-side assignment
Signal connected to the output port is a register:
Gate has illegal output specification
Illegal output port specification
Signal connected to the input port is a register:
Incompatible declaration, (signal) defined as input

Common Mistakes in Choosing Data Types

6/29/95 Cadence Design Systems, Inc. 5-24


Verilog Data Types and Logic System 5-25

Parameters

Use parameters to declare run-time constants.


You can use a parameter anywhere that you can use a literal.

module mod1(out,in1,in2);
. . .
parameter p1 = 8,
real_constant = 2.039,
x_word = 16bx,
file = /net/usr/design/mem_file.dat;
. . .
wire [p1:0] w1; // A wire declaration using parameter
. . .
endmodule

Parameters
Use parameters to declare run-time constants. They are not variables.
Typically, you use parameters to define delays and widths of variables.
You can use a parameter anywhere that you can use a literal.
Parameter definition syntax is
parameter <list_of_assignments>
where <list_of_assignments> is a comma-separated list of parameters and their values.

6/29/95 Cadence Design Systems, Inc. 5-26


Verilog Data Types and Logic System 5-27

Overriding the Values of Parameters


Defparam Statement
module mod1(out,in1,in2);
. . .
parameter p1 = 8,
real_constant = 2.039,
x_word = 16bx,
file = /net/usr/design/mem_file.dat;
. . .
endmodule

module p_values;
...
mod1 I1(out,in1,in2);
defparam
I1.p1 = 6,
I1.file = ../my_mem.dat;
...
endmodule

Overriding the Values of Parameters


Defparam Statement
The values of parameters can be overridden at compile time by reassigning them using
the defparam statement.
The defparam statement must refer to the hierarchical name of the parameter.
Any parameter value can be overridden by calling a defparam statement on that
parameter.

6/29/95 Cadence Design Systems, Inc. 5-28


Verilog Data Types and Logic System 5-29

Overriding the Values of Parameters (continued)


Module Instance Parameter Value Assignment

module mod1(out,in1,in2);
. . .
parameter p1 = 8,
real_constant = 2.039,
x_word = 16bx,
file = /net/usr/design/mem_file.dat;
. . .
endmodule

module top;
...
mod1 #(5, 3.0, 16bx, ../my_mem.dat) I1(out,in1,in2);
...
endmodule

Overriding the Values of Parameters (continued)


Module Instance Parameter Value Assignment
Parameter values can be assigned new values within a module instance using the #
character.
The specification is similar to the primitive instance delay specification.
The order of assignment of the parameters follows the order of declaration of parameters
in the module.
It is not necessary to assign new values to all parameters, but it is not possible to skip
over a parameter.

6/29/95 Cadence Design Systems, Inc. 5-30


Structural Modeling 6-1

Structural Modeling
Objectives
Learn how to use the Verilog primitives.
Building a hierarchical design.
Delays in Verilog primitives.
Using library cells in Verilog models.

Terms and Definitions

Structural Modeling Describing the functionality of a device in terms of gates.


Verilog Primitives Language-defined functional models for simple logic functions.

6/29/95 Cadence Design Systems, Inc. 6-2


Structural Modeling 6-3

Structural Modeling

A structural model represents a schematic in HDL.


A model is created using existing components.

r module rs_ff (y, yb, r, s);


y
output y, yb;
input r, s;
nor n1(y, r, yb);
yb nor n2(yb, s, y);
s endmodule

Structural Modeling
A structural model is equivalent to a schematic. You connect simple components to
create a more complex component. In order to accomplish this, you use connectivity
constructs of the HDL.
When you use components to create another model, you create instances of these
components.

6/29/95 Cadence Design Systems, Inc. 6-4


Structural Modeling 6-5

Verilog Primitives

Verilog primitive gates provide basic logic functions.


Integral part of the bottom-up design methodology in Verilog.
Primitives are acceleratable.

Primitive Name Functionality


and Logical And
or Logical Or
not Inverter
buf Buffer
xor Logical Exclusive Or
nand Logical And Inverted
nor Logical Or Inverted
xnor Logical Exclusive Or Inverted

Verilog Primitives
Verilog provides basic logical functions as predefined primitives therefore, the user does
not have to define this basic functionality.
Most of the ASIC libraries are developed using Verilog primitives and hence form an
integral part of the bottom-up design methodology.
Verilog-XL simulates the predefined primitives with XL algorithms; hence, their
simulation is very fast.

6/29/95 Cadence Design Systems, Inc. 6-6


Structural Modeling 6-7

Primitive Pins Are Expandable

The number of pins for the primitive gate is defined by the number of nets
connected to it.

in1 out
and (out, in1, in2);
in2

in1 out
in2 and (out, in1, in2, in3);
in3

in1
in2 out
in3 and (out, in1, in2, in3, in4);
in4

Primitive Pins Are Expandable

The number of pins for the primitive gate is defined by the number of nets connected to
it. Thus, you do not need to redefine a new logical function whenever the number of
inputs or the outputs of a logical function change.
All gates except not and buf can have a variable number of inputs, but only a single
output.
The not and buf gates have variable number of outputs, but only one input.

6/29/95 Cadence Design Systems, Inc. 6-8


Structural Modeling 6-9

Conditional Primitives

Verilog has four different types of conditional primitives.


They are enabled and disabled by the control pin.
They have only three pins.

Primitive Name Functionality


bufif1 Conditional buffer with logic 1 as enabling input
bufif0 Conditional buffer with logic 0 as enabling input
notif1 Conditional inverter with logic 1 as enabling input
notif0 Conditional inverter with logic 0 as enabling input

bufif1 bufif0

a out a out

e e
bufif1 (out, a, e) bufif0 (out, a, e)

Conditional Primitives

Verilog has four conditional primitives.


They are enabled and disabled by the control pin.
They have only three pins: output, input and control.
When they are disabled, their output is at high impedance.

6/29/95 Cadence Design Systems, Inc. 6-10


Structural Modeling 6-11

Primitive Instantiation

Optional instance name.


Optional delay specification.
You must specify outputs before inputs.

and (out, in1, in2, in3, in4);


buf b1 (out1, out2, in);
notif0 #3.1 n1 (out, in, cntrl);

Primitive Instantiation
It is optional to specify an instance name for a primitive instantiation.
You can specify an optional delay to define the intrinsic delay of the primitive. In other
words, a signal will take the specified delay time before a change in input is reflected at
the output. Without the delay specification, the primitive operates at zero delay.
You must specify all the outputs of the primitive before inputs to the primitive.
Examples of primitive instantiation
and a1 (out, in[1], in[2]); // Bits of nets in port list.
or #2.0 (out, a, b); // Instance with no name but delay specified.
not (inv1, inv2, in_net); // Instance driving multiple outputs.
not (inv1[1], in_net[1]); // Single bit driving a single vector bit.

6/29/95 Cadence Design Systems, Inc. 6-12


Structural Modeling 6-13

Module Instantiation
A module instantiation must have an instance name.
In position mapping port order follows the module declaration , but in named
mapping, it is independent of the position.

module comp1 (o1, o2, i1, i2);


output o1, o2;
input i1, i2;
. . .
endmodule

module test;
comp1 c1(out1,out2,in1,in2); // Positional Mapping
comp1 c2 (.i2(xx),.i1(yy),.o2(zz),.o1(tt)); // Named Mapping
comp1 c3 (Q,,J,K); // One port left unconnected
endmodule

Module Instantiation
A module instantiation must have an instance name.
Port order follows the module port declaration in position mapping.
Named mapping is independent of the position. You refer to the ports by their names and
specify the nets you want to connect the ports to. The syntax is
.actual_port_name(net_connected_to_port)
You can leave a port unconnected in a module instantiation, but it results in a warning
from Verilog.

6/29/95 Cadence Design Systems, Inc. 6-14


Structural Modeling 6-15

Delay Specification in Primitives

Delay specification defines the intrinsic delay through the primitive gate.
Verilog allows (rise, fall, turn-off) delays to be specified on primitives.
These delays can be specified as (minimum : typical: maximum) delays.
By default, Verilog primitives use typical delay values and the inertial delay
algorithm.
While simulating, Verilog uses only one of these delays, which is specified
by the following command line options:

+mindelays +typdelays +maxdelays

bufif0 #(3,3,7) (out, in, ctrl); // Rise, Fall, Turn-off


and #(2,3) (out, in1, in2); // Rise, Fall
or #(3.2:4.0:6.3) o1(out, in1, in2, in3); // min:typ:max
// Rise min:typ:max, Fall min:typ:max
nand #(1.0:1.2:1.5, 2.3:3.5:4.7) n1(out, in1, in2, in3);

Delay Specification in Primitives


Delay specification defines the intrinsic delay through the primitive gate. Any change in
the inputs is reflected at the output only after this delay. Without the delay specification,
the delay on the primitive is 0.
Verilog allows rise, fall and turn-off delays to be specified on primitives. The turn-off
delays are valid for only the tristatable primitives.
Rise delays are the delays associated with transitions to 1.
Fall delays are the delays associated with transitions to 0.
Turn-off delays are the delays associated with transitions to high Z.
These delays can be specified as minimum, typical, and maximum delays. However,
while simulating, Verilog uses only one of these delays, which is specified by the
following command-line options.
+maxdelays instructing Verilog to simulate with maximum delay values
+typdelays instructing Verilog to simulate with typical delay values
+mindelays instructing Verilog to simulate with minimum delay values
By default, Verilog primitives use typical delay values and the inertial delay algorithm.

6/29/95 Cadence Design Systems, Inc. 6-16


Structural Modeling 6-17

Logic Strength Modeling

Verilog provides multiple levels of logic strengths.


Logic strength modeling resolves combinations of signals into known or
unknown values to represent the behavior of the hardware with maximum
accuracy.

Logic Strength Modeling


Popular examples:
Open collector output (pullup required)
Multiple tri-state drivers to a single node
MOS charge storage
ECL Gates (emitter dotting)

6/29/95 Cadence Design Systems, Inc. 6-18


Structural Modeling 6-19

Signal Strength Value System


Strength Values %v formats Specification mnemonics
7 Supply Drive Su0 Su1 supply0 supply1
6 Strong Drive (default) St0 St1 strong0 strong1
5 Pull Drive Pu0 Pu1 pull0 pull1
4 Large Capacitive La0 La1 large
3 Weak Drive We0 We1 weak0 weak1
2 Medium Capacitive Me0 Me1 medium
1 Small Capacitive Sm0 Sm1 small
0 High Impedance Hi0 Hi1 highz0 highz1

Syntax for gate strength specification:


<gate> <drive_strength> #(300,500) (out,x,y);
where <drive_strength> is
(<strength0>,<strength1>) or (<strength1>,<strength0>)
The strength and logic value of a net can be displayed using the %v format
specifier.
$monitor ($time,,"f output = %v", f);

Signal Strength Value System


Syntax for gate strength specification:
<gate> <drive_strength> #(300,500) (out,x,y);
where <drive_strength> is
(<strength0>,<strength1>) or (<strength1>,<strength0>)
The strength and logic value of a net can be displayed using the %v format specifier.
$monitor ($time,,"f output = %v", f);

6/29/95 Cadence Design Systems, Inc. 6-20


Structural Modeling 6-21

Verilog Resolves Ambiguous Strength

weak1, strong0
Logic Unknown

Resolve Logic Conflict


weak1 with strong0 -> strong0
x strong0 with strong0 -> strong0
highz with strong0 -> strong0
x out

strong1, strong0 bufif1 (weak1, strong0) (out,in1,en1);


Logic 0 notif1 (out, in2,en2);

Verilog Resolves Ambiguous Strength

6/29/95 Cadence Design Systems, Inc. 6-22


Structural Modeling 6-23

Verilog Model Libraries

Verilog has a large base of vendor-supplied libraries.


Each library component contains functionality and timing information.
Such a component is known as a cell.
The designer creates a netlist that has instances of the components in a
library.
Verilog reads the model libraries to search for the instantiated models at
compile time.

Verilog Model Libraries


Verilog has a large base of vendor-supplied libraries which provide the designer with
the functionality of the basic and commonly used models with the vendor-specific
technology.
Each library component contains the functionality and the vendor-specific timing
information.
Each component is encompassed between celldefine and endcelldefine and is known
as a cell. Cells are used by delay calculators.

6/29/95 Cadence Design Systems, Inc. 6-24


Structural Modeling 6-25

Verilog Model Libraries (continued)

Each component must be modeled as a separate module.


All modules may be placed in one library file.
Each module may be a different file and placed in a library directory.
Libraries need to be scanned during compilation using -v or -y options.

Verilog Model Libraries (continued)


Each component must be modeled as a separate module.
All modules may be placed in one library file.
Each module may be a different file and placed in a library directory. In this case, the
name of the file must be same as the name of the module plus an optional extension.
Libraries need to be scanned during compilation using -v or -y options so that only the
models used in the design are compiled with the design. Otherwise compiling the entire
library unnecessarily increases the size of the simulation database.
The -v option scans a library file.
verilog test.v design.v -v library_file

6/29/95 Cadence Design Systems, Inc. 6-26


Structural Modeling 6-27

Verilog Model Libraries (continued)


The -v option scans a library file.
verilog test.v design.v -v library_file
The +liborder option directs Verilog-XL to scan libraries in a circular fashion.
verilog file1.v -v lib1.v file2.v -v lib2.v +liborder

Verilog Model Library File

module and2(...);
...
endmodule

module mux(...);
...
endmodule

module dff(...);
...
endmodule

Verilog Model Libraries (continued)


The -v option scans a library file.
verilog test.v design.v -v library_file
The +liborder option directs Verilog-XL to scan libraries as they follow on the
command line and then wrap around to previous libraries that Verilog has not yet
scanned.
verilog source1.v -v lib1.v source2.v -v lib2.v +liborder

6/29/95 Cadence Design Systems, Inc. 6-28


Structural Modeling 6-29

Verilog Model Libraries (continued)


The -y option scans the library directory.
verilog test.v design.v -y library_directory
Verilog uses +libext+ to specify that the filename has a .v extension.
verilog test.v design.v -y library_directory +libext+.v

Verilog Model Library Directory


and2.v
module and2(...);
...
endmodule dff.v
module dff(...);
...
mux.v endmodule
module mux(...);
...
endmodule

Verilog Model Libraries (continued)


The -y option scans the library directory.
verilog test.v design.v -y library_directory
Verilog uses +libext+ to specify that the filename has a .v extension.
verilog test.v design.v -y library_directory +libext+.v

6/29/95 Cadence Design Systems, Inc. 6-30


Structural Modeling 6-31

Verilog Model Libraries (continued)

The `uselib compiler directive specifies where Verilog-XL searches for the
definitions of modules and UDPs instantiated in a design description that
does not include those definitions.
Each `uselib directive explicitly defines the library search that resolves the
instances that follow it until the compiler encounters another `uselib
directive or a `resetall.
If the design description includes no `uselib compiler directives, the compiler
looks to the command line for the options to configure the library search.
The syntax for `uselib is:
<uselib_compiler_directive>::= `uselib <library_reference>*
Use the +define+ command line option and the define compiler directive to
define the paths with which the uselib compiler directive configures the
search.

Verilog Model Libraries (continued)


The `uselib compiler directive specifies where Verilog-XL searches for the definitions
of modules and UDPs instantiated in a design description that does not include those
definitions.
Each `uselib directive explicitly defines the library that resolves the instances that
follows it, until the compiler encounters another `uselib directive, which completely
redefines the search. If the design description includes no `uselib compiler directives,
the compiler looks to the command line for options to configure the library search.
An empty `uselib directive makes the preceding `uselib directives ineffective.
It is efficient to use the +define+ command line option and the `define compiler directive
to define the paths with which the `uselib compiler directive configures the search. This
practice enables you to use brief macro names in the `uselib compiler directives
anywhere in the design description. This localizes the search paths for easy alteration,
which increases portability.
If you define the same macro with both a compiler directive and a command line option,
the command line option takes precedence and Verilog-XL displays a warning message.

6/29/95 Cadence Design Systems, Inc. 6-32


Structural Modeling 6-33

Example of the `uselib Compiler Directive


define LIB_ROOT /net/lib
define TTL_LIB dir=LIB_ROOT/TTL_LIB/source libext=.v
define TTL_UDP file=LIB_ROOT/TTL_LIB/udp.v
define FAST_LIB dir=LIB_ROOT/FAST/source libext=.v

module board (in,out,bus);


input [142:0] in;
output [39:0] out;
inout [127:0] bus;

uselib TTL_LIB
SN7400 U1 (clear,in[0],int_clear);
SN7404 U2 (clear_bar,clear);
uselib TTL_LIB TTL_UDP
SN7474 U3 (slave, ,data0,set_bar,clear_bar);
uselib FAST_LIB
SN7400 U4 (out[3],data0,data1);
endmodule
resetall

Example of the `uselib Compiler Directive


The first `define directive defines a macro that is incorporated in the others. The first
`uselib directive specifies that search for the definitions of the U1 and U2 devices. The
second `uselib directive adds a path to the first one to specify the search for the definition
of U3. Adding the path requires a new `define directive, because each `define directive
completely redefines the search. The second `define directive can specify the search for
devices U1, U2, and U3.
The last `uselib directive defines a search path for an instantiation that has the same
name as the first instantiation, but the different path enables Verilog-XL to find the
correct definition. The `resetall compiler directive has the same effect as an empty
`uselib directive; it makes the compiler look to the command line to configure the library
search. In addition, the `resetall compiler directive makes any other compiler directives
that precede it ineffective.
The `uselib directive can make a multiple line specification when you use the backslash
character (\), as the following lines show.
`uselib file=/net/machine/home/foo.lib \
dir=/net/machine/home libext=.v

6/29/95 Cadence Design Systems, Inc. 6-34


Structural Modeling 6-35

Labs
Lab 2 Structural Modeling
Modeling an 8-bit Register with Design Hierarchy Using Library
Components

6/29/95 Cadence Design Systems, Inc. 6-36


Support for Verification 7-1

Support for Verification


Objectives
Understand text and graphic outputs from Verilog.
Understand different system functions to read simulation time.
Understand file I/O in Verilog.

Terms and Definitions

12/7/95 Cadence Design Systems, Inc. 7-2


Support for Verification 7-3

Support for Verification

Verilog has system functions to read the current simulation time.


$time
$stime
$realtime

Verilog has system tasks to support text output.


$display
$strobe
$write
$monitor

Verilog has system tasks to support graphic output.


cWaves

Support for Verification

All the system tasks are called from the procedural blocks or interactive mode.

Note: For more information on interactive mode, see the module "Interactive Debugging in Verilog".

12/7/95 Cadence Design Systems, Inc. 7-4


Support for Verification 7-5

Reading Simulation Time

The $time, $realtime, and $stime functions return the current simulation
time.
Each of these functions returns a value that is scaled to the time unit of the
module that invoked it.
$time returns time as a 64-bit integer.
$stime returns time as a 32-bit integer.
$realtime returns time as a real number.

Reading Simulation Time


$time, $realtime, and $stime are system functions that return the current simulation time.
Each of these functions returns a value that is scaled to the time unit of the module that
invoked it.
$time returns time as a 64-bit integer.
$stime returns time as a 32-bit integer. For times greater than 232, the value returned is
expressed in 232 modulus. It is most often used in $monitor and $display to save space on the
printed line.
$realtime returns time as a real number.

12/7/95 Cadence Design Systems, Inc. 7-6


Support for Verification 7-7

Accessing Time Information

You can use the $timeformat system task and the %t formatter to globally control
how time values are displayed.
$timeformat(<unit>,<precision>,<suffix>,<min_width>)

timescale 10ns / 100ps


module top;
reg in1;
The output for this
not m1(o1,in1); example will be
similar to: 180.00 ns
initial
begin
$timeformat(-9,2," ns",10);
in1 = 0;
#8 in1 = 1;
#10 $display("%t %b %b",$realtime,in1,o1);
#10 $finish;
end
endmodule

Accessing Time Information


When using multiple timescale compiler directives, displayed values are scaled to the
smallest precision.
You can use the $timeformat system task and the %t formatter to globally control the
display of time values.
Syntax of the $timeformat system task:
$timeformat(<unit>,<precision>,<suffix>,<min_width>);
<unit> - integer between 0 (s) and -15 (fs) indicating time scale
<precision> - number of decimal digits to display
<suffix> - string to display after time value
<min_width> - minimum field width used for display
The $time system function returns the time as an integer and rounds the value to the time
unit of the module.
The $realtime returns the time as a real number, to retain all decimal digits.

12/7/95 Cadence Design Systems, Inc. 7-8


Support for Verification 7-9

Printing Time Information


The following is an example of printing time information.
timescale 1 ns / 10 ps
module top;
reg in1;
not #9.53 n1 (o1,in1);
initial
begin
$display(" time realtime stime \t in1 \t o1 " );
$monitor("%d %t %d \t %b \t %b",
$time,$realtime,$stime,in1,o1);
$timeformat(-9,2, "ns", 10); Results
in1 = 0;
#10 in1 = 1;
#10 $finish; time realtime stime in1 o1
end 0 0.00ns 0 0 x
endmodule 10 9.53ns 10 0 1
10 10.00ns 10 1 1
20 19.53ns 20 1 0

Printing Time Information

12/7/95 Cadence Design Systems, Inc. 7-10


Support for Verification 7-11

Displaying Signal Values

$display prints out the current values of the signals in the argument list.
$display automatically prints a new line.
$display supports different bases.

$display($time, %b \t %h \t %d \t %o, sig1, sig2, sig3, sig4);


$display($time, %b \t, sig1, %h \t, sig2, %d \t, sig3, %o, sig4);
$display(sig1, sig2, sig3, sig4);
$displayb(sig1, sig2, sig3, sig4);
$displayo(sig1, sig2, sig3, sig4);
$displayh(sig1, sig2, sig3, sig4);

Displaying Signal Values


$display
$display prints out the current values of the signals in the argument list whenever they
are encountered in the source description.
$display automatically prints a new line after printing the argument list.
$display supports different bases. The default base is decimal but the other supported
bases are binary, hexadecimal and octal.
$display(<<format_specifier>, argument>+)
$display(<format_specifiers>, <argument_list>)

The format specifiers supported in the command are


h o d b c s v m
hex octal decimal binary ASCII string strength module

The escaped literals that are supported


\t \n \\ \ \ddd
tab new line backslash double quote 1-3 digit octal number

12/7/95 Cadence Design Systems, Inc. 7-12


Support for Verification 7-13

Displaying Signal Values (continued)

$write is identical to $display except that it does not print a new line
character.
$write($time, %b \t %h \t %d \t %o \n, sig1, sig2, sig3,
sig4);
$write($time, %b \t, sig1, %h \t, sig2, %d \t, sig3, %o
\n, sig4);

$strobe is identical to $display except that the argument evaluation is


delayed just prior to the advance of simulation time.
$strobe($time, %b \t %h \t %d \t %o, sig1, sig2, sig3, sig4);
$strobe($time, %b \t, sig1, %h \t, sig2, %d \t, sig3,
%o, sig4);

Both $write and $strobe support multiple default bases as $display.

Displaying Signal Values (continued)


Argument list of $write and $strobe is of identical format as $display.

$write
$write displays the values of the argument list when it is encountered in the source
description but does not print a new line character automatically as $display does.
$write supports different bases.
$writeb
$writeo
$writeh

$strobe
$strobe delays the argument evaluation just prior to the advance of the simulation time.
As a result of the $strobe, steady state values of the signals are obtained; this is different
from $display and $write, which can print the intermediate value of the signal.
$strobe supports different bases.
$strobeb
$strobeo
$strobeh
12/7/95 Cadence Design Systems, Inc. 7-14
Support for Verification 7-15

Displaying Signal Values (continued)


module textio;
reg flag;
reg [31:0] data;
initial
begin
$writeb(%d, $time,,%h \t, data,, flag, \n);
#15 flag = 1; data = 16;
$displayh($time,, data,, flag); In what base will
time be printed?
end
initial
begin
#10 data = 20;
$strobe($time,,data); What are the values
printed by $strobe
$display($time,,data); and $display?
data = 30;
end
endmodule

Displaying Signal Values (continued)


Example
From writeb 0 xxxxxxxx x
From display 10 20
From strobe 10 30
From displayh 000000000000000f 00000010 1

12/7/95 Cadence Design Systems, Inc. 7-16


Support for Verification 7-17

Monitoring Signal Values

$monitor displays the values of the argument list whenever any of the
arguments change.
Any subsequent $monitor overrides the previous call to $monitor.
Continuous monitoring can be controlled by $monitoron and $monitoroff
system tasks.
$monitor supports different default bases.
$monitor($time, %b \t %h \t %d \t %o, sig1, sig2, sig3,
sig4);
$monitor($time, %b \t, sig1, %h \t, sig2, %d \t, sig3,
%o, sig4);

Monitoring Signal Values


$monitor
$monitor displays the values of the argument list whenever any of the arguments change
at the end of the time step. It is, however, not triggered by the change in value caused by
$time, $stime, $realtime.
Any subsequent $monitor overrides the previous call to $monitor. The signals in the
argument list of the new $monitor will be monitored and those in the previous $monitor
will not.
Continuous monitoring can be controlled by $monitoron and $monitoroff system tasks.
This is useful when the designer is interested in the signal values only between a certain
time intervals of the simulation.
The argument list of $monitor is identical to the argument list of $display.
$monitor supports different default bases
$monitorb
$monitoro
$monitorh

12/7/95 Cadence Design Systems, Inc. 7-18


Support for Verification 7-19

File Output in Verilog


$fopen opens the file specified as a parameter and returns a 32-bit unsigned
multichannel descriptor that is uniquely associated with the file. It returns 0 if the
file could not be opened for writing.

$fopen("<name_of_file>")
$fclose(<multichannel_descriptor>);

Each of the four formatted display tasks$display, $write, $monitor, and


$strobehas a counterpart that writes to specific files as opposed to the log file
and standard output.

$fdisplay(<multi_channel_descriptor>, P1, P2, ... , Pn);


$fwrite(<multi_channel_descriptor>, P1, P2, ... , Pn);
$fstrobe(<multi_channel_descriptor>, P1, P2, ..., Pn);
$fmonitor(<multi_channel_descriptor>, P1, P2, ..., Pn);

File Output in Verilog


The function $fopen opens the file specified as a parameter and returns a 32-bit unsigned
multichannel descriptor that is uniquely associated with the file. It returns 0 if the file could
not be opened for writing.
The $fclose system task closes the channels specified in the multichannel.
Each of the four formatted display tasks$display, $write, $monitor, and $strobehas a
counterpart that writes to specific files as opposed to the log file and standard output. These
counterpart tasks$fdisplay, $fwrite, $fmonitor, and $fstrobeaccept the same type of
parameters as the tasks they are based upon, with one exception: The first parameter must be
a multichannel descriptor that indicates where to direct the file output. A multichannel
descriptor is either a variable or the result of an expression that takes the form of a 32-bit
unsigned integer value. This value determines which open files the task will write to.
The multichannel descriptor should be thought of as a set of 32 flags, where each flag
represents a single output channel. The least significant bit (bit 0) of a multichannel descriptor
always refers to the standard outputthat is, the log file and the screen (unless it has been
redirected to a file). The standard output is also called channel 0. The other bits refer to
channels that have been opened by the $fopen system function.

12/7/95 Cadence Design Systems, Inc. 7-20


Support for Verification 7-21

File Output in Verilog (continued)

. . .
integer messages,broadcast,cpu_chann,alu_chann;
initial
begin
cpu_chann = $fopen("cpu.dat"); if(cpu_chann == 0) $finish;
alu_chann = $fopen("alu.dat"); if(alu_chann == 0) $finish;
messages = cpu_chann | alu_chann;
// includes standard output and verilog.log
broadcast = 1 | messages;
end
// at every positive edge of clock print the following line to alu.dat
always @(posedge clock)
$fdisplay(alu_chann, "acc= %h f=%h a=%h b=%h",acc,f,a,b);

/* at every edge of reset print the following line to alu.dat, cpu.dat,


the standard output and verilog.log */
always @(reset)
$fdisplay(broadcast, "system reset at time %d", $time);
. . .

File Output in Verilog (continued)


All the formatted text output system tasks have their counterparts that write to one or
more user-specified files and optionally write to standard output files.
The file I/O system tasks start with f followed by the name of the system task and take
an additional argument which is the Multi-Channel Descriptor (MCD).
MCD is declared as an integer and it gets a pointer to the file as the return value of the
$fopen system task.

12/7/95 Cadence Design Systems, Inc. 7-22


Specify Block 8-1

Specify Blocks
Objectives
Specify path delays.
Specify timing checks for a module.

Terms and Definitions

Module Path A path across module is known as a module path. It connects


module input (an input or an inout port) with module output (an
output or an inout port).
Path Delay Delay associated with a particular path.
Timing Check Monitor the relationship between two input signals to ensure that
the circuit operates correctly.

12/7/95 Cadence Design Systems, Inc. 8-2


Specify Block 8-3

Features of a Specify Block

A specify block defines the timing section of the module in a separate block.
Typical tasks you perform inside a specify block
Describe various paths across the module and assign delays to those
paths.
Describe timing checks.
A specify block is bounded by the keywords specify and endspecify.
Parameters are declared using the specparam keyword in a specify block.

Features of a Specify Block


A specify block defines the timing section of the module in a separate block. As a result,
the functional verification becomes independent of the timing verification. It is the key
component of timing-driven design, because this block that contains the timing
information can remain unchanged at different levels of abstraction.
Typical tasks you perform inside a specify block
Describe various paths across the module and assign delays to those paths.
Describe timing checks which would ensure that the timing constraints of the device
are met.
A specify block is bounded by the keywords specify and endspecify, and must appear
within a module boundary.

12/7/95 Cadence Design Systems, Inc. 8-4


Specify Block 8-5

Delay Modeling Options


1
noror ASIC cell Lump all the delay
at the last gate
A
B
a1
O
C

2
Distribute the delay
across each gate 3
Use a specify block
to specify pin-to-pin
delays for each path.

Typical delay specification


Delay from A to O = 2
Delay from B to O = 3
Delay from C to O = 1

Delay Modeling Options


Lump delay on the last gate driving the output.
Easy to model
Inaccurate
Distribute delays across the gates.
Need to solve a set of simultaneous equations
delay1 + delay2 = 2 or 3
delay2 = 1
delay1 = 1 or 2
More accurate than lumped delay methodology
More work
Inconsistent set of simultaneous equations
Path delays
Verilog constructs enable the path delays to be specified for delays between all
transitions of 0, 1 and Z
Exactly match the delay specification

12/7/95 Cadence Design Systems, Inc. 8-6


Specify Block 8-7

Module Path Delays

module noror(O, A, B, C);


output O;
input A, B, C;

nor n1 (net1, A, B);


or o1 (O, C, net1);

specify
(A => O) = 2;
(B => O) = 3;
(C => O) = 1;
endspecify
endmodule

Module Path Delays


Module Path Delay Examples
(a, b *> out1) = 2.2; // Path delay specified from a and b to out.

(r *> o1, o2) = (1, 2); // Rise and Fall delay for r to o1 and o2.

// Delay specified for all the paths for each vector of a and o.
(a[7:0] *> o[7:0]) = 6.3;

// Rise, Fall, and Turn off delays specified using specparameters.


(in => out) = (t_rise, t_fall, t_toz);

// Rise and Fall delays specified in min:typ:max format.


(in => out) = (1.2:1.4:1.6, 2.1:2.3:2.5);

12/7/95 Cadence Design Systems, Inc. 8-8


Specify Block 8-9

Parallel Versus Full Connection Module Paths

(a, b *> q, qb) = 12:15:18; *> signifies full connections. All the
inputs connect to all the outputs.
is equivalent to
(a => q) = 12:15:18;
=> signifies parallel connection and
(b => q) = 12:15:18;
can be between two scalar or two
(a => qb) = 12:15:18; vectors of same size.
(b => qb) = 12:15:18;

Delays for all the paths are 12:15:18

You can explicitly define transitions between 0, 1, and Z.


Syntax
(<inputs> => <outputs>)=(<0->1>,<1->0>,<0->Z>,<Z->1>,<1->Z>, <Z->0>);

Example
(C => Q) = (5, 12, 17, 10, 6, 22);

Parallel Versus Full Connection Module Paths

12/7/95 Cadence Design Systems, Inc. 8-10


Specify Block 8-11

Specify Block Parameters

module noror(O, A, B, C);


output O;
input A, B, C;

nor n1 (net1, A, B);


or o1 (O, C, net1);

specify
specparam ao = 2,
bo = 3, co = 1;

(A => O) = ao;
(B => O) = bo;
(C => O) = co;
endspecify
endmodule

Specify Block Parameters


The keyword specparam declares parameters within specify blocks. They are called
specify parameters or specparams, to distinguish them from module parameters. Unlike
specify parameters, module parameters are declared outside the specify block with the
keyword parameter. You cannot use module parameters in specify blocks.The following
summarizes the differences between the two types of parameter declarations.
SPECPARAMS
Use keyword specparam
Must be declared inside specify blocks
May only be used inside specify blocks
Cannot use defparam to override values
Save memory because they are not replicated with each module instance
PARAMETERS
Use keyword parameter
Must be declared outside specify blocks
Cannot be used inside specify blocks
Use defparam to override values
Use memory because they are replicated with each module instance

12/7/95 Cadence Design Systems, Inc. 8-12


Specify Block 8-13

Restrictions on Module Paths

All the destinations of a module path must be driven by a gate.


Verilog Error Message
Error! Path delay output is not accelerated due to. . .
. . .[Verilog-PDOMBA<number>]

Path destinations can have only one driver inside the module.
Verilog Error Message
Error! Multiple path delays defined to node <path_destination>;
Path delay outputs must have only one driver within the module
[Verilog-PDOMOD]

Restrictions on Module Paths

All the destinations of a module path must be acceleratable. Verilog issues an error
message if the destination is not a Verilog primitive or if it is driven by behavioral
Verilog code.
Path destinations can have only one driver inside the module. When wired logic is the
path destination, Verilog issues an error message because you have more than one
driver.
You can remove these errors by buffering the output. Insert the buf primitive between
the destination of the module path and the driver.

12/7/95 Cadence Design Systems, Inc. 8-14


Specify Block 8-15

Inertial Versus Transport Delay Models


Verilog by default supports the inertial delay mode.
In inertial delay mode, Verilog does not transmit the pulses with a duration
that is shorter than the switching time of the circuit.
In transport delay mode, every change at the input is reflected at the output.

Inertial Versus Transport Delays

in out

delay=2

in Note rejection of pulses which


Inertial
are shorter than intrinsic delay
out

Transport Note one-to-one transport of


out input changes to output changes

Inertial Versus Transport Delay Models


By default, Verilog supports the inertial delay mode.
In inertial delay mode, Verilog does not transmit the pulses with a duration that is shorter
than the switching time of the circuit. This characterizes the behavior of switching
circuits.
In transport delay mode, every change at the input is reflected at the output. This
characterizes the behavior of transmission lines.

12/7/95 Cadence Design Systems, Inc. 8-16


Specify Block 8-17

Path Pulse Control Options


Transport mode: +transport_path_delays
verilog +transport_path_delays source.v
Pulse control for specific modules and module paths: +pathpulse and
PATHPULSE$
<pulse_control_specparam>
::=PATHPULSE$=<r_value>,<e_value>;
||=PATHPULSE$<module_path_source>$
<module_path_destination>=<r_value>,<e_value>;

specify
(clk => q) = 12;
(data => q) = 10;
(clr, pre *> q) = 4;
specparam
PATHPULSE$ = 3;
PATHPULSE$clk$q = ( 2, 9 ) ;
PATHPULSE$clr$q = 1 ;
endspecify

Path Pulse Control Options


Transport mode: +transport_path_delays
In Verilog-XL version 2.1 and later versions, module path delays have unlimited
transport delay functionality. To make use of this functionality, you must invoke
Verilog with the +transport_path_delays command line plus option.
Pulse control for specific modules and module paths: +pathpulse and PATHPULSE$
You can override global pulse control by declaring specialized specparams that use the
prefix PATHPULSE$. The PATHPULSE$ specparam narrows the scope of module
path pulse control to a specific module or to particular paths within modules. The
command line must include the +pathpulse option in order for the PATHPULSE$
specparams to be effective.
Note: The +pathpulse command line option adds significant compilation overhead.

12/7/95 Cadence Design Systems, Inc. 8-18


Specify Block 8-19

Path Pulse Control Options (continued)

Global path pulse control: +pulse_r/m and +pulse_e/n


verilog source.v +pulse_r/50 +pulse_e/80

Path Pulse Control Options (continued)


Global path pulse control: +pulse_r/m and _pulse_e/n
The +pulse_r/m and +pulse_e/n plus options set global module path pulse control in
Verilog-XL. By setting global pulse control, you can direct the simulator to take one
of the following three actions on all module path output pulses:
Reject the module path output pulse (the output is unaffected by the pulse).
Let the module path output pulse pass through.
Flag the module path output pulse as an error (e state).
Verilog-XL uses these percent values to calculate the limits for its acceptance window,
as follows:
reject_limit = (reject% / 100) * (module_path_delay)
error_limit = (error% / 100) * (module_path_delay)
The simulator then acts on the pulse according to the following rules:
REJECT if 0 < pulse < (reject_limit)
SET TO E if reject_limit <= pulse <(error_limit)
PASS if pulse >= error_limit

12/7/95 Cadence Design Systems, Inc. 8-20


Specify Block 8-21

Timing Checks in Verilog

Use timing checks to verify the timing of the design.


In Verilog-XL, timing checks perform the following steps
Determine elapsed time between the two events
Compare the elapsed time to a specified limit
If the elapsed time does not fall within the specified time window, report
a timing violation.
Timing checks performed by Verilog-XL are
setup
hold
pulse width
clock period
skew
recovery

Timing Checks in Verilog


Timing checks are used to verify the timing of the design.
In Verilog-XL, the timing checks perform the following
Determine elapsed time between the two events which are specified in the timing
check.
Compare the elapsed time to a limit specified in the check
If the elapsed time does not fall within the specified time window, report a timing
violation. This violation is reported as a warning and does not affect the output of the
module.

12/7/95 Cadence Design Systems, Inc. 8-22


Specify Block 8-23

Timing Checks in Verilog (continued)

$setup reports a violation if the period that elapsed from a change in data to
posedge clk is less than 20.
$setup(data, posedge clk, 20, notifier);
$hold reports a violation if the period that elapsed from posedge clk to
change in data is smaller than 11.
$hold(posedge clk, data, 11, notifier);
$setuphold is the combination of the $setup and $hold timing checks. This
statement sets up a setup check of 20 and a hold check of 11.
$setuphold(posedge clk, data, 20, 11, notifier);

20 11

clk

data

Timing Checks in Verilog (continued)


$setup(data_event, ref_event, limit, notifier);
$hold(ref_event, data_event, limit, notifier);
$setuphold(ref_event,data_event,s_limit, h_limit, notifier);
$recovery(ref_event, data_event, limit, notifier);
$width(ref_event, limit, threshold, notifier);
$period(ref_event, limit, notifier);
$skew(ref_event, data_event, limit, notifier);
ref_event is the transition at a control signal that establishes the reference time for
tracking timing violations on the data_event.
data_event is the signal change that initiates the timing check and is monitored for
timing check.
limit is the time limit used to detect timing violations.
Important
Unlike the other timing checks, the $setuphold and $recovery tasks allow negative time specifications to define the
windows in which events generate violations.

notifier is a Verilog register that toggles its value every time a violation is reported. It
is an optional argument.
threshold is an optional argument that filters out spikes and glitches.

12/7/95 Cadence Design Systems, Inc. 8-24


Specify Block 8-25

Notifiers in Timing Checks

When a timing-check violation occurs, Verilog reports a violation and the


output receives the new value.
The expected behavior might be for the output to become undefined when
a timing violation occurs.
There are two ways to make use of the notifier to effect the value of the
output:
Specify an additional port is in the sequential user-defined primitives
(UDP). This forces the output to an undefined value whenever the notifier
register toggles.
Use the notifier in a more complex behavioral model to change the value
of the output.

Notifiers in Timing Checks


When a timing-check violation occurs, Verilog reports a violation and the output
receives the new value.
Note: For more information on UDPs and the notifiers, see the module "Modeling ASIC Libraries".

12/7/95 Cadence Design Systems, Inc. 8-26


Specify Block 8-27

Conditional Timing Checks


The timing check can be limited to an evaluation of a conditional expression.

module dff_pc (data, clock, preset, clear, q, nq);


input data, clock, preset, clear;
output q, nq;
// instantiate the primitives for the basic flip-flop
udp_dff_pc(q_int, data, clock, preset, clear);
buf b1 (q, q_int);
not n1 (nq, q_int);

// instantiate an and primitive to form p_c = preset & clear


and a1(p_c, preset, clear);
// Note the use of &&& and p_c
specify
$setup(data, posedge clock &&& p_c, 12);
$hold(posedge clock, data &&& p_c, 5);
$width(posedge clock, 25);
endspecify
endmodule

Conditional Timing Checks


The evaluation of a timing check can be limited to the evaluation of a conditional
expression.
The conditional timing check reduces pessimism because the timing check is performed
only when the condition is true and not otherwise. In the overhead example, all the
timing checks are performed only when clear and preset signals are high and not
otherwise when the flip-flop is in either preset or reset modes.
The conditional timing check can have only one condition. For more than one condition,
separate logic must be generated. In the overhead example, p_c is created to meet this
condition.
The expression in the condition should be an input or an internal signal generated from
the inputs.

12/7/95 Cadence Design Systems, Inc. 8-28


Specify Block 8-29

Labs
Lab 3 Modeling with Path Delays and Timing Checks
Modeling a D Flip-Flop with Path Delays and Timing Checks

12/7/95 Cadence Design Systems, Inc. 8-30


Behavioral Modeling 9-1

Behavioral Modeling
Objectives
Learn the basics of behavioral modeling.
Learn the operators available in Verilog.
Learn the high-level programming language constructs available in Verilog.

Terms and Definitions

12/7/95 Cadence Design Systems, Inc. 9-2


Behavioral Modeling 9-3

Behavioral Modeling

Behavioral modeling enables you to describe the system at a high level of


abstraction.
Behavioral modeling in Verilog is described by specifying a set of
concurrently active procedural blocks.
High-level programming language constructs are available in Verilog for
behavioral modeling.

DFF
Clr
At every positive edge of Clk
If Clr is not low
Data Q Set Q to the value of Data
Set Qb to inverse of Data
DFF
Qb
V

Whenever Clr goes low


Set Q to 0
Clk Set Qb to 1

Behavioral Modeling
Behavioral modeling enables you to describe the system at a high-level of abstraction.
At this level of abstraction, implementation is not as important as the high-level
description of a functional block or the system.
Behavioral modeling in Verilog is described by specifying a set of concurrently active
procedural blocks in a high-level programming language that together describe the
operation of the system.
High-level programming language constructs are available in Verilog for behavioral
modeling. Some of these are
Assignment Statements
Looping Statements
Conditional Statements

12/7/95 Cadence Design Systems, Inc. 9-4


Behavioral Modeling 9-5

Procedural Blocks

Procedural blocks are the basis for behavioral modeling.


Procedural blocks are of two types
initial procedural blocks
always procedural blocks
Procedural blocks have the following components
Procedural assignment statements
Timing controls
High-level programming language constructs.

initial c always c
c c
c c
c c
c c
c c
c c
c c

Procedural Blocks
Procedural blocks are the basis for behavioral modeling.
Procedural blocks are of two types
initial procedural blocks, which execute only once.
always procedural blocks, which execute in a loop.
Procedural blocks have the following components
Procedural assignment statements to describe the data flow within the block.
Timing controls to control the triggering of the block and the execution of the
statements in the block.
High-level programming language constructs that describe the functional operation
of the block.

12/7/95 Cadence Design Systems, Inc. 9-6


Behavioral Modeling 9-7

Timing Control in Procedural Blocks

Procedural block timing is specified using three types of timing controls.

Simple Delay
#10 rega = regb;
#(cycle/2) clk = ~clk; // cycle is declared as a parameter

Edge-Triggered Timing Control


@(r or q) rega = regb; // controlled by in r or q
@(posedge clk) rega = regb; // controlled by positive edge
@(negedge clk) rega = regb; // controlled by negative edge

Level-Triggered Timing Control


wait (!enable) rega = regb; // will wait until enable = 0

Timing Control in Procedural Blocks

Procedural block timing is specified using three types of timing controls.


#<delay> simple delay
Delays execution for a specific number of time steps.
@(<signal>) edge-triggered timing control
Delays execution until an edge occurs on <signal>. The active edge of <signal> can
be specified using posedge or negedge. Several <signal> arguments can be specified
using the or keyword.
wait(<expr>) level-sensitive timing control
Delays execution until <expr> evaluates TRUE (non-zero).

12/7/95 Cadence Design Systems, Inc. 9-8


Behavioral Modeling 9-9

Timing Control in Procedural Blocks (continued)


always wait (set)
begin
@(posedge clk)
#3 q = 1;
#10 q = 0;
wait (!set);
end

0 10 30 50 70 90 110

clk

set
15 48 70

q
33 43 93 103

Timing Control in Procedural Blocks (continued)


Example
posedge at 10 is ignored because it is waiting for set = 1.
posedge at 30 is caught and q = 1 at 33 (30+3) followed by q = 0 at 43 (33 + 10).
It now waits for set = 0 which happens at 48.
It is now waiting for set = 1, which happens at 70, and coincides with the posedge of clk.
However this posedge is ignored, because by the time it reaches this statement, the
clk = 1 and the posedge could be missed as shown in this example.
Caution
In actual hardware design this would be considered a race condition. During simulation the evaluation will be order
dependent and unpredictable. In general, this is not a recommended modeling style.

12/7/95 Cadence Design Systems, Inc. 9-10


Behavioral Modeling 9-11

Procedural Assignment

Assignments made in procedural blocks are known as procedural assignments.

module dff (q, qb, d, clk);


output q, qb;
input d, clk;
reg q, qb;
always@(posedge clk)
begin
#5 q = d;
#1 qb = ~d;
end
endmodule

Procedural Assignment

Assignments made in procedural blocks are known as procedural assignments.


The left-hand side of a procedural assignment must be a data type in the register class.
The right-hand side of a procedural assignment can be any valid expression. The data
types used in the right-hand-side expression are not restricted.
If you forget to declare a signal, it defaults to be a wire. When it is used on the left-hand
side, it gives an error message.
"Illegal left-hand-side assignment"

12/7/95 Cadence Design Systems, Inc. 9-12


Behavioral Modeling 9-13

Operators in Verilog Assignments

2s complement arithmetic (+,-,*,/,%)


binary bit-wise (~,&,|,^,~^)
unary reduction (&,~&,|,~|,^,~^)
logical (!,&&,||,==,===,!=,!==)
relational(>,<,>=,<=)
logical shift (<<,>>)
conditional (?:)
concatenate & replicate ({},{{ }})

Operators in Verilog Assignments


The operators above will be discussed in the next few modules.

12/7/95 Cadence Design Systems, Inc. 9-14


Behavioral Modeling 9-15

Bit-Wise, Unary, and Logical Operators

Given:
a = 1011
b = 0010

Bit-wise Unary reduction Logical

a | b = 1011 |a=1 a || b = 1
a & b = 0010 &a=0 a && b = 1

Bit-Wise, Unary, and Logical Operators


Bit-wise operators perform bit-wise manipulations on the operands. The operator
compares one bit in one operand with its equivalent bit in the other operand to calculate
one bit for the result.
Unary reduction operators perform bit-wise operation on a single operand to produce a
single-bit result.
Logical operators operate with logic values. Anything non-zero is true, anything with
value 0 is false, and any value containing an unknown is ambiguous.

12/7/95 Cadence Design Systems, Inc. 9-16


Behavioral Modeling 9-17

Equality Operators
= is the assignment operator. It copies the value of the RHS of the
expression to the LHS.
== is the equality operator.
== 0 1 x z a = 2b1x;
b = 2b1x;
0 1 0 x x
if (a == b)
1 0 1 x x $display(a is equal to b);
else
x x x x x $display(a is not equal to b);
z x x x x

=== is the identity operator.


=== 0 1 x z a = 2b1x;
b = 2b1x;
0 1 0 0 0
if (a === b)
1 0 1 0 0 $display(a is identical to b);
else
x 0 0 1 0 $display(a is not identical to b);
z 0 0 0 1

Equality Operators
= is the assignment operator. It copies the value of the RHS of the expression to the LHS.
== is the equality operator.
It returns 1 or true if the bits that you are comparing are known, that is, if they are 0
or 1 and are equal.
It returns 0 or false if bits being compared are known and are not equal.
It returns x or unknown if one or both of the bits that you are comparing are unknown,
such as x or z.
=== is the identity operator.
It returns 1 or true if the bits that you are comparing are the same, including x and z.
It returns 0 or false if the bits that you are comparing are known and are not equal.
!= is the inequality operator and works the same way as the == operator.
!== is the inverse of the === operator and it works the same way.

12/7/95 Cadence Design Systems, Inc. 9-18


Behavioral Modeling 9-19

Block Statements

Block statements are used to group two or more statements together.


Sequential block statements are enclosed between the keywords begin and
end.
Parallel Block statements are enclosed between the keywords fork and join.

always c always c initial c initial c


begin fork begin fork
c c c c
c c c c
c c c c
c c c c
c c c c
c c c c
c c c c
end join end join

Block Statements
Block statements are used to group two or more statements together so that they act as
one statement, syntactically.
Sequential block statements are enclosed between the keywords begin and end. The
statements in this block are executed in a sequential manner.
Parallel block statements are enclosed between the keywords fork and join. The
statements in this block are executed concurrently.

12/7/95 Cadence Design Systems, Inc. 9-20


Behavioral Modeling 9-21

Intra-Assignment Timing Control


Intra-assignment timing controls delay the assignment to the left-hand side but do
not delay the evaluation of the right-hand side.

fork This is a race fork The values of a


#5 a = b; condition. a = #5 b; and b are saved
#5 b = a; b = #5 a; upon entry to
join join the fork block

There is implicit temporary storage for each right-hand side expression in


intra-assignment statements

begin These are


temp=b; equivalent a = @(posedge clk) b;
@(posedge clk) a=temp; statements
end

Intra-Assignment Timing Control

Intra-assignment timing controls delay the assignment to the left-hand side but do not delay
the evaluation of the right-hand side.
Syntax
<intra-assignment_timing>
::=left-hand side = <delay_control> right-hand side;
::=left-hand side = <event_control> right-hand side;
This can be used to concisely model register swaps and shifts.

12/7/95 Cadence Design Systems, Inc. 9-22


Behavioral Modeling 9-23

Intra-Assignment Timing Control Example

module data_pipe(out, a, b, c);


output [7:0] out; c a b
reg [7:0] out; opc opa opb
input [7:0] a, b, c;
reg [7:0] opa,opb,opc,opc2,sum;
always @(posedge clk) +
fork
opa = @(negedge clk) a; opc2 sum
opb = @(negedge clk) b;
opc = @(negedge clk) c;
sum = @(negedge clk) opa + opb; X
opc2 = @(negedge clk) opc;
out = @(negedge clk) opc2 * sum;
out
join
endmodule

Intra-Assignment Timing Control Example


The block flow is as follows
On the positive edge of the clock, the fork statement starts all the procedural
assignments.
All the RHS (Right-Hand Side) expressions are evaluated, stored in temporary
storage, and are scheduled to be assigned.
At the negative edge of the clock, all the temps are copied into the LHS (Left Hand
Side) expressions.
Due to the temporary storage, the values used by the successive stages are the values that
have already been evaluated in the previous clock cycles.

12/7/95 Cadence Design Systems, Inc. 9-24


Behavioral Modeling 9-25

Nonblocking Procedural Assignment


module swap_vals;
reg a, b, c;
initial
begin
a = 0;
b = 1;
c = 0;
end
always #5 c = ~c;
always @(posedge c)
begin
a <= b; // Nonblocking procedural assignment
b <= a; // swaps the values of a and b.
end
endmodule

Nonblocking Procedural Assignment


A blocking procedural assignment must be executed before the execution of the next
statement in the sequential block.
A nonblocking allows the assignments without blocking the procedural flow.
The assignment happens in two steps
The simulator evaluates all the RHS expressions and schedules the assignment to
take place at the time specified by timing control.
At the end of the time step in which the delay has expired, the simulator executes the
assignment by assigning the value to the LHS expression.

12/7/95 Cadence Design Systems, Inc. 9-26


Behavioral Modeling 9-27

Nonblocking Procedural Assignment


//non_block1.v
module non_block1;
//module instansiation
......
reg a, b, c, d, e, f; The simulator assigns 1 to
//blocking assignments register a at simulation time
initial 10, assigns 0 to register b
begin at simulation time 12, and
a = #10 1; assigns 1 to register c at
b = #2 0; simulation time 16.
c = #4 1;
end
//non-blocking assignments
initial
begin The simulator assigns 1 to
d <= #10 1; register d at simulation time
e <= #2 0; 10, assigns 0 to register e at
f <= #4 1; simulation time 2, and
end assigns 1 to register f at
initial simulation time 4.
begin
$monitor ($time, ,"a = %b b = %b c = %b
d = %b e = %b f = %b", a,b, c, d,e, f);
#100 $finish;
end
endmodule

Nonblocking Procedural Assignment

12/7/95 Cadence Design Systems, Inc. 9-28


Behavioral Modeling 9-29

Conditional Statements
If and If-Else Statements

initial
if (index > 0) // Beginning of Outer if
if (rega > regb) // Beginning of the 1st inner if
result = rega;
else
result = 0; // End of the 1st inner if
else
if (index == 0)
$display(Note : Index is zero);
else
$display(Note : Index is negative);

Conditional Statements
If and If-Else Statements

In nested if sequences, else is associated with the closest previous if.


To ensure proper readability and proper association, use begin-end block statements.

12/7/95 Cadence Design Systems, Inc. 9-30


Behavioral Modeling 9-31

Conditional Statements (continued)


Case Statement
case (opcode)
3b000 : result = rega + regb;
3b001 : result = rega - regb;
3b010 ,
3b100 : result = rega / regb;
default : begin
result = bx;
$display (no match);
end
endcase

Conditional Statements (continued)


Case Statement

The case statement is a special multiway conditional statement that tests whether the
expression matches one of a number of other expressions and branches accordingly.
The case statement does a bit-by-bit comparison for an exact match.
The default statement is optional. It is executed when none of the statements match the
case expression. If, however, it is not specified, no action is taken by Verilog.
Use of multiple default statements is illegal.
It is a good programming practice to always use the default statement, especially to check for
X and Z.
The casez and casex are two other types of case statements are provided to allow handling of
dont-care conditions in the comparisons. Dont care values (z values for casez, z and x values
for casex), in any bit of either the case expression or the case items, are treated as dont-care
conditions during the comparison, and that bit position is not considered. The question mark
(?) is used to specify dont-care bits in a casez or casex statement.

12/7/95 Cadence Design Systems, Inc. 9-32


Behavioral Modeling 9-33

Looping Statements
Repeat Loop
module multiplier(result, op_a, op_b);
parameter size=8;
input [size:1] op_a,op_b;
output [2*size:1] result;
reg [2*size:1] shift_opa,result;
reg [size:1] shift_opb;
always @(op_a or op_b)
begin
result = 0;
shift_opa = op_a; // zero extend left
shift_opb = op_b;
repeat (size)
begin
#10 if (shift_opb[1]) result = result + shift_opa;
shift_opa = shift_opa << 1; // logical left shift
shift_opb = shift_opb >> 1; // logical right shift
end
end
endmodule

Looping Statements
Repeat Loop
A repeat loop executes a block of statements a fixed number of times.
The code above implements a shift and add multiplier.

12/7/95 Cadence Design Systems, Inc. 9-34


Behavioral Modeling 9-35

Looping Statements (continued)


While Loops

...
reg [7:0] tempreg
....
....
while (tempreg)
begin
if (tempreg[0]) count = count + 1;
tempreg = tempreg >> 1; // Right Shift
end
endmodule

Looping Statements (continued)


While Loops

A while loop executes a statement (or block of statements) as long as its expression is
true (or nonzero).
If the expression starts out false, the statements are not executed.

12/7/95 Cadence Design Systems, Inc. 9-36


Behavioral Modeling 9-37

Looping Statements (continued)


For Loops

for (index = 0; index < size; index = index + 1)


if (val[index] == 1bx)
$display (found an X);

for (i = 10; i > index; i = i-1)


memory[i] = 0;

Looping Statements (continued)


For Loops

The loop executes as long as the condition evaluates to TRUE.


The for loop functionality can be implemented with a while loop, but this requires
separate initialization and counter incrementing assignments that are included as a part
of the for loop.

12/7/95 Cadence Design Systems, Inc. 9-38


Behavioral Modeling 9-39

Modeling Asynchronous Reset

module test (q, qb, data, clock, reset);


input data, clock, reset;
output q, qb;
reg state;

buf #(6,5) (q, state);


not #(5,6) (qb, state);

This procedural always


assignment will have @(posedge clock)
no effect on state The left side is
while reset is 0
state=data; restricted to a register
or concatenation of
always @(reset) registers
if(!reset)
assign state=0;
else The right side may
be any expression
deassign state;

endmodule

Modeling Asynchronous Reset


The assign procedural statement sets up a continuous relationship between an
expression and a register.
The assign procedural statement overrides procedural assignments.
The deassign procedural statement removes the effect of the assign statement.
Ability to model asynchronous override of synchronous operation.

12/7/95 Cadence Design Systems, Inc. 9-40


Behavioral Modeling 9-41

Zero-Delay Loops in Verilog


module comparator(out,in1, in2);
output [1:0] out;
input [7:0] in1, in2;
reg [1:0] out;
always
begin
if (in1 == in2)
out = 2b00;
else if (in1 > in2)
out = 2b01;
else
out = 2b10;
end
initial
#10 $finish;
endmodule

Zero-Delay Loops in Verilog

Simulation advances when all the events in the event queue finish. In a zero-delay loop, events
keep getting added at the same time slot. Due to this, the simulation gets stuck at that time slot.
In the overhead example, simulation events are occurring but simulation time does not
advance. This typically happens when there is an always loop with no timing controls.

12/7/95 Cadence Design Systems, Inc. 9-42


Behavioral Modeling 9-43

Importing VHDL Models

Verilog HDL designs can include VHDL models that Cadences VHDL
simulator (Leapfrog) simulates.
You can link a slave Leapfrog simulator to the Verilog-XL executable. The
slave simulator will simulate the VHDL models that are incorporated into a
Verilog design by using a special definition.

Importing VHDL Models


Verilog HDL designs can include VHDL models that Cadences VHDL simulator (Leapfrog)
simulates. You can link a slave Leapfrog simulator to the Verilog-XL executable. The slave
simulator will simulate the VHDL models that are incorporated into a Verilog design by using
a special definition.
The slave VHDL simulator requires a special license different from the normal Leapfrog
license. If the slave license is available and if the design incorporates a VHDL model,
cosimulation starts automatically. The Verilog-XL simulator tells the slave when to start and
stop and synchronizes the slaves activities with its own.
Note: This is an optional product which you can purchase.

12/7/95 Cadence Design Systems, Inc. 9-44


Behavioral Modeling 9-45

Labs
Lab 4 Behavioral Modeling
Modeling a 5-bit Counter

12/7/95 Cadence Design Systems, Inc. 9-46


Interactive Debugging in Verilog 10-1

Interactive Debugging in Verilog


Objectives
Learn about the interactive mode in Verilog.

Terms and Definitions

6/14/95 Cadence Design Systems, Inc. 10-2


Interactive Debugging in Verilog 10-3

Running in Batch Mode Versus Interactive Mode

In batch mode, all the results are analyzed at the end of simulation run.
In interactive mode, the simulation is analyzed as the simulation
progresses.

Running in Batch Mode Versus Interactive Mode


In batch mode, all results are analyzed at the end of simulation run. As a result, any
errors that are detected need to be fixed at the end of simulation, and the simulation
should be run again.
In interactive mode, the simulation results are analyzed as the simulation progresses.
Thus, the moment an error is detected, the simulation can be stopped and the problem
can be debugged as the simulation progresses.

6/14/95 Cadence Design Systems, Inc. 10-4


Interactive Debugging in Verilog 10-5

Verilog in the Interactive Mode

Verilog allows you to interrupt simulation at discrete points in time.


When Verilog is interrupted, it enters interactive mode and prompts you for
command input.
At this time the simulation is in a state of "suspended animation".

Verilog in the Interactive Mode


Verilog allows you to interrupt simulation at discrete points in time in order to interact
with the design under test.
When Verilog is interrupted, it enters interactive mode and prompts you for command
input. Any command that can be placed in a procedural block can be invoked here along
with some special commands to be used only in the debugging environment.
The simulation is now in a state of "suspended animation", for example, all objects are
"frozen" in their current state.

6/14/95 Cadence Design Systems, Inc. 10-6


Interactive Debugging in Verilog 10-7

Entering the Interactive Mode

Interactive mode can be entered in three ways


-s command-line option
^C asynchronous interrupt while simulation is running
#10 $stop; system task placed in procedural description

Once in interactive mode, Verilog prompts you for interactive commands.


The following is the interactive command prompt:
C1 >

Entering the Interactive Mode


Interactive mode can be entered in three ways
-s command-line option causes interactive mode to be entered immediately after
compilation (at time 0).
^C or asynchronous interrupt while simulation is running. It uses the process interrupt
character specific to the machine.
$stop system task placed in a procedural description to enter interactive mode at a
specific time (or based on a specific event). It may also be used interactively to set
breakpoints
Once in interactive mode, Verilog prompts you for interactive commands. The
following is the interactive command prompt:
C1 >

6/14/95 Cadence Design Systems, Inc. 10-8


Interactive Debugging in Verilog 10-9

Typical Tasks in Interactive Mode


Setting Breakpoints
Breakpoints can be set on evaluation of any expression.
C1 > #10 $stop; Stop the simulation
C2 > . after 10 time units

C3 > forever @(posedge clk) $stop;


C4 > . Always stop the
simulation at the
C5 > if (en1 | en2) posedge of clk
> @(posedge clk)
> $stop; If en1 or en2 = 1, then
wait for posedge of clk
C6 > and stop simulation

Typing a period . resumes simulation.

Note:All interactive commands must be terminated with a semicolon.


If Verilog thinks the command is incomplete, it will respond with >.

Typical Tasks in Interactive Mode


Setting Breakpoints
Simple breakpoints can be set using the delay specification in conjunction with $stop.
Complicated breakpoints can be set using the behavioral constructs of Verilog language.
After setting the breakpoint, Verilog does not automatically continue execution. Typing
a period (.) resumes the simulation activity.
If Verilog thinks that the command on the interactive mode is incomplete, it will respond
with > instead of Cn>.

6/14/95 Cadence Design Systems, Inc. 10-10


Interactive Debugging in Verilog 10-11

Typical Tasks in Interactive Mode (continued)

Traversing the Design Hierarchy


Verilog has interactive commands to traverse the hierarchy of a design.

C1 > $showscopes;
Directory of scopes at current scope level:
module (adder), instance (u1)
module (latch), instance (u2)

Current scope is (top)


Highest level modules:
top
C2 > $scope(u1);
C3 >

Typical Tasks in Interactive Mode (continued)


Traversing the Design Hierarchy
The $showscopes system task lists all the scopes in the current scope. When the
interactive mode is first entered, the scope is set to the top level.
$showscopes;
The $scope system task changes the scope to the named level of hierarchy. Hierarchical
names are allowed. After the scope has been set, the objects in the scope no longer need
to be referenced with full hierarchical names.
$scope(<scope_name>);

6/14/95 Cadence Design Systems, Inc. 10-12


Interactive Debugging in Verilog 10-13

Decompiling the Design


The $list system task decompiles the current or named scope.

// counter_test.v

7 module counter_test;
8 reg [4:0]
8 data; // = 5h1d, 29
9 reg
9 rst, // = 1h1, 1
9 load, // = 1h0, 0 Current states of
9 clk; // = 1h1, 1 declared variables
10 wire [4:0]
10 cnt; // = 5h2, 2
14 counter
14 c1(cnt, clk, data, rst, load);
17 always The asterisk * specifies a
17* #10 currently active procedural
17 clk = ~clk; statement

Decompiling the Design


The $list system task decompiles the current or named scope.
The output produced by $list will have an asterisk (*) next to all currently active
procedural statements.

6/14/95 Cadence Design Systems, Inc. 10-14


Interactive Debugging in Verilog 10-15

An Example of Traversing the Design

A
B C
D E F G

EQUIVALENT $list commands


$list (A.B.D); $scope(A.B.D); $scope (A.B);

$list; $list(D);

An Example of Traversing the Design


Given this hierarchical description, the top-level module is A.
When you enter the interactive mode for the first time:
Executing $showscopes; will identify module A as the current scope and list module
instances B and C as scopes within A
Executing $list; will decompile the current scope (module A)
Executing $list(C); will decompile module instance C
Executing $scope(B); will set the current interactive scope to module instance B

6/14/95 Cadence Design Systems, Inc. 10-16


Interactive Debugging in Verilog 10-17

Typical Tasks in Interactive Mode (continued)

Displaying Signal Values


The standard output commands can be invoked in interactive mode.
Detailed information about a signal can be obtained by $showvars.

C1 > $showvars(o1);
o1 (top) wire = StX, schedule = StX
HiZ <- (top.m1): bufif1 g3(o1, i3, c3);
schedule = St1
St1 <- (top.m1): bufif1 g2(o1, i2, c2);
St0 <- (top.m1): bufif1 g1(o1, i1, c1);
C2 >

Typical Tasks in Interactive Mode (continued)


Displaying Signal Values
The standard output commands such as $monitor, $display, and $strobe, can be invoked
in interactive mode.
Detailed information about a signal can be obtained using $showvars. The task is called
with the name of a net or register variable. It includes the following information
Name of the variable
Scope of the variable
Type of variable
Current value
Future value scheduled
Whether the variable is forced
Decompilation of drivers, with output values
Future values of drivers, if scheduled
When invoked without any arguments, $showvars displays the information about all the
variables in the current scope; otherwise it displays all the information for the argument
list.

6/14/95 Cadence Design Systems, Inc. 10-18


Interactive Debugging in Verilog 10-19

Typical Tasks in Interactive Mode (continued)

Circuit Patching
force and release can be used to interactively patch the design.
These commands allows the drivers on nets or statements to be overridden
for a controlled period of time.

C1 > force o1 = in1 | in2;


C2 > . . .
. . .
C14 > release o1;
C15 > $reset; //resets the simulation to time zero

The $list_forces system task lists the currently active force statements.

Typical Tasks in Interactive Mode (continued)


Circuit Patching
Use force and release to interactively patch the design.
These commands allow the drivers on nets or statements to be overridden for a
controlled period of time. Releasing the force on a net brings it back to the state it should
be in due to original logic, whereas a register holds the forced value till the next
assignment after the release.

force <lhs> = <rhs>


<lhs> can be a net or register data type.
<rhs> can be any legal expression.
The $reset system task tells Verilog-XL to return the simulation of your design to its
logical state at simulation time 0.
The $list_forces system task lists the currently active force statements.

6/14/95 Cadence Design Systems, Inc. 10-20


Interactive Debugging in Verilog 10-21

Typical Tasks in Interactive Mode (continued)


$deposit
The $deposit system task lets you set a net or register to a particular value
and then simulate with the signal, set to that new value.
$deposit should be used as a debugging or design initialization aid. It should
not be used to represent actual circuitry.
Here are some examples of using $deposit:
$deposit(sig, 1);
$deposit(bus, hA2);
$deposit(bus4, bZ01x);

Typical Tasks in Interactive Mode (continued)


$deposit
The $deposit system task lets you set a net or register to a particular value and then simulate
with the signal, set to that new value. The value change is propagated throughout the nets and
registers being driven by the variable that has been set.
The $deposit task can be used within any Verilog-XL procedural block. The time at which the
net is to be deposited to can be defined using standard procedural constructs. The task can also
be used on the interactive command line.
Common uses for the $deposit system task include the following:
To initialize large portions or all of a circuit, either at the beginning of, or during
simulation. You can select the nodes to be deposited to yourself, or use PLI code to
extract the node names.
To stop the simulator during a debugging session and to use the command on the
interactive command line to set a new value.
To reset a circuit to a known state after simulation in order to retry a different debug
route.
To set parts of a circuit to analyze intricate circuit details (common for switch-level
simulation).
To break feedback loops and to set them to a known state.
X and Z states can also be deposited.
6/14/95 Cadence Design Systems, Inc. 10-22
Interactive Debugging in Verilog 10-23

Typical Tasks in Interactive Mode (continued)


Tracing Simulation Activity
The $settrace and $cleartrace system tasks turn simulation tracing on and off.

C1 > forever begin


> @enable $settrace; #2 $cleartrace; $stop; end
C2 > .
SIMULATION TIME IS 300
L8 run_ta.v: buf u4 >>> XL GATE = St0
L6 run_ta.v: wire clk >>> FROMXL NET = St0
L12 latch.v (run_ta.u3): @(negedge enable) >>> CONTINUE
L13 latch.v (run_ta.u3): r1 = #(1) data; >>> = #(32h1, 1)
1hx, x;
C1: #2 >>> CONTINUE
C1: $cleartrace;
C2 >

Typical Tasks in Interactive Mode (continued)


Tracing Simulation Activity
The $settrace and $cleartrace system tasks turn simulation tracing on and off.
Trace displays the event with a file and line number from the source description.
Simulation tracing is particularly useful when a timing problem, such as a race
condition, has been narrowed down to a small window.

6/14/95 Cadence Design Systems, Inc. 10-24


Interactive Debugging in Verilog 10-25

Source-Level Debugger in Verilog

Verilog offers a rich set of source-level debugging system tasks.


$db_set_focus
$db_delete_focus
$db_step
$db_steptime
$db_breakatline
$db_breakbeforetime
$db_breakaftertime
You can use these system tasks in conjunction with the other debugger
commands.

Note:More system tasks used for source-level debugging are described in the Verilog-XL
Reference Manual.

Source-Level Debugger in Verilog


$db_set_focus(<scope>+) - $db_delete_focus(<scope>+)
Sets or deletes focus on a scope for stepping and tracing behavioral statements and
unidirectional primitives. Multiple foci can be set.
$db_step
Steps behavioral statements and undirectional primitives in the foci. When no focus is
selected it is same as ; (step).
$db_steptime(<time_unit>)
Advances simulation by a given time unit. The break occurs before any simulation
event is interpreted at a simulation time equal to current simulation time plus the time
unit.
$db_breakatline(<line_no> <,<scope><,<file_name>>>)
Breaks before a behavioral statement evaluation or after an unidirectional primitives
output evaluation.
$db_breakbeforetime - $db_breakaftertime
Breaks before or after simulation events are evaluated at a certain simulation time.

6/14/95 Cadence Design Systems, Inc. 10-26


Interactive Debugging in Verilog 10-27

Saving and Restarting a Verilog Simulation

Verilog has the ability to save the simulation data structure into a permanent file
and restart the simulation from the time of save.
module checkpoint;
initial
// Save the simulation data structures after 500 ns.
#500 $save(save.dat);
// Incrementally save the simulation after every 100000 ns
initial
begin
#100000 $incsave(inc1.dat);
#100000 $incsave(inc2.dat);
#100000 $incsave(inc3.dat);
#100000 $incsave(inc4.dat);
end
endmodule

Use $restart in the interactive mode or -r command-line option to restart from an


already saved file.

Saving and Restarting Verilog Simulation


Verilog has the ability to save the simulation data structure into a permanent file. You
can load again at a later time to start simulation from the time of save.
This utility is useful
In large simulations to save the check-point versions of the data structures.
To perform quick try-and-see experiments without running the entire simulation.
To guard against machine failures during simulation.
$save system task saves the simulation database. It takes one argument which is the
name of the file the database is to be stored in.
$incsave is the system task that lets Verilog perform incremental saves. The incremental
save, saves data from the last save. It takes one argument, which is the name of the file
the database is to be stored in.
$restart restarts the simulation from the point it was saved by reading the information in
the save file supplied as its argument. For restarting simulation using $restart, the design
needs to be compiled again and the restart command issued in the interactive mode.
Another way to restart a simulation is to use the -r command-line option:
verilog -r save.dat
The file save.dat must be created by $save or $incsave system tasks.

6/14/95 Cadence Design Systems, Inc. 10-28


Interactive Debugging in Verilog 10-29

Interactive Command History


The $history system task lists previously executed interactive commands.
You can execute a command again by entering the command number.

C4 > $history; List command history

Command history:
C1* forever
@(posedge clk)
Active commands
$stop;
C2 $list;
C3 $display(clear);
C4* $history;

C5 > -1 Disable the continuous breakpoint

C6 > 2 Repeat C2 ($list in this case)

Interactive Command History


The $history system task lists previously executed interactive commands.
You can execute the command again by entering the command number.
The output produced by $history has an asterisk (*) next to all active commands.
You can disable active commands by typing -n, where n is the command number.
All interactive commands are written to the keys file. The keys file is named verilog.key
by default. You can replay the keys file by entering $input or by starting the Verilog
software with the -i command-line option.

6/14/95 Cadence Design Systems, Inc. 10-30


Interactive Debugging in Verilog 10-31

Labs
Lab 5 Behavioral Modeling and Interactive Debugging
Modeling an Arithmetic Logic Unit (ALU)

6/14/95 Cadence Design Systems, Inc. 10-32


Modeling with Continuous Assignments 11-1

Modeling with Continuous Assignments


Objectives
Learn how to model with continuous assignments.
Learn the operators available for use in continuous assignments.

Terms and Definitions

6/29/95 Cadence Design Systems, Inc. 11-2


Modeling with Continuous Assignments 11-3

Continuous Assignments

Continuous assignments drive values onto a net.


Any changes in the RHS of the continuous assignment are evaluated and
the LHS is updated.
You can model combinational logic with continuous assignments.
Continuous assignments drive a net that has been previously declared.
wire out;
assign out = a & b;

wire #10 inv = ~in;

wire eq;
assign eq = (a == b);

Continuous Assignments
Continuous assignments drive values onto a net.
Any changes in the RHS of the continuous assignment are evaluated and the LHS is
updated with the new value.
You can model combinational logic with continuous assignments without using gates
and interconnect nets.
Continuous assignments drive a net that has been previously declared. It is an error if the
net is not declared.
Strength specification for a net in a continuous assignment
wire (strong1,weak0) [7:0] net1 = net2 & net3;
Delay specified for the continuous assignment
tri #10 xor_net = a^b;
Multiple assignments in one declaration
wire and_net = a1&a2,
or_net = a1|a2;
Concatenation at LHS
assign {carry_out, sum} = ina + inb + carry_in;
Multiple continuous assignments with delay of 5
assign #5 c = a[0], d = {r1, r2, r3}, f[3:2] = {r3, r4};
6/29/95 Cadence Design Systems, Inc. 11-4
Modeling with Continuous Assignments 11-5

Conditional Operator

in out

enable

assign out = ( enable ? in : bz );

Conditional Operator
The conditional operator is similar to the case statement. The value assigned to the LHS
is the one that results true from the expression evaluation.

6/29/95 Cadence Design Systems, Inc. 11-6


Modeling with Continuous Assignments 11-7

Conditional Operator (continued)


2
sel
in1
in2
in3 out
4
in4
4

module mux4_1 (out, in1, in2, in3, in4, sel);


output [3:0] out;
input [3:0] in1, in2, in3, in4;
input [1:0] sel;
wire [3:0] out;

assign out = (sel == 2b00) ? in1 :


(sel == 2b01) ? in2 :
(sel == 2b10) ? in3 :
(sel == 2b11) ? in4 :
4bx;
endmodule

Conditional Operator (continued)

The default is specified to ensure proper behavior for any case that is not enumerated. In the
overhead example, it would be when one of the bits of sel is unknown.

6/29/95 Cadence Design Systems, Inc. 11-8


Modeling with Continuous Assignments 11-9

Concatenation and Replication Operators

Byte Swap
wire [15:0] new_word = {word[7:0], word[15:8]};

Concatenation operator in LHS


module add_32 (co, sum, a, b, ci);
output co;
output [31:0] sum;
input [31:0] a,b;
input ci;
assign #102 {co, sum} = a + b + ci;
endmodule

Bit replication to generate 8b01010101


byte = {4{2b01}};

Sign Extension
word = {{8{byte[7]}}, byte};

Concatenation and Replication Operators

6/29/95 Cadence Design Systems, Inc. 11-10


Modeling with Continuous Assignments 11-11

Labs
Lab 6 Modeling with Continuous Assignments
Modeling a Scalable Multiplexer.

6/29/95 Cadence Design Systems, Inc. 11-12


Modeling Memories 12-1

Modeling Memories
Objectives
Learn how to model memories with Verilog HDL.

Terms and Definitions

6/9/95 Cadence Design Systems, Inc. 12-2


Modeling Memories 12-3

Memory Declaration

A memory in Verilog is declared as a two-dimensional array of registers.

reg [15:0] MEM [0:1023]; // 1K x 16-bit memory array

reg [7:0] PREP [hFFFE:hFFFF]; // 2 x 8-bit memory array

reg [0:wordsize-1] MEM3 [memsize-1:0];


// Memory array declared using parameters

Memory Declaration
In Verilog syntax, you declare a memory as an array of registers.

reg [<msb>:<lsb>] <memory_name> [<first_addr>:<last_addr>];

where
<msb> and <lsb> determine the word size of the memory
<memory_name> is the name of the memory array
<first_addr> and <last_addr> determine the depth of the memory

You can declare word size and the memory depth with any legal expression.

6/9/95 Cadence Design Systems, Inc. 12-4


Modeling Memories 12-5

Memory Addressing

A memory element is addressed by giving the location to the memory array.

. . .
reg [8:1] mema [0:255];// declare memory called mema
reg [8:1] mem_word;// temp register called mem_word
. . .
// Display contents of the 6th memory address
$displayb(mema[5]);
. . .
// Display the msb of the 6th memory word
mem_word = mema[5];
$displayb(mem_word[8]);
. . .

Memory Addressing
A memory element is addressed by giving the location as the address to a previously
defined memory array.
You can address a bit, or a part of a memory word. To do so, store the memory location
addressed in a temporary register of the correct width and then the bits can be accessed.

6/9/95 Cadence Design Systems, Inc. 12-6


Modeling Memories 12-7

Loading a Memory Array

Assigning values to each word of the memory array.


Call to $readmem system task.

$readmem<base>(<filename>,<mem_name>,<start>?,<finish>?);

parameter memsize = 256;


reg [7:0] mema [0:memsize-1];
. . .
initial
for (i = 0; i < memsize; i = i+1)
mema[i] = 8b0;
. . .
initial
$readmemb(mem_file.txt, mema);
. . .

Loading a Memory Array

In order to load a memory array you can use of the following:


Assign values to each word of the memory array. This method is useful when the value
of a particular word of the memory needs to be changed or when all the words of the
memory need to be initialized to the same value.
Use $readmemb and $readmemh system tasks. A Verilog memory array can be
initialized by writing into the memory the contents of a text file. The $readmemb and
$readmemh system tasks read from a file and write into the memory.
$readmem<base>(<filename>, <mem_name>, <start>?, <finish>?);
where
<base> is b if the values are binary numbers.
is h if the values are hexadecimal numbers.
<filename> is the file from which the memory array is to be loaded.
<mem_name> is the name of the memory to be loaded.
<start> and <finish> are the addresses of the memory that are to be loaded. By default,
<start> is the first address and <finish> is the last address of the memory array

6/9/95 Cadence Design Systems, Inc. 12-8


Modeling Memories 12-9

File Format for $readmemb and $readmemh

$readmemb(mem_file.txt, mem);

UNIX Text File Declared Memory Array


mem_file.txt reg [0:7] mem [0:1023]
00000000 0
0000_0000 .
01100001
0110_0001 0011_0010 .
// addresses 3-255 are not 00110010 .
// defined .
@100 .
1111_1100
11111100 256
/* addresses 257-1022 are .
not defined */
.
@3FF
.
1110_0010 11100010
1023
0 7

File Format for $readmemb and $readmemh


The values are represented as binary or hexadecimal numbers depending on the system
task being called.
You may use an underscore (_) to increase readability.
Both single line and multiline comments of Verilog are supported.
You can assign a value to a particular address. When addresses are used in the data file,
the format is an at character (@) followed by a hexadecimal number. Both upper and
lower case digits are allowed in the number. No white space is allowed between the @
and the number. When the system task encounters an address specification, it loads
subsequent data starting at that memory address.
Verilog does not tell you if a non-existent address is loaded.

6/9/95 Cadence Design Systems, Inc. 12-10


Modeling Memories 12-11

Modeling Bidirectional Ports

The bidirectional port needs to be declared using the keyword inout.


Inout ports follow the following rules
The inout port must be driven by a net and not a register.
An inout port must drive a net and not a register.
Logic needs to be built around the inout port to ensure proper operation.

Modeling Bidirectional Ports


Inout ports follow the port connection rules. No stimulus can be applied to the inout port
through a register data type, thus, the port needs to be buffered.
Logic needs to be built around the inout port to ensure proper operation. Therefore,
when the port is acting as an input port, the output logic is disabled and when it is acting
as an output port, the input logic is disabled.

6/9/95 Cadence Design Systems, Inc. 12-12


Modeling Memories 12-13

Modeling Bidirectional Ports (continued)


bufif primitives

rd_wr_

io_port Module
Logic
data

module inout_port(io_port, rd_wr_);


inout io_port;
input rd_wr_;
bufif1 b1 (io_port, data, rd_wr_);
bufif0 b2 (data, io_port, rd_wr_);
. . .
endmodule

Modeling Bidirectional Ports (continued)


bufif Primitives
The rd_wr_ input controls the enabling and disabling of the bufif primitives.
When rd_wr_ = 1, the primitive b1 is enabled and the data gets transferred to the io_port.
When rd_wr_ = 0, the primitive b2 is enabled and the value on the io_port is transferred
to the data.

6/9/95 Cadence Design Systems, Inc. 12-14


Modeling Memories 12-15

Modeling Bidirectional Ports (continued)


Continuous Assignments

module inout_port(io_port, rd_wr_);


inout [7:0] io_port;
input rd_wr_;
reg [7:0] out_reg;
wire [7:0] io_port;

assign io_port = (rd_wr_ ? out_reg : bz);

always @(negedge rd_wr_)


out_reg = io_port;
endmodule

Modeling Bidirectional Ports (continued)


Continuous Assignments
A continuous assignment controls the data on the inout port by the value of the enable pin.
If rd_wr_ = 1, the port acts as an output (read mode) and the value in the internal register,
out_reg, is placed on the port.
If rd_wr_ = 0, the port acts as an input port (write mode) and the value on the port is
placed on the internal storage register, out_reg.

6/9/95 Cadence Design Systems, Inc. 12-16


Modeling Memories 12-17

Labs
Lab 7 Modeling Memories
Modeling a RAM with a Bidirectional Data Bus

6/9/95 Cadence Design Systems, Inc. 12-18


User-Defined Tasks and Functions in Verilog 13-1

User-Defined Tasks and Functions in Verilog


Objectives
Learn the use of Verilog tasks and functions.
Learn the named event and blocks.
Enabling and disabling named events and tasks.

Terms and Definitions

6/29/95 Cadence Design Systems, Inc. 13-2


User-Defined Tasks and Functions in Verilog 13-3

Verilog Tasks and Functions

Both functions and tasks let you execute common procedures from different
places in a description.
They help to simplify the complex behavior of the design.
You typically use a function in Verilog to create a new operation.
A task describes a separate piece of hardware.
A task can contain delays while a function cannot.
A function has only input parameters and it returns a single value.
A task can have input, output, and inout parameters.

Verilog Tasks and Functions


Both functions and tasks let you execute common procedures from different places in a
description.
They help to simplify the complex behavior of the design by breaking up large
procedures into smaller, more manageable ones.
You typically use a function in Verilog to create a new operation.
A task describes a separate piece of hardware that is a smaller part of the bigger system.
A task can contain delays, while a function cannot.
A function has only input parameters and it returns a single value.
A task can have input, output, and inout parameters.

6/29/95 Cadence Design Systems, Inc. 13-4


User-Defined Tasks and Functions in Verilog 13-5

Specifications of a CPU Interface


CPU asserts read_request and waits for read_grant.
When read_grant is asserted, the CPU places the address on the address
bus and reads the data.
After reading the data, CPU deasserts the read_request and drives the
address to high impedance.
The bits of the data need to be swapped.
If read_grant is deasserted while read_request is asserted, abort the read.

read_request module cpu_iface(<ports>);


<port declarations>
read_grant reg [16:1] IR, PC, address;

always @(posedge sys_clk)


address
CPU begin
16 if (read_request == 1)
INTERFACE // Call the read task
data // Call function to swap bits
16 // Call named event
sys_clk end
// Abort read
endmodule

Specifications of a CPU Interface


Use a task to perform the read operation.
Use a function to swap the bits of data.
Use a named event to indicate the completion of the read.
Use task disabling to abort the read when the read_grant is deasserted while the
read_request is still asserted.

6/29/95 Cadence Design Systems, Inc. 13-6


User-Defined Tasks and Functions in Verilog 13-7

Verilog Task
. . .
always @(sys_clk)
begin
if (read_request == 1)
begin
read_mem(IR, PC);
// Event and Function calls
end
end

task read_mem;
output [15:0] data_in;
input [15:0] addr;
@(posedge read_grant)
begin
ADDRESS = addr;
#15 data_in = data;
end
endtask
. . .

Verilog Task

Key Features:
Task is enabled when the task name is encountered in the Verilog description.
Task definition is contained in the module definition.
The arguments passed to the task are in the same order as the task I/O declarations.
You can use timing controls freely in the statement.
Tasks define a new scope in Verilog.

6/29/95 Cadence Design Systems, Inc. 13-8


User-Defined Tasks and Functions in Verilog 13-9

Verilog Function
always @(sys_clk)
begin
. . .
IR = swap_bits(IR);
. . .
end
function [16:1] swap_bits;
input [16:1] in_vec;
reg [15:0] temp_reg;
integer i;
begin
for (i = 16; i >= 1; i = i-1)
temp_reg[16 -i] = in_vec[i];
swap_bits = temp_reg;
end
endfunction
. . .

Verilog Function

Key Features:
A function definition cannot contain any timing-control statements.
It must contain at least one input and does not contain any output or inout port.
A function returns only one value, which is the value of the function itself. Therefore,
parameters cannot be declared as output or inout.
The arguments passed to the function are in the same order as the function input
parameter declarations.
The function definition must be contained within the module definition.
A function cannot enable a task. However, a task can enable a function.
Functions define a new scope in Verilog.

6/29/95 Cadence Design Systems, Inc. 13-10


User-Defined Tasks and Functions in Verilog 13-11

Named Event
event read_complete;
. . .
always @(sys_clk)
begin
if (read_request == 1)
begin
// Task and Function calls
->read_complete;
end
end
always @(read_complete)
begin
read_request = 1b0;
ADDRESS = 16bz;
$display(Data Received, Read is Complete);
end
. . .

Named Event
A Named event is a data type that you trigger in a procedural block to enable actions.
You must declare a named event before you can reference it.
Named events have no duration and carry no value.
You can only make an event occur from a procedure.
The -> operator is the trigger for the named event.

6/29/95 Cadence Design Systems, Inc. 13-12


User-Defined Tasks and Functions in Verilog 13-13

Named Blocks

You can name a block by adding : <name_of_block> after the keywords


begin or fork.
module named_blk;
. . .
begin : seq_blk
. . .
end
. . .
fork : par_blk
. . .
join
. . .
endmodule
You can declare local variables in the block.
You can disable a block.

Named Blocks
You can name a block by adding : <name_of_block> after the keywords begin or fork.
You can declare local variables in the named block.
You can disable a named block.
Named blocks define a new scope in Verilog.

6/29/95 Cadence Design Systems, Inc. 13-14


User-Defined Tasks and Functions in Verilog 13-15

Disabling Named Blocks and Tasks


. . .
always @(sys_clk)
begin
if (read_request == 1)
read_mem(IR, PC);
end
. . .
always @(negedge read_grant)
if (read_request == 1)
disable read_mem;
. . .
task read_mem;
. . .
-> read_complete;
endtask
. . .

Disabling Named Blocks and Tasks


The disable statement provides the ability to terminate all the activity of a named block
or a task. It provides the ability of returning from the named block or a task before all
the statements are executed.
When a named block or a task is disabled, then all the events scheduled by them are
removed from the event queue.

6/29/95 Cadence Design Systems, Inc. 13-16


User-Defined Tasks and Functions in Verilog 13-17

Labs

Lab 8 Tasks and Functions in Verilog


Modeling a Sequence Controller
Lab 9 Simulating a Complete System
Modeling and Simulating a RISC CPU System (Optional)

6/29/95 Cadence Design Systems, Inc. 13-18


Modeling for Synergy 14-1

Modeling for Synergy


Objectives
Introduce modeling style for Synergy.
Basics of modeling combinational and sequential logic.
Basics of modeling Finite State Machines.
Introduce library modeling guidelines.

Terms and Definitions

FSM Finite State Machine

6/29/95 Cadence Design Systems, Inc. 14-2


Modeling for Synergy 14-3

Synthesis
Top-Down Design
Requirements
Analysis Begin Top-Down design
at the highest level of
System abstraction and finish at
Partitioning the lowest level.

Behavioral / Functional
Specification

Behavioral / Functional
Verification

Synthesis and
Optimization

Gate Level
Verification

Synthesis

Synthesis tools play an important role in top-down design.


At the higher level, you write an HDL model as an executable functional specification
of the design.
After functional verification, you translate the functional description to a gate-level
design, using synthesis and optimization tools.
Mixed-level logic simulation allows you to verify the design at both the functional and
structural levels.

6/29/95 Cadence Design Systems, Inc. 14-4


Modeling for Synergy 14-5

Modeling Style

There will always be a modeling style policy for synthesis tools.


The goals of the modeling style are efficiency and predictability.
Two basic rules for writing synthesizable Verilog descriptions:
Gate-level simulation should match functional-level simulation.
Sequential designs should work independently of technology-specific
propagation delays.
Important
This chapter will discuss modeling style for Synergy only, for other synthesis tools please refer to
the appropriate documentation.

Modeling Style
There will always be a modeling style policy for synthesis tools.
You can write Verilog descriptions for which there are no hardware representations
in the digital domain.
Synthesis results are sensitive to the input description.
Goals of the modeling style:
Efficient for simulation
Synthesizable with predictable results
Helps you describe more efficient hardware
Two basic rules for writing Verilog descriptions that are synthesizable:
Gate-level simulation should match functional-level simulation. (You can verify
functionality at the RTL level).
Sequential designs should work independently of technology-specific propagation
delays.

6/29/95 Cadence Design Systems, Inc. 14-6


Modeling for Synergy 14-7

Combinational Logic

A
B
E OUT
module orand(OUT,A,B,C,D,E); C
input A,B,C,D,E; D
output OUT;
or (or1,A,B);
or (or2,C,D); A netlist structure of combinational
and (OUT,or1,or2,E); primitives with no feedback
endmodule loops

module orand(OUT,A,B,C,D,E);
input A,B,C,D,E;
output OUT;
assign OUT = E &(A|B)&(C|D); A continuous assignment
statement with no feedback
endmodule loop

Combinational Logic
For logic to be combinational, the output must have only one possible value for any
combination of input values. There must be no timing or order dependencies.
If your description meets this definition, it can be synthesized as combinational logic.
There are three modeling styles that meet these requirements:
A netlist structure of combinational primitives with no feedback loops.
A continuous assignment statement with no feedback loops.
A procedural block with an event sensitivity list, which has no assignments to nodes
on the sensitivity list.

6/29/95 Cadence Design Systems, Inc. 14-8


Modeling for Synergy 14-9

Procedural Blocks with Event Sensitivity List

reg OUT;
always @(A or B or C or D or E) Complete Sensitivity List
if (E)
OUT = (A|B)&(C|D);
else
OUT = 0;

reg OUT;
always @(E)
if (E)
assign OUT = (A|B)&(C|D); Dynamic Sensitivity List
else
assign OUT = 0;

Procedural Blocks with Event Sensitivity List


An event sensitivity list allows you to monitor any change in the inputs. The output may
assume only one value for any specified set of inputs.
Use procedural blocks with event sensitivity list to model combinational logic.
Sensitivity list must include all the operands of the expressions in order to match
simulation.

6/29/95 Cadence Design Systems, Inc. 14-10


Modeling for Synergy 14-11

Case Statement

module mux(A,B,C,D,OUT,SEL);
input [3:0] A,B,C,D; A
4

output[3:0] OUT; B 4
OUT
input [1:0] SEL; C
reg [3:0] OUT; D

... 2
always @(SEL or A or B or C or D)
SEL
case(SEL)
2b00:OUT = A;
2b01:OUT = B; Case Statement
2b10:OUT = C;
2b11:OUT = D;
default: OUT = 4bx;
endcase

endmodule

Case Statement

If combinational logic is desired, all branches of a case statement should be specified,


including the default branch. If the synthesizer cannot determine that the assignments are
complete in all branches of the decision, it will add latches in order to match simulation.

6/29/95 Cadence Design Systems, Inc. 14-12


Modeling for Synergy 14-13

Latched Logic
module latch (OUT, IN, ENABLE);
input [7:0] IN; 8
in D
output [7:0] OUT;
8
input ENABLE; out
en G
reg [7:0] OUT;

always @(ENABLE or IN)


if(ENABLE)
OUT = IN;
Using an unspecified
branch
endmodule

module latch (OUT, IN, ENABLE);


input [7:0] IN;
output [7:0] OUT;
input ENABLE
reg [7:0] OUT;

always @(ENABLE)
if(ENABLE)
assign OUT = IN; Using the assign/deassign
else statements
deassign OUT;

endmodule

Latched Logic
Latched logic is implied when there are storage devices independent from a clock;
latches are modeled in a style similar to the procedural style for combinational logic.
Storage is implied when there is a branch in a procedural block in which the data signal
is not assigned.
In the first example, there is no else clause, so a latch is created to hold the value of
OUT when ENABLE is deasserted.
In the second example, OUT is disconnected from IN when ENABLE is deasserted, so
it holds the last value of IN, which requires a latch. This is more efficient for simulation.

6/29/95 Cadence Design Systems, Inc. 14-14


Modeling for Synergy 14-15

Simple Sequential Logic


module mux
(A,B,C,D,OUT,SEL,CLK); R
input[3:0] A,B,C,D; INPUTS
COMBINATIONAL E
OUTPUTS
output[3:0] OUT; LOGIC G

input[1:0] SEL;
input CLK;
reg [3:0] OUT;
...
Edge-sensitive
always @(posedge CLK)
Event Control
case(SEL)
2b00: OUT = A;
2b01: OUT = B;
2b10: OUT = C;
4
2b11: OUT = D; A
B 4
default: OUT = 4bx; C
D
4
endcase D >
OUT

2
endmodule SEL CLK

Simple Sequential Logic


The output of a block is stored with a flip-flop when it is triggered by an edge-sensitive
event control.
Modeling style rules for sequential logic
Each always block can have only one edge of one clock. (Exception for
asynchronous/synchronous branch modeling style for reset.)
Each stored variable may be assigned from only one clock-edge-triggered procedural
block.

6/29/95 Cadence Design Systems, Inc. 14-16


Modeling for Synergy 14-17

Asynchronous Reset
module mux_dffrs
(Q,A,B,SEL,CLK,RES,SET); 2
output [1:0] Q; A 2 D S
input [1:0] A,B; B
> R_ Q[1]
input SEL,CLK,RES,SET;
reg [1:0] Q; SEL
D S
always @(posedge CLK) > R_ Q[0]
if (SEL)
Q = A; CLK
SET
else RES
Q = B;
always @(posedge CLK or posedge RES
always @(RES or SET) or posedge SET)
case({RES,SET}) if (RES)
2b10: assign Q = 2b00; Q = 2b00;
2b01: assign Q = 2b11; else if (SET)
default: deassign Q; Q = 2b11;
endcase else
if (SEL)
endmodule Q = A;
else
A separate block is used to Q = B;
describe the asynchronous
reset.

Asynchronous Reset
You can model reset for any type of storage device, edge or level sensitive.
Asynchronous reset can be modeled in a separate, combinational block with the
assign/deassign statements.
A separate reset block is usually more efficient for simulation.
Asynchronous reset can be modeled in a single block with asynchronous and
synchronous branches.
There must be exactly one synchronous branch in the conditional statement. A branch
with no condition is considered synchronous.

6/29/95 Cadence Design Systems, Inc. 14-18


Modeling for Synergy 14-19

Synchronous Reset
module mux_dffrs (Q,A,B,SEL,CLK,RES,SET);
output [1:0] Q;
input [1:0] A,B;
Reset and Set branches
input SEL,CLK,RES,SET;
reg [1:0] Q;

always @(posedge CLK)


if (RES)
Q = 2b00;
else if (SET)
Q = 2b11;
else
if (SEL)
Q = A;
else
A[1:0]
Q = B;
CLK Q[1:0]
endmodule SET

SEL

B[1:0]
RES

Synchronous Reset
Check the status of the reset signal at every clock edge.
If your target library does not contain a storage device with synchronous reset, the reset
is implemented in the data path.

6/29/95 Cadence Design Systems, Inc. 14-20


Modeling for Synergy 14-21

Explicit Style of Finite State Machines


always @(posedge clk)
case (state) Case Statement and
INIT: if (mem_op) State Variable
if (r_not_w)
begin
state = READ; Transition to the
rd = 1; Next State
end
else
begin
state = WRITE;
wr = 1;
end
else state = INIT;
INIT
READ: begin
state = INIT;
rd = 0;
data = membus;
end
WRITE: begin READ WRITE
state = INIT;
wr = 0;
end
default: state = INIT;
endcase

Explicit Style of Finite State Machines


You can describe an FSM explicitly in a procedural block with a single clock edge and
a case statement.
You have to specify a state variable that defines the states of the state machine.
In each state, you have to specify the next state.
If all the assignments to the state register are constant expressions, the synthesizer can
encode the assignments again to optimize the state machine.

6/29/95 Cadence Design Systems, Inc. 14-22


Modeling for Synergy 14-23

Implicit Style of Finite State Machines

You can describe an FSM implicitly without defining a state register.


You can insert multiple clock edges in a procedural block.
Each clock edge represents a transition to another state.
The HDL Synthesizer automatically extracts the state machine and creates
control logic.

Implicit Style of Finite State Machines


Registers are created whenever data is written in one clock cycle and read in another.
Implicit FSMs are at a higher level of abstraction than explicit FSMs.
More efficient for simulation.
Allows support for all Verilog procedural constructs.

6/29/95 Cadence Design Systems, Inc. 14-24


Modeling for Synergy 14-25

An Example of an Implicit FSM

module fsm (out,clk,d1,d2,res);


output out;
input clk,d1,d2,res;
reg out;

always @(posedge clk)


begin: seq_block
out = d1;
@(posedge clk)
out = d2;
end

endmodule

An Example of an Implicit FSM


From each always block that models sequential logic, HDL Synthesizer extracts a single
finite state machine (FSM).
If the always block has only clock cycle (degenerate FSM), it is implemented with
combinational logic plus register.
Registers are created whenever data is written in one clock cycle and read in another for
the stored variables.
If the FSM has more than one cycle, HDL Synthesizer generates control logic, including
a register to keep track of the current state, and adds registers for the stored variables.

6/29/95 Cadence Design Systems, Inc. 14-26


Modeling for Synergy 14-27

Library Basics
Overview
Synergy library is based on the Verilog Simulation Library.
All library cell descriptions must conform to the Synergy HDL Synthesizer
and Optimizer Modeling Style Guide.
Constructs you can use to model Synergy libraries are:
Verilog primitives
Continuous assignments
UDPs
Procedural blocks
All library cell descriptions must be delimited by celldefine and
endcelldefine.
A Library must contain at least one time scale directive.

Library Basics
Overview
For consistency purposes, you should separate all additions to the existing models that
are synthesis specific (including specparams), using the conditional compilation
constructs (`ifdef, etc.) with the symbol SYNTH.
Note: For more information, refer to the Synergy Library Development Guide.

6/29/95 Cadence Design Systems, Inc. 14-28


Modeling for Synergy 14-29

Library Basics (continued)


Modeling
Low-Level Operators:
Combinational single bit output cells can be modeled with Verilog
primitives, continuous assignment statements or combinational UDPs.
High-Level Operators:
Synergy maps complex operations to high-level cells before it creates
boolean equations for the rest of the logic.
High-Level combinational cells must be modeled behaviorally.
High-Level Sequential cells must be modeled either behaviorally or with
UDPs.

Library Basics (continued)


Modeling
Low-Level Operators:
Combinational single bit output cells can be modeled with Verilog primitives,
continuous assignment statements or combinational UDPs.
High-Level Operators:
Synergy maps complex operations to high-level cells before it creates boolean
equations for the rest of the logic.
High-Level combinational cells must be modeled behaviorally.
High-Level Sequential cells must be modeled either behaviorally or with UDPs.
In order to maintain efficient gate-level simulation, this portion of the model must be
conditionally compiled for synthesis with the ifdef directive. The ifdef compiler
directive checks for the definition of a variable name. If it finds the definition, it
includes the source code. This way certain lines of code can be optionally included by
specifying the conditions that must be met.

6/29/95 Cadence Design Systems, Inc. 14-30


Modeling for Synergy 14-31

Library Basics (continued)


Specify Blocks
Add specparams to describe technology specific information.
At least one cost factor should be specified. The default is zero.
All models must have path delays specifying the intrinsic delays of the
models (Ti).
All cells in the library should have the following delay calculation factors
specified:
Rise/Fall Drive factors (TD)
Input and output Load (TL)
Slew (Ts)
Wire delay models, to estimate the delay due to interconnect wiring (Tw).

Delay = Ti + Ts + TD*(TL + Tw)

Library Basics (continued)


Specify Blocks
All models must have path delays specifying the intrinsic delays of the models.
All cells in the library should have the following specparams specified. These
specparams are used by the optimizer and delay calculator.
Area information
One or more of: actual area, relative area, gatecount, etc.
Delay calculation parameters
input load, output load, rise drive, fall drive, input rise slew, input fall slew. If any
of these specparams are not specified, they are assumed to be zero by the HDL
Synthesizer and Optimizers delay calculator.
Intrinsic Delays
Intrinsic delays are taken from the path delays that are specified in the models.
Wire Delays
Wire delays are used in order to consider the delay due to interconnect wiring.

6/29/95 Cadence Design Systems, Inc. 14-32


Modeling ASIC Libraries 15-1

Modeling ASIC Libraries


Objectives
Understand Verilog composite libraries.
Understand functional modeling of ASIC libraries.
Learn about the use of UDPs in ASIC library models.
Understand how to model timing in ASIC libraries.
Learn about the source protection mechanism in Verilog.

Terms and Definitions

UDP User-Defined Primitives behave just like a Verilog primitive. The


user specifies the functionality with a table.
Composite Libraries ASIC libraries that are compatible with Verilog, Veritime,
Verifault-XL, and the HDL Synthesizer and Optimizer.
PLI Programming Language Interface
MIPD Module Input Port Delay

12/8/95 Cadence Design Systems, Inc. 15-2


Modeling ASIC Libraries 15-3

Verilog Composite Libraries

A composite Verilog ASIC library is one that is compatible with


Veritime
Verifault-XL
HDL Synthesizer and Optimizer
One library for the entire flow of HDL-based design.

Verilog Composite Libraries


A composite Verilog ASIC library is the one that is compatible with other Veritools as
well. It contains the information required for the following tools:
Veritime
Verifault-XL
HDL Synthesizer and Optimizer
One library for the entire flow of HDL-based design so that the consistency is
maintained in the design process.

12/8/95 Cadence Design Systems, Inc. 15-4


Modeling ASIC Libraries 15-5

Modeling ASIC Libraries

Each cell in the library has two parts.


Functional
Timing
A cell is defined in Verilog by enclosing the module definition between
celldefine and endcelldefine directives.
celldefine
timescale 1ns / 100ps
module full_adder(cout, sum, a_in, b_in, c_in);
input a_in, b_in, c_in;
output cout, sum;
// Functional description
. . .
// Timing
...
endmodule
endcelldefine

Modeling ASIC Libraries


Each cell in the library has two parts.
Functional part of the cell describes the functionality of the cell.
Timing part of the cell describes the timing behavior of the cell.
A cell is defined in Verilog by enclosing the module definition between celldefine and
endcelldefine directives.
Cells are recognized by PLI routines and are used for delay calculation.
The timescale directive before the module definition defines the time units and time
precision for the cell.

12/8/95 Cadence Design Systems, Inc. 15-6


Modeling ASIC Libraries 15-7

Functional Modeling of Library Cells

Functionality of a cell can be described at two levels


Structural
Behavioral
Avoid mixing these constructs
Structural description
Verilog built-in primitives used to model combinational cells.
User-Defined Primitives (UDPs) used for sequential cells.
Cells simulate fast and efficiently.
Behavioral description
Used to model RAMs, ROMs, and other macromodules.
Cells simulate fast and efficiently.

Functional Modeling of Library Cells


Functionality of a cell can be described at two levels
Structural
Behavioral
Avoid mixing constructs from these levels because switching between the XL and
non-XL algorithm is more expensive than running a simulation with non-XL
algorithm.
Structural description
Verilog built-in primitives are typically used to model combinational cells
User Defined Primitives are typically used to model sequential cells.
These cells are fast and efficient since they are simulated with the XL algorithm of
Verilog.
Behavioral description
Used to model RAMs, ROMs and other macromodules because they can be modeled
more efficiently at behavior level.
These cells are fast and efficient since they are simulated with the Turbo algorithm
of Verilog. For more information about simulaion performance, see the module
"Modeling to Achieve Simulation Performance".

12/8/95 Cadence Design Systems, Inc. 15-8


Modeling ASIC Libraries 15-9

UDPs

You can use UDPs to augment the set of predefined primitive elements.
UDPs can represent sequential as well as combinational elements.
The behavior is described in a truth table.
A UDP can replace 10 to 20 built-in primitives.

UDPs

UDPs permit the user to augment the set of predefined primitive elements, for example,
they can be accelerated with the XL algorithm.
UDPs can represent sequential as well as combinational elements.
Their behavior is described in a truth table (which takes less time to evaluate than two
built-in accelerated primitives).
A UDP can replace 10 to 20 built-in primitives. Thus, the simulation time and the
memory requirements can be reduced significantly, especially if there are a number of
instances of that module.

12/8/95 Cadence Design Systems, Inc. 15-10


Modeling ASIC Libraries 15-11

UDP Features

UDPs can have only one output.


UDPs can have 1 to 10 inputs.
All ports must be scalar and no bidirectional ports are allowed.
z logic values are not supported.
The UDP output terminal can be initialized to a known value at the start of
simulation.

UDP Features
UDPs can have only one output. Thus if the functionality requires more than one output,
then the additional primitives need to be connected to the output of the UDP or several
UDPs can be used together.
UDPs can have 1 to 10 inputs. However, the memory requirements increase
dramatically as the number of inputs increase from 5. The table below shows the
memory requirement per definition for the number of inputs.
# inputs Memory (k bytes)
1-5 <1
6 5
7 17
8 56
9 187
10 623

All ports must be scalar and no bidirectional ports are allowed.


The z logic value is not supported. It is mapped to x.
The UDP output terminal can be initialized to a known value at the start of simulation
using the sequential UDP initial statement.
12/8/95 Cadence Design Systems, Inc. 15-12
Modeling ASIC Libraries 15-13

Combinational UDP Example: 2-1 Multiplexer


This is the The output
name of the port must be
primitive the first port
primitive multiplexer (o, a, b, s);
Table columns output o;
are inputs in input a, b, s;
order declared table UDP definitions
in primitive // a b s : o occur outside of
statement, 0 ? 1 : 0; a module
colon, output, 1 ? 1 : 1;
followed by a ? 0 0 : 0;
semicolon ? 1 0 : 1;
These entries
0 0 x : 0;
reduce
Any 1 1 x : 1; pessimism
combination of endtable
inputs which is endprimitive
not specified
in the table will
produce an x at
the output

UDP Examples
Combinational UDP: 2-1 Multiplexer
? in the table represents iteration over 0, 1 or x logic values.
The first two entries say that if s = 1 then, irrespective of the value of the input b, the
value on the output o, will be same as that of input a.
The next two entries say that if s = 0 then, irrespective of the value of the input a, the
value on the output o, will be same as that of input b.
The last two entries are put in to reduce pessimism. We say that if both the inputs, a and
b, have the same logic value, then even if sel = x, the output o will have the same value
as inputs a or b. This behavior cannot be modeled using Verilog built-in primitives.

12/8/95 Cadence Design Systems, Inc. 15-14


Modeling ASIC Libraries 15-15

Combinational UDP Example: Full Adder


You can implement the full adder with only two combinational UDPs.

Cin Cin
A U_ADDR2_S Sum
A G2 Sum
B G1 B

G4 G5 Cout
U_ADDR2_C
G3 Cout

primitive U_ADDR2_C (CO, A, B, CI); primitive U_ADDR2_S (S, A, B, CI);


output CO; output S;
input A, B, CI; input A, B, CI;
// FUNCTION: FULL ADDER CARRY OUT TERM // FUNCTION: FULL ADDER SUM TERM
table table
// A B CI: CO // A B CI: S
1 1 ? : 1; 0 0 0 : 0;
1 ? 1 : 1; 0 0 1 : 1;
0 1 0 : 1;
? 1 1 : 1; 0 1 1 : 0;
0 0 ? : 0; 1 0 0 : 1;
0 ? 0 : 0; 1 0 1 : 0;
? 0 0 : 0; 1 1 0 : 0;
1 1 1 : 1;
endtable endtable
endprimitive endprimitive

UDP Examples
Combinational UDP: Full Adder
The full adder can be implemented using only two combinational UDPs instead of five
Verilog defined primitives.
For a large number of instantiations of the full adder, the memory requirements will be
greatly reduced since the full adder now consists of only two primitives (versus five in
the original design).

12/8/95 Cadence Design Systems, Inc. 15-16


Modeling ASIC Libraries 15-17

Level-Sensitive Sequential UDP: Latch


The table now has an additional field
representing the current state
Note use of a
reg declaration
primitive latch (q, clock, data); for storage
output q;
reg q;
The output is
input clock, data;
initialized to
initial q = 1b1; 1b1
table
// clock data current next
// state state
0 1 :?: 1 ;
0 0 :?: 0 ;
1 ? :?: - ; // - = no change
endtable
endprimitive Next
state

The ? is used to represent Current


dont care conditions in state
either inputs or current state

UDP Examples

Level Sensitive Sequential UDP: Latch


The latch behaves as follows
When the clock input is 0, the value on the data input is put on the output.
When the clock input is 1, there is no change in the output.
If the output has -, then it means that there is no change in the output.
The output needs to be declared as a reg to store the previous value.
The statement initial q = 1b1; is the sequential UDPs initialization statement and it
causes the output terminal of the UDP to have a value of 1 at the start of simulation.

12/8/95 Cadence Design Systems, Inc. 15-18


Modeling ASIC Libraries 15-19

Edge-Sensitive Sequential UDP: D Flip Flop


primitive d_edge_ff(q, clock, data);
output q;
reg q;
input clock, data;
table
//obtain output on rising edge of clock
// clk dat state next
(01) 0 : ? : 0 ;
(01) 1 : ? : 1 ;
(0x) 1 : 1 : 1 ;
(0x) 0 : 0 : 0 ;
// ignore negative edge of clock
(?0) ? : ? : - ;
//ignore data changes on steady clock
? (??) : ? : - ;
endtable
endprimitive

UDP Examples
Edge-Sensitive Sequential UDP: D Flip Flop
The table has edge terms representing transitions on inputs.
At most, one input transition may be specified in any table entry statement.
All input transitions must be specified if any are specified.

12/8/95 Cadence Design Systems, Inc. 15-20


Modeling ASIC Libraries 15-21

Modeling Timing for Library Cells

The timing of the cell consists of


Delay modeling
Modeling timing checks

Modeling Timing for Library Cells

The timing of the cell consists of


Delay modeling to model the delays through the cell.
Timing checks to model the timing relationship of the various signals in a sequential
cell.

12/8/95 Cadence Design Systems, Inc. 15-22


Modeling ASIC Libraries 15-23

Delay Modeling

Two methods of modeling delays in Verilog


Distributed delays
Path delays in the specify block
Most ASIC library cells are modeled using path delays
Easier to model
Functional description can be simpler
Path delays are more accurate
Supported by HDL Synthesizer and Optimizer
Modular cells

Delay Modeling

Two methods of modeling delays in Verilog.


Distributed delay modeling involves specifying delays on the various elements that
comprise the functionality of the cell.
With path delays, the delays are modeled as the time delay for a change in an input
to propagate to an output.
Note: Both path and distributed delays can be specified in the same module. If no delay mode is explicitly selected,
Verilog will simulate a path taking in to account both delays, and it will pick the worst delay.
Most ASIC cells are modeled using path delays.
Easier to model since delays can be read directly from the data books because
pin-to-pin delays are specified in the data books.
Functional descriptions can be simpler since they need not create delay placeholders.
For example a 3-input and gate with different delays from each input would require
three primitives in a distributed-delay model but only one in a path-delay model.
Path delays are more accurate because delays for all the six transitions can be
specified.
Path delays are supported by the HDL Synthesizer and Optimizer, whereas
distributed delays are not.
Using path delays also creates more modular cells since the delays are modeled inside
the specify block and not embedded inside the functional description.

12/8/95 Cadence Design Systems, Inc. 15-24


Modeling ASIC Libraries 15-25

State-Dependent Path Delays (SDPDs)


The path delays through the cells can be dependent on the state of the cell
inputs.
This behavior is modeled using SDPDs by the conditional-expression
clause of the path-delay statement.

module XOR2 (y, a, b);


input a, b;
output y;
xor i1(y, a, b);
specify
if ( b) (a => y) = (200, 300);
if (~b) (a => y) = (100, 200);
if ( a) (b => y) = (250, 350);
if (~a) (b => y) = (150, 250);
endspecify
endmodule

State-Dependent Path Delays (SDPDs)

The default module path delay algorithm in Verilog-XL uses an efficient method for
choosing delays. It selects path delays without considering circuit logic. It is possible for
the delay that the default algorithm chooses for a transition to be a delay specified for a
path that could not have caused the transition. State-dependent path delays can help in
resolving this type of problem.
The path delays through the cells can be dependent on the state of the cell inputs.
This behavior is modeled using SDPDs by the conditional-expression clause of the
path-delay statement.
All possible input states must be accounted. Otherwise that state is simulated with
distributed delays, if found, or with zero delays.
Multiple states may be combined in a conditional expression.

12/8/95 Cadence Design Systems, Inc. 15-26


Modeling ASIC Libraries 15-27

Delays of X Transitions
Transitions between 0, 1, and Z can be explicitly defined.
Delays involving X transitions are derived from other delays.
The calculation for delay values for X transitions is based on the following
pessimistic rules:
Transitions from a known state to an unknown state should occur as
quickly as possible.
Transitions from a unknown state to a known state should take as long
as possible.

(<inputs> => <outputs>)=(< 0->1 >,< 1->0 >,< 0->Z >,< Z->1 >,< 1->Z >, < Z->0 >);
(C => Q) = (5, 12, 17, 10, 6, 22);
0 -> x = min(5, 17) = 5
1 -> x = min(12, 6) = 6
z -> x = min(10, 22) = 10
x -> 0 = max(12, 22) = 22
x -> 1 = max(5, 10) = 10
x -> z = max(17, 6) = 17

Delays of X Transitions

Transitions between 0, 1, and Z can be explicitly defined.


Delays involving X transitions are derived from other delays.
The calculation for delay values for X transitions is based on the following pessimistic
rules
Transitions from a known state to an unknown state should occur as quickly as
possible. The delay will be the minimum of all the delays specified from the known
value.
Transitions from a unknown state to a known state should take as long as possible.
The delay will be the maximum of all the delays specified for transitions to the known
value.

12/8/95 Cadence Design Systems, Inc. 15-28


Modeling ASIC Libraries 15-29

Notifiers in Timing Checks

When a timing-check violation occurs, Verilog reports a violation and the


output gets the new value.
The expected behavior might be for the output to become undefined when
a timing violation occurs.
An additional port is specified in the sequential UDP which will force the
output to an undefined value whenever the notifier register toggles.

module dff(data, clock, q);


input data, clock;
output q;
reg flag;
udp_dff(q, data, clock, flag);
specify
$setup(data, posedge clock, 12, flag);
$hold(posedge clock, data, 5, flag);
$width(posedge clock, 25, flag);
endspecify
endmodule

Notifiers in Timing Checks


When a timing-check violation occurs, Verilog reports a violation and the output gets
the new value.
The expected behavior might be for the output to become undefined when a timing
violation occurs.
An additional port is specified in the sequential UDP, which will force the output to an
undefined value whenever the notifier register toggles.
Whenever a timing violation occurs, the notifier will toggle and it is fed in to the
udp_dff.
The notifier register argument in the timing checks toggles as follows:
Before Violation After Violation
x 0
0 1
1 0
Note: Since the toggling from x yields a known value, there is no need to initialize the notifier to a known value.

12/8/95 Cadence Design Systems, Inc. 15-30


Modeling ASIC Libraries 15-31

Notifiers in Timing Checks (continued)


primitive udp_dff(q, clock, data, notifier);
output q;
reg q;
input clock, data, notifier;
table
// clk dat not state next
(01) 0 ? : ? : 0 ;
(01) 1 ? : ? : 1 ;
(0x) 1 ? : 1 : 1 ;
(0x) 0 ? : 0 : 0 ;
(?0) ? ? : ? : - ;
? (??) ? : ? : - ;
// When notifier changes, send output to unknown
? ? * : ? : x ;
endtable
endprimitive

Notifiers in Timing Checks (continued)


An * in the table entry means all transitions including transitions to and from x, such
as (??).
The last entry in the table says that whenever the notifier input changes, drive the
output, q of the UDP to unknown. The output will remain x until the next change in
any of the inputs of the UDP.
Since the notifier input is tied in to the notifier register argument of the timing checks,
it would change only when a violation in the timing check toggles it.

12/8/95 Cadence Design Systems, Inc. 15-32


Modeling ASIC Libraries 15-33

Source Protection Mechanism in Verilog

Source protection allows you to protect the proprietary information in a cell


or a design.
There are two ways to protect Verilog source descriptions
Automatically protect all modules.
Protect selected modules or regions within modules.
The protection mechanism creates an encrypted file.

module AND2 protected


:X_F]mZa<Si5e@n\\\]gD1CBVHgagfFp6NkGeFkg:DEH\Dl1NjLblLT\ZGSQnc0?
LVMqBS\7<>LiJ8;=V_nmQ=PYQ7p=Ja^g42][?:B8kAMHfP0o12pnPL?aS5k<>N<p
_\:PeS4Y5;5MZBe31pKkoH[L>onF4YbEi25gb0[N>YISHQ]p_;mGGfq9c=Nn<
SXh;QSebF]<]WXAfTD]c=<N\79YTB45;89JgHIS5\0>F=ql<\=dWf@F739WTD<3P
=A;Xj4fMMjdYlHLQA]^Q;Bj<7I2F\=0UqWO7nbSq\JT$
endprotected endmodule

Source Protection Mechanism in Verilog


Source protection allows you to protect the proprietary information in a cell or a design.
There are two ways to protect Verilog source descriptions
Automatically protect all modules.
Protect selected modules or regions within modules.
The protection mechanism creates an encrypted file and hence it cannot be read by
others.
The encrypted portion is placed between protected and endprotected compiler
directives.

12/8/95 Cadence Design Systems, Inc. 15-34


Modeling ASIC Libraries 15-35

Automatic Protection of All Modules and UDPs


To protect all modules and UDPs in a design the description is compiled with
+autoprotect command line option.
verilog design.v +autoprotect
This creates a new source file that has only the module name readable.
module AND2(a, b, c);
output a;
input b, c;
and a1(a, b, c);
specify
Module name
is unprotected (b => a) = (1.2,2.0,2.8);
(c => a) = (1.4,1.8,2.6);
endspecify
endmodule
module AND2 protected
:X_F]mZa<Si5e@n\\\]gD1CBVHgagfFp6NkGeFkg:DEH\Dl1NjLblLT\ZGSQnc0?
LVMqBS\7<>LiJ8;=V_nmQ=PYQ7p=Ja^g42][?:B8kAMHfP0o12pnPL?aS5k<>N<p
_\:PeS4Y5;5MZBe31pKkoH[L>onF4YbEi25gb0[N>YISHQ]p_;mGGfq9c=Nn<
SXh;QSebF]<]WXAfTD]c=<N\79YTB45;89JgHIS5\0>F=ql<\=dWf@F739WTD<3P
=A;Xj4fMMjdYlHLQA]^Q;Bj<7I2F\=0UqWO7nbSq\JT$
endprotected endmodule

Automatic Protection of All Modules and UDPs


To protect all modules and UDPs in a design the description is compiled with
+autoprotect command line option.
verilog design.v +autoprotect
This creates a new source file that has only the module name readable.
By default the protected file has p appended to the design file name.
design.vp
The extension in name of the new source file can be controlled by specifying the string
with the +autoprotect command line option.
verilog design.v +autoprotect.prot

This will create a protected file called design.v.prot.


The advantage of using autoprotect is that a large number of files with many modules
and UDPs can be protected without having to go into each module description.

12/8/95 Cadence Design Systems, Inc. 15-36


Modeling ASIC Libraries 15-37

Protecting Selected Regions in a Source Description


To protect selected regions of the source description
Place protect and endprotect to mark the region to be protected.
Compile the description with the +protect command-line option.
Protect everything module AND2(a, b, c);
between these output a;
directives input b, c;
protect
and a1(a, b, c);
Module name
and port list specify
is unprotected (b => a) = (1.2,2.0,2.8);
(c => a) = (1.4,1.8,2.6);
endspecify
module AND2(a, b, c); endprotect
output a; endmodule
input b, c;
protected
o]e4dl\DWm30WF^g[\0WM9:ThMk51VI@mCjQ[WYD>6OoC@kk;oICcp0MNa9^;I
_7U4F65I5oC;<D5A@oRSeUdEchC5db63<0p[EG]o3DcMF2I^Ac=eXjG5EaFkWMb\
fRmngKEKBUS6V]UQZR0@2gVB:G6L87[;bp_9YXlFp::0L:ID8hoPDLV>R8Z]OBn
V1h1WSYEqgXD]>m\p]PKIe\]O0\EjNoRGk[fi>TEJ_?NIGd7A>eQ;HN5D;\?gMZ
4o:_qnJ3FKL<T\YZFG>GEnnAm2OOBDA3c;KK[89>m<[5b5e^]]G3:Z[mqVAl^8WJ
$
endprotected
endmodule

Protecting Selected Regions in a Source Description

To protect selected regions of the source description


Place protect and endprotect to mark the region to be protected.
Compile the description with the +protect command line option.
The new file that is created will have the region bound by protect and endprotect
encrypted and the rest will remain unchanged.
The advantage is that the library developer can control the regions in the source
description that need to be encrypted. Typically, the person using the library needs the
port list to use the cell and using the autoprotect mechanism does not solve the problem.
The extension of the protected files can be controlled the same way as autoprotection
control.

12/8/95 Cadence Design Systems, Inc. 15-38


Modeling ASIC Libraries 15-39

Labs

Lab 10 Modeling ASIC Libraries


Modeling a D Flip-Flop with User-Defined Primitives (UDPs)

12/8/95 Cadence Design Systems, Inc. 15-40


Delay Calculation and Backannotation 16-1

Delay Calculation and Backannotation


Objectives
Understand the process of delay calculation and backannotation.
Find out about the Central Delay Calculator.
Find out about Standard Delay Format.

Terms and Definitions

Delay Calculation The process of calculating the delays for each component based
on the loading, drive strength, etc.
Delay The process of placing the delays calculated from an external
Backannotation source into the Verilog data structures.
Programming Programming Language Interface or PLI provides procedural
Language Interface access to the Verilog data structures.
Central Delay Central Delay Calculator or CDC is a common delay calculator
Calculator that is used by all the tools in the design flow.
Timing Driven Complete front-to-back design flow where timing information
Design forms the glue between different stages.
SDF Standard Delay Format
RSPF Reduced Standard Parasitic File
MIPD Module Input Port Delay
SITD Single-Source Interconnect Transport Delay
MITD Multi-Source Interconnect Transport Delay

12/8/95 Cadence Design Systems, Inc. 16-2


Delay Calculation and Backannotation 16-3

Why Delay Calculation and Backannotation?

Only intrinsic delays are independent of the component configuration.


To increase the accuracy of the design, the netlist needs to be probed and
the delays contributed by all the factors need to be calculated.
The following factors contribute to the delays in a design
Intrinsic delays of the components.
The actual loading of each instance of the component.
The parasitic delays of interconnecting wires.
Other factors that might affect the speed of a component, such as fanin,
temperature, voltage, and so on.
Once the delays have been calculated, they need to be annotated in the
design, so that simulation is accurate.

Why Delay Calculation and Backannotation?


Only intrinsic delays are independent of the component configuration. The rest will
differ from one design to another.

12/8/95 Cadence Design Systems, Inc. 16-4


Delay Calculation and Backannotation 16-5

Types of Delay Calculators

PLI based
Custom delay calculators
ASIC vendor supplied
Central delay calculator

Types of Delay Calculators


Programming Language Interface (PLI) Based Delay Calculators
Custom Delay Calculators are written by the designer using the PLI. The delay
equation and the delay calculator written are typically for the use by the designer to
get an idea about the delays through the design.
ASIC Vendor Supplied delay calculators are provided by most ASIC library vendors.
They calculate the delays based on their manufacturing process. Often these are also
written using PLI but use vendor proprietary equations for delay calculation.
Central Delay Calculator (CDC) is a common delay calculator that is used by Cadence
front-end tools and back-end tools.

12/8/95 Cadence Design Systems, Inc. 16-6


Delay Calculation and Backannotation 16-7

Central Delay Calculator


Different toolsOne Delay Calculator.

Design Composition
SDF Annotator

Simulation

SDF User
Synthesis Delays Equation

SDF
Constraints
Simulation Connectivity
Information
CDC
Timing Analysis
RSPF
File
SDF Floor Planner
Constraints
RSPF
File
Place & Route

VerilogDomain

Central Delay Calculator

For a typical timing-driven top-down design methodology, the delay calculation is done
by
Reading connectivity information of the gate-level netlist.
Using the reduced parasitic information from the floor planner.
Using the reduced parasitic information from the place and route tool.
The Verilog domain in the timing-driven top-down design methodology is marked by
the shaded region.
The Central Delay Calculator (CDC) ensures consistency between the front-end and
back-end tools since the common delay calculation algorithm is used for all tools.
Maintenance is easier since only one delay calculator needs to be maintained versus four
if a different delay calculator was being used for each tool (simulation, synthesis, timing,
P&R).
The timing information can be freely used by any tool since it is placed in a Standard
Delay Format (SDF).

12/8/95 Cadence Design Systems, Inc. 16-8


Delay Calculation and Backannotation 16-9

Verilog and CDC

Using the connectivity information, the CDC calculates the approximate


delays.
CDC also calculates delays using parasitic information and places the
calculated delays in the SDF.
The delay values are placed into an SDF file which is read by the Verilog
family of tools using SDF Annotator.

Verilog and CDC

Using the connectivity information, the CDC calculates the approximate delays.
CDC also calculates delays using parasitic information from the back-end tools, like
Place and Route, and Floorplanner. and places the calculated delays in the SDF which
can be read into Verilog data structures.
The delay values are placed into an SDF file.
The SDF annotator reads the timing data from the SDF file and annotates the timing
information to the Verilog family tool using the PLI.

12/8/95 Cadence Design Systems, Inc. 16-10


Delay Calculation and Backannotation 16-11

Standard Delay Format

The Standard Delay Format (SDF) provides a tool-independent uniform way


of representing timing information.
SDF can represent
Module Path Delays - Conditional and Unconditional
Device Delays
Interconnect Delays
Port Delays
Timing Checks
Path and Net Timing Constraints
SDF supports hierarchical specifications.

Standard Delay Format


Delay mapping between some SDF and Verilog constructs:
Verilog-XL
SDF Construct
Path Delay Library Distributed Delay Library
IOPATH PATH LUMPED OUTPUT
PORT MIPD / SITD / MITD MIPD
INTERCONNECT MIPD / SITD / MITD MIPD
NETDELAY MIPD / SITD / MITD MIPD
DEVICE PATH LUMPED OUTPUT

Note: MIPDs describes the delay to a module input or inout port. Delays are inertial and affect three transitions:
to 1, to 0, and to Z.

SITDs are like MIPDs, but with transport delays and with global and local pulse control. SITDs affect six
transitions: 0 to 1, 1 to 0, 0 to Z, Z to 0, 1 to Z, and Z to 1.

MITDs are like SITDs, but allow you to specify unique delays for each source-load path.

12/8/95 Cadence Design Systems, Inc. 16-12


Delay Calculation and Backannotation 16-13

SDF Example
(DELAYFILE
(DESIGN system)
(DATE Mon Jun 1 14:54:29 PST 1992)
(VENDOR Cadence)
(PROGRAM delay_calc)
(VERSION 1.6a,4)
(DIVIDER /) ; Character used as hierarchical dividing character
(VOLTAGE 4.5:5.0:5.5)
(PROCESS worst)
(TIMESCALE 1ns) ; The time units of the delays specified
(CELL
(CELLTYPE system) ; The name of the top level cell
(INSTANCE block_1) ; Instance name for the top level cell
(DELAY (ABSOLUTE
(INTERCONNECT P1/z B1/C1/i1 (.145:.148:.156) (.125:.127:.128)))))
(CELL
(CELLTYPE INV)
(INSTANCE ) ; This specification is for all cells
(DELAY (INCREMENT
(IOPATH i1 z (.345::.348) (.325::.329)))))
)

SDF Example

The header information of the SDF file configures the entire SDF file.
Delay values can be specified for a specific instance of a cell, or for all instances.
Delay values can be either absolute or incremental.

12/8/95 Cadence Design Systems, Inc. 16-14


Delay Calculation and Backannotation 16-15

The SDF Annotator

Verilog Family
Veritime Verilog-XL Verifault-XL

PLI

SDF Annotator

SDF File

The SDF Flow

The SDF Annotator


The SDF annotator reads the timing data from the SDF file and annotates the timing
information to the Verilog family tool through the Programming Language Interface (PLI).
Note: The SDF Annotator supports only the SDF file constructs that are meaningful to the Verilog family tools.

For Example:
>verilog testfixture.v +sdf_verbose +sdf_error_info
Where verilog is the name of the Verilog executable, the name of the Verilog source code is
testfixture.v and the rest of the string are SDF options.
Command Explanation
+sdf_verbose Writes detailed information about the backannotation process to
the annotation log file.
+sdf_error_info This command displays the PLI error messages.

12/8/95 Cadence Design Systems, Inc. 16-16


Delay Calculation and Backannotation 16-17

Running the SDF Annotator


You can run the SDF Annotator from the Verilog test bench file or while you
are in the interactive mode of simulation.
There is a built-in system task within Verilog-XL called $sdf_annotate.
The syntax is as follows:
$sdf_annotate (<sdf_file>,
<module_instance>?,<config_files>?,<log_files>?,
<mtm_spec>?, <scale_factors>?, <scale_type>?);

Note:All the fields except the sdf_file are optional.

The SDF annotator (Continued)


Running the SDF Annotator
SDF_FILE: This is a literal string that identifies the SDF file.
MODULE_INSTANCE: This is optional. This field identifies the specific hierarchical level
of the instance name. If the instance name is not specified then the SDF annotator will use the
module containing the call to the $sdf_annotate system task as the module_instance for
annotation.
CONFIG_FILE: The timing data in the SDF file is controlled through the configuration file.
This is an optional field. If the user does not specify the configuration file then the SDF
annotator will use the default settings.
LOG_FILE: This is optional, it is used to identify the annotation log file.
MTM_SPEC: This is optional. This field is used to specify minimum, typical, and maximum
delay values that are annotated to Verilog. The default for mtm_spec is typical. Note that the
mtm_spec argument overrides the mtm command configuration file.
SCALE_FACTORS: This is optional, it is used to scale the timing information in the SDF
file to the minimum, typical and maximum information that is backannotated to Verilog.
SCALE_TYPE: This is optional and is used for scaling the timing specifications in SDF that
are annotated to Verilog.

12/8/95 Cadence Design Systems, Inc. 16-18


Delay Calculation and Backannotation 16-19

Running the SDF Annotator


The following example shows backannotation with scaling to the top-level design.
module top;
...
circuit m1 (i1,i2,i3,o1,o2,o3);
initial
$sdf_annotate (my.sdf,config,,,1.6:1.4:1.2);
// Apply stimulus and response checking
...
endmodule

timescale 1ns/1ns
module top (ck,d1,q1);
...
dff u2 (q1,ckin,d1);
buffer1 u1 (ckin,ck);
...
initial
begin
$sdf_annotate ("sdffiles/iopath.sdf", , ,"logfiles/sdf.log");
$sdf_annotate ("sdffiles/timingcheck.sdf", ,logfiles/sdf.log);
$sdf_annotate ("sdffiles/port.sdf", , ,"logfiles/sdf.log");
$sdf_annotate ("sdffiles/interconnect.sdf", , "logfiles/sdf.log");
end

Running the SDF Annotator


The other way of running the SDF annotator is to show separate backannotation to distinct
portions of a design hierarchy. There is no configuration file specification; therefore, the SDF
annotator uses the defaults.

12/8/95 Cadence Design Systems, Inc. 16-20


Modeling to Achieve Simulation Performance 17-1

Modeling to Achieve Simulation Performance


Objectives
Learn about different Verilog algorithms.
Introduce Verilog-XL Turbo and Twin Turbo.
Understand the relationship between modeling styles and performance.
Use the Behavioral profiler.

Terms and Definitions

Turbo Algorithm The Turbo algorithm accelerates behavioral-level simulation.


XL Algorithm The XL algorithm accelerates the simulation of gate-level and
switch-level (unidirectional switches) descriptions.
Non-XL Algorithm The non-XL algorithm does not provide any acceleration.
Switch-XL The Switch-XL algorithm accelerates the simulation of
bidirectional switches.
UDP User-Defined Primitive

12/8/95 Cadence Design Systems, Inc. 17-2


Modeling to Achieve Simulation Performance 17-3

The Turbo and the XL Algorithm

The Turbo algorithm accelerates the simulation of behavioral-level


descriptions.
The XL algorithm accelerates the simulation of gate-level and switch-level
(unidirectional switches) descriptions.

The Turbo and the XL Algorithm

The Turbo Algorithm


The Turbo algorithm accelerates behavioral-level simulation. The simulation speed is
proportional to the number of behavioral statements in your source description.
Gate-level simulation is NOT affected by the Turbo feature.
The XL algorithm
The XL algorithm provides accelerated gate-level and switch-level simulation.
The XL algorithm accelerates nets declared without the vectored keyword, standard
primitives, and user-defined primitives.

12/8/95 Cadence Design Systems, Inc. 17-4


Modeling to Achieve Simulation Performance 17-5

Default Algorithm Flow Chart

Start

Turbo No
Option

Yes

Turbo
license No
available?
Yes
XL license No
available?
Run Turbo
with 5-7X Yes NO LICENSE
available

Run XL

Default Algorithm Flow Chart


When you initiate a simulation, determine whether you will use a Turbo license or a
Verilog-XL license.
You use the +no_turbo plus option to force the selection of the XL algorithm. If an XL
license does not exist, then you are notified that there is no license available. If the XL
license exists, then an XL simulation is run.
When you omit the +no_turbo option from the command line, the software will first
check to see if a Turbo license exists. If one exists, it is used for the simulation. If there
are no Turbo licenses available, then a check is made to see if the XL license is available
(see above).

12/8/95 Cadence Design Systems, Inc. 17-6


Modeling to Achieve Simulation Performance 17-7

Controlling Acceleration

Command line Option Application


+caxl Accelerates the simulation of continuous
assignments.
+switchxl Accelerates the simulation of bidirectional switches.
+no_turbo Disables the Turbo algorithm.

Controlling Acceleration
+caxl: The plus option +caxl accelerates continuous assignments that conform to some
restrictions.
+switchxl: The +switchxl plus option invokes the Switch-XL algorithm to accelerate the
simulation of bidirectional switches.
+no_turbo: This option disables the Turbo algorithm and makes Verilog apply the XL
algorithm.

12/8/95 Cadence Design Systems, Inc. 17-8


Modeling to Achieve Simulation Performance 17-9

The Four Levels of Turbo

Level Option Effect


default Turbo <none> Extension of the speed enhancements which are
mode in the 1.6x +speedup option. The event count and
the profiler are enabled.
1st level of +turbo Turns off the event count and the profiler. These
extended Turbo two small changes will increase performance by
5-10%.
2nd level of +turbo+2 Has alternative algorithm changes which will
extended Turbo almost always increase performance and will
always guarantee event ordering to match
Verilog-XL.
3rd level of +turbo+3 Can affect event ordering, and in designs which
extended Turbo rely on event ordering, the simulation results may
be different. In most cases, this will not be an issue
and the designs achieve a significant speed
improvement when using this highest level of
Turbo.

The Four Levels of Turbo


With Verilog-XL Turbo, a wide range of basic speed improvements are used.
Three plus options are available to select a level of Turbo above the default level, giving
the users an easy way to select the appropriate speed improvement for their design
environments.

12/8/95 Cadence Design Systems, Inc. 17-10


Modeling to Achieve Simulation Performance 17-11

Using Turbo with Other Performance Options

If a simulation runs significantly faster with the other performance options prior to
using Turbo, then using them with Turbo still yields better overall performance.

Turbo Algorithm
XL Algorithm
+caxl
+switchxl

Simulation Performance Generally Improved

Using Turbo with Other Performance Options


As a general rule, the Turbo feature increases simulation performance, regardless of the
use of the other command line options. The Turbo feature improves the performance of
only non-gate constructs of Verilog-XL.
When using the Turbo feature, the best results occur when the XL algorithm is used.
There is a trade-off associated with switching between the XL and any non-XL
algorithm, but as long as there is enough activity in XL, the speed improvement due to
the XL algorithm compensates for the overhead of switching between the XL and
non-XL algorithms.
The same argument can be made for using the +switchxl option. The +switchxl
algorithm applies only to gate constructs which are not affected by Turbo. If the
+switchxl option is of a benefit prior to using the Turbo feature, then the combination of
both +switchxl and Turbo will yield even better results.
The Turbo feature improves the simulation performance of continuous assignments. The
continuous assignments are evaluated faster in +caxl than in Turbo. In general, the
pattern of performance improvement with the +caxl option is the same as with the other
options. If a simulation runs significantly faster with the +caxl option prior to using
Turbo, then using +caxl with Turbo still yields better overall performance.

12/8/95 Cadence Design Systems, Inc. 17-12


Modeling to Achieve Simulation Performance 17-13

Twin Turbo

The Twin Turbo option +twin_turbo, causes the simulation to generate and
utilize compiled code for processing behavioral constructs in the selected
Turbo mode.
The Twin Turbo functionality operates in conjunction with each of the
existing Turbo modes.

Twin Turbo
The terms compiled code simulation and interpreted simulation refer to the way in which a
simulator operates on a designs source description. An interpreted simulator reads the source
code of a design/stimulus description and from it, builds an internal representation or data
structure of primitive operations. During simulation, these operations representing the
designs behavior are interpreted, or processed by the simulator, one at a time.
A Compiled Code (CC) simulator converts the HDL description into a computer program,
then executes the program to run the simulation. Many CC simulators convert the HDL
description into a standard programming language and then use the machine compiler to
convert the program into an executable.
The Twin Turbo mode is a Direct Compiled Implementation that converts the description
directly into machine code, thus bypassing the inefficient step of running the standard
compiler. With the introduction of Twin Turbo mode in the Verilog-XL Turbo 2.1 release,
performance enhancements have been added by augmenting Turbos interpreted simulation
method with a new compiled code implementation. In Twin Turbo mode, machine code
instructions are generated for all behavioral source code prior to simulation. During
simulation, machine instruction sequences representing behavioral code execute at the system
speed of the host computer. The compiled code executes considerably faster than the
interpreted pseudocode utilized in the Turbo mode, yet all of the flexibility and interactive
debugging capabilities are maintained.
Note: For more information see Appendix A, "Verilog-XL Twin Turbo Mode".

12/8/95 Cadence Design Systems, Inc. 17-14


Modeling to Achieve Simulation Performance 17-15

+twin_turbo (continued)
OPTIONS LEVEL EFFECT
+twin_turbo Twin Turbo extension -$listcounts disabled
of default Turbo mode -Twin Turbo optimizations
+twin_turbo with Twin Turbo extension -Default Turbo mode
+turbo of first-level Turbo mode optimizations
-Twin Turbo optimizations
+twin_turbo with Twin Turbo extension -Assignment optimizations
+turbo+2 of second-level Turbo -Scalar to compact node
mode conversion
-First-level Turbo mode
optimizations
-Twin Turbo optimizations
+twin_turbo with Twin Turbo extension -Delayed evaluation of
+turbo+3 of third-level Turbo mode complex continuous
assignment expressions
(can impact event order)
-Second-level Turbo mode
optimizations
-Twin Turbo optimizations

+twin_turbo (continued)
The Twin Turbo functionality operates in conjunction with each of the existing Turbo modes.
Specifying the Twin Turbo option causes the simulation to generate and utilize compiled code
for processing behavioral constructs in the selected Turbo mode. Because Twin Turbo is an
extension of the existing Verilog-XL Turbo capability, no additional licensing is required. The
VXL-TURBO feature string in the license file supports both Turbo and Twin Turbo.

12/8/95 Cadence Design Systems, Inc. 17-16


Modeling to Achieve Simulation Performance 17-17

The XL Algorithm

The XL algorithm accelerates primitives and net types:

supported primitives:
buf and xor not nand xnor or nor
bufif0 bufif1 notif0 notif1

nmos pmos cmos rnmos rpmos rcmos


pullup pulldown

user-defined combinational and sequential primitives

supported net types:


wire wand wor trireg triand
tri tri0 tri1 trior supply0 supply1

The XL Algorithm
The table above shows the primitives and net types that the XL algorithm accelerates.
The XL algorithm also accelerates UDPs.
Any unsupported items are automatically processed by the non-XL algorithm.
Specifying the driving strength of gate has no impact on whether or not the XL algorithm
can accelerate it.

12/8/95 Cadence Design Systems, Inc. 17-18


Modeling to Achieve Simulation Performance 17-19

Items Unsupported by the XL Algorithm

The bidirectional primitives


tran tranif0 tranif1 rtran rtranif1 rtranif0.
The buf and not gates with more than one output
Nets with non-zero delay
More than 32767 distinct gate delays
Primitives that have non-constant (or dynamic) delay expressions
Primitives with an expression involving any kind of operator on an input
Vectored nets declared with the vectored keyword
Any net that has a continuous assignment made to it
Any forced net

Note:$shownonxl() system task locates non-XL structures.

Items Unsupported by the XL Algorithm


The bidirectional primitives shown above are not accelerated by the XL algorithm.
However, you can accelerate them by using the Switch-XL algorithm.
The buf and not gates with more than one output are not accelerated.
Nets with non-zero delay are not accelerated. The XL algorithm can support no more
than 32767 distinct gate delays. Once this limit is reached during compilation, any
subsequent gates with distinct delays cannot be accelerated.
Primitives that have non-constant (or dynamic) delay expressions are not accelerated.
Primitives with an expression involving any kind of operator on an input are not
accelerated.
Vectored nets (nets declared with the vectored keyword) are not accelerated.
Any net that has a continuous assignment made to it, is not accelerated unless the +caxl
option is used.
Any forced net is not accelerated; that is, a net may start out as an accelerated net but
once a force statement is activated on it, it can no longer be accelerated, even after it is
released.
Note: The $shownonxl() system task locates non-XL structures. The parentheses in the system task can contain no
argument, or they can hold the instance name of a module. If the parentheses contain no argument, the
$shownonxl task searches the entire simulation in which you invoke it for non-XL structures. If the
parentheses contain the instance name of a module, the scope of the $shownonxl is limited to the named
module.

12/8/95 Cadence Design Systems, Inc. 17-20


Modeling to Achieve Simulation Performance 17-21

XL Algorithm Performance Considerations

Create Verilog models that minimize behavioral activity as in this example.


....
buf (w1,i1);
not #1 (w2,w1); The behavioral engine
assign w3 = w1 | w2; evaluates this assignment. Use
the +caxl option or convert the
nand #2 (w4,w3,w2); assignment to gates.
...vt
Use the largest timescale unit possible.
Use sequential UDPs to model storage devices.

XL Algorithm Performance Considerations


With XL circuits it is important to structure the Verilog models to minimize behavioral
activity. Moving from one simulation engine to another can be costly (for example, to
move from XL to Behavioral or from Behavioral to XL).
Try to eliminate behavioral constructs whenever possible in an XL design. In the above
example, the XL not gate fans out to the assignment and also to the nand gate. The
behavioral engine evaluates the continuous assignment, unless you
Use the +caxl option (this option lets Verilog-XL convert the assignment to gates).
Convert the assignment to gates by hand.
When modeling in XL, try to use the largest timescale unit possible. Very small
timescale units use large amounts of memory in delay-table generation.
Try to minimize the use of behavioral constructs to model flip-flops. Sequential UDPs
provide a much faster solution to modeling storage devices.

12/8/95 Cadence Design Systems, Inc. 17-22


Modeling to Achieve Simulation Performance 17-23

Turbo Algorithm Performance Considerations

Group statements of like delay when using RTL statements.

Efficient RTL Less Efficient RTL


a <= #1 b; a <= #1 b;
c <= #1 d; Statements of like delay
i <= #2 j;
e <= #1 f; (#1) are grouped c <= #1 d;
g <= #1 h; k <= #2 m;
i <= #2 j; Statements of like delay e <= #1 f;
(#2) are grouped
k <= #2 m; g <= #1 h;
.... ....

Keep XL gates grouped together.


Minimize use of fork/join statements and named blocks.

Turbo Algorithm Performance Considerations


When using RTL statements it is much more efficient to group statements with the same
delay. This allows Verilog-XL to optimize the scheduling associated with these
statements.
When designing a mostly behavioral model, it is important to try to keep XL gates
grouped together. It can be more efficient to place an assignment in the middle of a
behavioral circuit then to model with XL gates.
To obtain maximum performance on behavioral designs the designer should try to
reduce the generation of unnecessary schedules. The overuse of fork/join statements and
named blocks can harm simulation performance.

12/8/95 Cadence Design Systems, Inc. 17-24


Modeling to Achieve Simulation Performance 17-25

Achieving Optimal Performance


Several optimizations can be implemented to improve the performance of the
design. In general, the focus should be on keeping the number of scheduled
events as low as possible. The methods of optimization are:
File I/O and debug statements
It is generally best to minimize the use of debug statements that write to file
or display information.
Flow control
Better performance can be achieved by reducing the simulators workload.

always @(clk)
begin
always @(clk)
if (status == 2b00)
case(status)
out = Y;
2b00: out = Y;
if (status == 2b01)
2b01: out = A;
out = A;
2b10: out = 1bz;
if (status == 2b10)
2b11: out = B;
out = 1bz;
endcase
if (status == 2b11)
out = B;
end

Achieving Optimal Performance


You can optimize your code to improve the performance of a design. In general, your focus
should be on keeping the number of scheduled events as low as possible. The methods of
optimization are:
Use of file I/O and debug statements
Although the performance of file I/O system tasks such as $monitor and $display has
been improved, it is generally best to minimize the use of debug statements that write to
file or display information. Because of the relatively slow access to the computers
devices, calls to file I/O system tasks can significantly affect simulation performance.
Flow control
Better performance can be achieved by reducing the simulators workload. For example,
combining several if statements into a single case statement causes the simulator to
evaluate the case statement once to understand the branching condition. If a sequence of
if statements is used instead, the simulator has to evaluate the conditions repeatedly.

12/8/95 Cadence Design Systems, Inc. 17-26


Modeling to Achieve Simulation Performance 17-27

Achieving Optimal Performance (continued)


Procedural block grouping
always@(posedge clk)
Y = C + D; always@(posedge clk)
begin
always@(posedge clk) Y = C + D;
Z = A * B; Z = A * B;
X = E + F;
always@(posedge clk) end
X = E + F;

Event control

always@(posedge clk) always@(d)


q = d; @(posedge clk)
q = d;

Use of non-behavioral constructs

Since non-behavioral constructs are not accelerated by Turbo or Twin


Turbo modes, they detract from the simulations overall performance gain in
these modes.

Achieving Optimal Performance (continued)


Procedural block grouping
Where possible, consolidate multiple procedural blocks that are triggered by the same
conditions. For example, in synchronous designs many procedural blocks that are
triggered only by the positive edge of the system clock can be consolidated for more
efficient processing.
Event control
Inefficient use of event controls may cause the simulator to unnecessarily execute a
particular statement or group of statements. Careful attention to specifying the
conditions when procedural blocks execute ensures the desired functionality in the
fewest possible scheduled events. Of course, if a synthesis tool is used, the HDL rules
must not be violated.
Use of non-behavioral constructs
Because non-behavioral constructs are not accelerated by Turbo or Twin Turbo modes,
they detract from the simulations overall performance gain in these modes. Two
common sets of constructs that detract from Turbo and Twin Turbo performance are
instances of gate and UDP primitives and system tasks and functions, including PLI
applications. If speed does not improve as expected, the simulation must be profiled
using the behavioral profiler (described in the next section) to determine where the
simulator is spending its time.

12/8/95 Cadence Design Systems, Inc. 17-28


Modeling to Achieve Simulation Performance 17-29

The Behavioral Profiler

The best tool for finding behavioral model performance problems.


The behavioral profiler identifies the modules and statements in your
behavioral source description that use the most CPU time during simulation.

The Behavioral Profiler


The Behavioral Profiler is the best tool for finding behavioral model performance
problems.
The behavioral profiler identifies the modules and statements in your behavioral source
description that use the most CPU time during simulation. Once you have this
information, you can investigate rewriting these constructs so that your design will
simulate faster.

12/8/95 Cadence Design Systems, Inc. 17-30


Modeling to Achieve Simulation Performance 17-31

The Behavioral Profiler

Four system tasks for the behavioral profiler.


$startprofile: begins or resumes collecting data.
$reportprofile: reports this data before the end of the simulation.
$stopprofile: stops collecting this data.
$listcounts: produces a source listing with both the line numbers and the
execution count for each line.

The Behavioral Profiler


There are four system tasks for the behavioral profiler:
$startprofile, $reportprofile, $stopprofile, $listcounts
The $startprofile system task tells Verilog-XL to begin or resume collecting behavioral
profiler data.
The $reportprofile system task tells Verilog-XL to report this data before the end of the
simulation.
The $stopprofile system task tells Verilog-XL to stop collecting this data. Enter
$reportprofile or $stopprofile after $startprofile.
The $listcounts system task is an enhancement of $list.
It produces a line-numbered source listing that includes an execution countthe
number of times Verilog-XL executes the statements in the line.
You can enter $listcounts before or after $startprofile.
The $listcounts task is disabled unless you include the +listcounts option or the
+no_speedup option on the command line.

12/8/95 Cadence Design Systems, Inc. 17-32


Modeling to Achieve Simulation Performance 17-33

Running the Verilog Profiler


module rega;
reg a; module test;
rega inst1();
initial regb inst2();
begin
a=1; initial
forever begin
#1 a = ~a; $listcounts(inst1);
end $listcounts(inst2);
endmodule $listcounts;
#10 $startprofile;
module regb; #1000 $reportprofile;
reg b; $finish;
end
initial endmodule
begin
b=1;
forever
#10 b = ~b;
end
endmodule

Running the Verilog Profiler


When Verilog-XL executes the $startprofile system task, the behavioral profiler begins
to take samples of your source description. A sample is a snapshot of your design.
When the behavioral profiler takes a sample, it performs the following functions:
Interrupts the process.
Scans the Verilog-XL data structure to determine the source file line that the CPU is
executing.
Continues the process.
The behavioral profiler records the number of samples it takes of each line. By default,
the behavioral profiler takes a sample every 100 microseconds of CPU time.
There is a relationship between the number of samples the behavioral profiler records
for a line and the amount of CPU time used by that line. The more samples of a line in
your source description, the more CPU time is used by that line.

12/8/95 Cadence Design Systems, Inc. 17-34


Modeling to Achieve Simulation Performance 17-35

Running the Verilog Profiler (continued)


Profile ranking by statement:

Self% Cum.% Samples Statement


----- ----- ------- -----------------------
40.0% 40.0% 2 profile.v, L8, test.inst1
20.0% 60.0% 1 profile.v, L20, test.inst2
20.0% 80.0% 1 XL
20.0% 100.0% 1 profile.v, L8, test.inst1
Total samples in report: 5

Profile ranking by module instance:

Self% Cum.% Samples (Self + submodules) Instance


----- ----- ------- ------------------- --------
60.0% 60.0% 3 ( 60.0% 3) test.inst1
20.0% 80.0% 1 ( 20.0% 1) test.inst2

Profile by statement type:

Self% Cum.% Samples Statement type


----- ----- ------- --------------
60.0% 60.0% 3 assign_stat
20.0% 80.0% 1 OTHERS
20.0% 100.0% 1 delay_stat

L35 profile.v: $finish at simulation time 1010


3349 simulation events
CPU time: 1.9 secs to compile + 0.2 secs to link + 0.2 secs in simulation
End of VERILOG-XL 1.6c.5 Aug 10, 1993 16:54:41

Running the Verilog Profiler (continued)


The Verilog-XL simulator displays behavioral profiler data in three tables:
Profile ranking by statement
Profile ranking by module instance
Profile ranking by statement type
The Self% column indicates the percent of the total number of samples that represent the
line listed in the Statement column (referring to the profile ranking by statement).
The Cum.% column indicates the percent of samples that represent the line listed in the
Statement column plus the preceding lines.
The Samples column indicates how many samples of the line were found.

12/8/95 Cadence Design Systems, Inc. 17-36


Verilog Environment 18-1

The Verilog-XL Graphical Environment

Objectives
Learn about the Verilog-XL Graphical Environment
Verilog Control Window (VCW)
cWaves
Language Sensitive Editor (LSE)
Hierarchy Browser (HB)
Verilog Results Analyzer (VRA)

Terms and Definitions

Verilog Control A Motif compliant graphical interface. Use the VCW to advance
Window (VCW) and interrupt simulation, break into and alter simulation, control
scope and so on.
cWaves The Cadence waveform viewing tool. Shows simulation results
graphically as waveforms.
Language Sensitive The LSE lets you enter, analyze and debug a Verilog description.
Editor (LSE) When run as part of the environment, you can use the LSE to
select signals for interaction with simulation. The LSE also offers
a subset of the interactions with simulation that the VCW
provides.
Hierarchy Browser A graphical tool for navigating through a design and for
(HB) traversing the various scopes within the design.
Verilog Results A graphical window that lets you invoke cWaves, the LSE, and
Analyzer (VRA) the HB to analyze the results of simulation jobs run in batch
mode.
TMS Text Management System

12/8/95 Cadence Design Systems, Inc. 18-2


Verilog Environment 18-3

Invoking the Environment

Use +venv to invoke the complete environment (VCW and LSE with access to
cWaves and HB).
% verilog +venv <command_line_options> <design_files>

Use +vcw to invoke the VCW without the other environment windows.
% verilog +vcw <command_line_options> <design_files>

Invoking the Environment

Use +venv if you want access to the complete environment. This invokes the VCW and
the LSE with the source description of the top-level module. The VCW includes the
Tools menu, which allows you to invoke cWaves and the Hierarchy Browser.
Use +vcw if you want to invoke only the VCW.

12/8/95 Cadence Design Systems, Inc. 18-4


Verilog Environment 18-5

VCW
Toolbox and
Messages Selection
Pull-Down
Fixed Status
Menus Area Transcript
Menu

VCW
The VCW contains six areas:
Seven pull-down menus available at the top of the VCW. (The Tools menu is not
available if you invoke the environment with +vcw).
The fixed menu on the left-hand side of the VCW. Fourteen buttons provide quick
access to common interactive operations.
The Toolboxes and Selection areas enable you to set breakpoints or implement post
selection.
The Status area provides information about the progress of simulation.
The Message window displays messages concerning your interaction with the
simulation.
The Transcript area displays the output from interactive simulation. You can also enter
interactive commands at the prompt.

12/8/95 Cadence Design Systems, Inc. 18-6


Verilog Environment 18-7

VCW
Use the VCW pull-down menus and fixed menu to:
Advance and interrupt simulation
Show the values of signals
Show source
Control scope
Break into and alter simulation

VCW

12/8/95 Cadence Design Systems, Inc. 18-8


Verilog Environment 18-9

Selecting Objects

Two selection modes:


Preselection
1. Select object(s).
2. Press command button or select pull-down menu item.

Post selection
1. Press command button or select pulldown menu item.
2. Select object in LSE. Verilog-XL executes the command.
3. Select next object.
4. Press the Post Selection: Done button in the Toolbox and Selection Area.

Selecting Objects

For post selection, no object can be selected before you select the command.

12/8/95 Cadence Design Systems, Inc. 18-10


Verilog Environment 18-11

Selecting Objects (continued)

Three basic ways to select objects:


Select objects in the LSE.
Double click on object.
Hold down Shift key to select multiple objects.
Drag cursor across multiple lines.
Select entire classes or subclasses using Selections menu.
Select objects in X windows.
Use X window copy and paste.

Selecting Objects (continued)

To select objects in X windows, use Customize Preferences and make sure the
Use in VCW Selection option is on.
If you use Post Selection mode, select objects in the LSE (for example, X window
selection does not work).

12/8/95 Cadence Design Systems, Inc. 18-12


Verilog Environment 18-13

File Menu

SHM: Open, save, rename, or close an SHM database.


Reinvoke: Reinvoke Verilog-XL (only with +venv).
Quit Env: Exit the environment.
If you invoke only the VCW with +vcw, this entry is Quit VCW.

File Menu
Accessing SHM databases:
File SHM Open: Open a new SHM database or specify an existing database.
File SHM Save: Save the currently open SHM database with its current name.
File SHM Save As: Save the currently open SHM database to another SHM
database that you specify. Renaming the SHM database with the name of a preexisting
database overwrites the preexisting database.
File SHM Close: Save and close the currently open SHM database.
Reinvoking:
File Reinvoke: Reinvoke Verilog-XL using the same command line options on the
same design in the same working directory. Current breakpoints remain set, and the
currently probed signals remain displayed on the waveform display. Preferences set on
any menu are also saved. Allows you to quickly patch or change a design, recompile
it, and then resimulate up to the original problem.
Quitting:
If you invoked with +vcw, use File Quit VCW to exit the VCW.
If you invoked with +venv, use File Quit Env to exit the environment.

12/8/95 Cadence Design Systems, Inc. 18-14


Verilog Environment 18-15

Run Menu

Continue (Interrupt): Interrupts ongoing simulation or restarts interrupted


simulation.
Event Step: Advances simulation by event.
Source Step: Advances simulation by source line.
Reset to Time Zero: Resets to time zero and returns all values to their initial
states.
Finish: Completes simulation.
Defaults: Allows you to set the default number of event steps for the
Event Step command (or Step button).

Run Menu
Continue/Interrupt (Continue/Interrupt button): Allows you to continue or interrupt
simulation. Interrupt puts the simulation in interactive mode, in which all objects are
frozen in their current states. Continue resumes simulation.
Event Step (Step button): By default, advances simulation by one event. To adjust the
number of events:
Select Run Defaults Step and manipulate the Step Increment slider.
Click on the Step button with the right mouse button and select the number of steps.
Source Step: Advances simulation to the next point with one of the following
characteristics:
Gate or switch output is determined
One or more statements within a behavioral construct are about to undergo evaluation
To control the number of source steps, manipulate the slider in the Step Defaults form
generated by Run Defaults Step.
Reset to Time Zero: Returns all values to their initial states. Use the Continue button
to resume simulation. Preserves breakpoints but clears scope. No recompilation.
Finish: Completes simulation. Leaves the VCW up so that you can review the transcript,
but does not save a Verilog-XL data structure.
Defaults: Pops up the Step Defaults form, which you use to set the default number of
event steps for the Event Step command or the Step button.
12/8/95 Cadence Design Systems, Inc. 18-16
Verilog Environment 18-17

Show Menu

Display Values (Display button): Shows the values of selected signals.


Monitor (Monitor button): Continuously shows the value changes of signals.
Show Variables (Show Var button): Shows the current status for a signal(s).
Waveform...: Invokes cWaves.
Show Scopes (Scopes button): Show all scopes at the current level.
Read Source (Read Src button): Reads the source for the currently selected
scope.
Trace On/Trace Off (Trace On/Trace Off button): Turns tracing on or off.
History: Prints a list of prior interactive commands.
Defaults: View and set defaults for Display, Monitor, Waveform,
Read Source.

Show Menu
Display Values: Implements $display. Use Show Defaults Display to do the
formatting.
Monitor: Implements $monitor. Show Monitor Monitor Off ends the
monitoring. Use Show Defaults Monitor to do the formatting.
Show Variables: Implements $showvars. Use Customize Preferences to configure.
Waveform...: There are three ways to invoke cWaves from the VCW:
Show Waveform.
Waveform button.
Tools cWaves. This brings up an empty cWaves window.
Show Scopes: Implements $showscopes.
Read Source: In the environment, output appears in the LSE. For standalone, output
appears in the Transcript as decompilations of source code ($list).
Show Defaults Read gives you a choice of reading the source in the LSE, the
Transcript, or both.
Trace On: Shows the course of simulation. Information includes current simulation
time, location in the source file of the active statement, decompilation of the statement,
and result of executing the statement.
History: Type the command number to re-execute (for example, C11 $showscopes;).
Defaults: Allows you to view and set defaults for the Display Values, Monitor,
Waveform, and Read Source commands.

12/8/95 Cadence Design Systems, Inc. 18-18


Verilog Environment 18-19

Set Menu

Breakpoint...: Sets time, source line, or signal-based breakpoints.


Patch... (Patch button): Assigns values to signals.
Release: Releases specified signals from existing patches.
Value...: Sets the values of registers.
Scope (Set Scope button): Sets the interactive scope.
Focus: Sets focus.
Defaults: Sets defaults for the Breakpt button.

Set Menu
Breakpoint...: Generates a form that lets you set time, source line, or signal-based
breakpoints.
Patch...: Implements a force. Assigns values to signals independent of the simulation
process. Can assign 0, 1, X, Z, or an expression. Use Set Release to remove a patch.
Release: Releases currently patched signals.
Value...: Sets values of registers. Any assignment to a register makes it lose the value
setting. Can assign 0, 1, X, Z, or an expression. Use Verilog syntax for the value (1bz).
Scope: Implements $scope.
Up button sets scope to the parent of the current scope.
Pop button moves to next lower scope. Use the right mouse button to view and select
a scope.
Focus: Source stepping is active only within the current foci.
Defaults: Sets defaults for the Breakpt button, which allows you to set signal-based
breakpoints.

12/8/95 Cadence Design Systems, Inc. 18-20


Verilog Environment 18-21

Customize Menu

Preferences...:

Customize Menu
User Preferences form: Configures the selection function associated with interactive
operations.
X Primary Selection
(Use in VCW Selection)
Invokes the operation on objects selected in X windows outside the environment.
Selections in the LSE override selections in X windows.
X Primary Selection
(Use for Seeding Forms)
Makes X windows selections appear on popup forms. Selections in the LSE override
selections in X windows.
Selection Scheme: Prompt Mode
Makes the operation generate a form that enables you to choose multiple signals by
typing their names or by selecting them in the LSE.

12/8/95 Cadence Design Systems, Inc. 18-22


Verilog Environment 18-23

Tools Menu

cWaves: Invokes cWaves.


Hierarchy Browser: Invokes the Hierarchy Browser.
LSE: Invokes the LSE.

Tools Menu

12/8/95 Cadence Design Systems, Inc. 18-24


Verilog Environment 18-25

Help Menu

The Help menu contains four items:


Verilog Help: User guide task-oriented help.
Whats New: Product Notes and Known Problems and Solutions.
Related Products: Online help for cWaves, HB, LSE.
About Help: Explanation of how to use the online help system.

Help Menu
Verilog Help: Task oriented help on modeling, verifying your design, controlling
Verilog, debugging, improving performance, and so on.
Click on About Help at the bottom of the help screen for detailed information on how
to use this help system.
Related Products: No online help available for LSE.
About Help: Explanations on how to use bubble help and hypertext links to
documentation.
Bubble help. Point at any item and:
Shift and press the middle mouse button.
Help key
Hypertext links to documentation for Verilog, cWaves, Hierarchy Browser

12/8/95 Cadence Design Systems, Inc. 18-26


Verilog Environment 18-27

Setting Breakpoints in the VCW

Breakpt button
Set Default Breakpoints

Set Breakpoints

Breakpoints Toolbox

Setting Breakpoints in the VCW


Breakpoints are predefined events that stop simulation but leave all objects in their current
mode so you can interact with simulation. There are three kinds of breakpoints:
Time-Based
Simulation stops when a specified simulation time is reached. This is the default.
Source-Line Based
Simulation stops when a specified source line is reached. You must specify the scope,
file name, and line number.
Signal-Based
Simulation stops when a specified signal changes value or when a specific transition
occurs.
The VCW offers three methods for setting breakpoints:
Breakpt button (Signal-based, Set defaults with SetDefaultsBreakpoints)
Set Breakpoints (Time, source line, signal-based)
Breakpoints toolbox (Time, source line, signal-based)

12/8/95 Cadence Design Systems, Inc. 18-28


Verilog Environment 18-29

The Language Sensitive Editor (LSE)

LSE is an Emacs-based program that can be run:


Standalone to help you write syntactically correct Verilog descriptions
(Entry and Analysis mode).
Built-in templates for all Verilog constructs
Syntax checking and feedback on errors
Navigation through errors
Text editing in Emacs or vi modes
As part of the Verilog-XL Graphical Environment (Debug mode).
Source code browser
Navigation through design hierarchy
Control aspects of simulation, such as stepping and setting breakpoints
Make selections in the source code and operate on those selections in
the VCW

The Language Sensitive Editor (LSE)


The LSE is based on Lucid Emacs (lemacs), which is public domain software. Cadence
provides lemacs as part of the installation hierarchy.
You can use the LSE in two ways:
Run it standalone to help you enter and analyze your Verilog description.
Open a new or existing description file.
Use the templates to create a new description or add to an existing one.
Save and analyze the description.
Run it as part of the Graphical Environment.
View the module descriptions.
Navigate through the hierarchy.
Make selections.
Control some aspects of the simulation.

12/8/95 Cadence Design Systems, Inc. 18-30


Verilog Environment 18-31

Invoking the LSE

Standalone:
% lemacs filename.v

As part of the Verilog-XL environment:


% verilog +venv [command-line options] [design files] &

Invoking the LSE


Standalone:
% lemacs filename.v
This starts a standard lemacs process that recognizes files with the .v extension as
Verilog descriptions.

As part of the Verilog-XL environment:


% verilog +venv [command-line options] [design files] &
This brings up the VCW and the LSE.
Note: If you already have an LSE session running, the VCW connects to the active session instead of starting
another LSE session.

12/8/95 Cadence Design Systems, Inc. 18-32


Verilog Environment 18-33

Entry and Analysis Mode

Use the LSE to enter and analyze your Verilog description.


1. Open a new or existing description file.
% lemacs filename.v

2. Use the templates to create a new description or add to an existing one.

mod <TAB> => module


<TAB> => module <textenter:module_name> <#port-list>;
<#module-declarations>
<#module-body-items>
endmodule
register <RET> => module register <#port-list>;
r,clk,data,ena,rst <RET> => module register ( r, clk, data, ena, rst );

3. Select Analysis Save & Analyze to save and analyze the description.

Entry and Analysis Mode

Save and analyze the description.


Analyzer checks the file for errors.
LSE window is split in two: errors highlighted in upper window, results of analysis in
bottom window.
Use Analysis Next Error and Analysis Previous Error to navigate through the
errors.
Analysis Error Utilities Explain Source Error can provide useful information.

12/8/95 Cadence Design Systems, Inc. 18-34


Verilog Environment 18-35

Debug Mode
When used with the VCW as part of the environment, the LSE:
Acts as a source code browser
Provides the Debug, Selections, and Hierarchy menus, which allow you to:
Interrupt/Continue
Step
Reset
Set scope
Set, disable, enable, and delete source or signal breakpoints
Select or clear classes and subclasses of objects
Navigate through the design hierarchy

Debug Mode

12/8/95 Cadence Design Systems, Inc. 18-36


Verilog Environment 18-37

Hierarchy Browser
Lets you browse your design hierarchy.
Synchronized with other tools, such as LSE, so that selections from any tool are
reflected in the other tools.
To invoke the HB, use Tools Hierarchy Browser. The HB displays the top
level of your design.

Hierarchy Browser

12/8/95 Cadence Design Systems, Inc. 18-38


Verilog Environment 18-39

Hierarchy Browser (continued)


As you display lower levels of your design, HB creates a tree structure, with each
node of the tree being a scope within your design hierarchy.
Expanding/collapsing hierarchical blocks:
To display subscopes, double click on an unexpanded block.
To hide subscopes, double click on an expanded block.
Selecting/deselecting nodes:
Single click on a node to select a node.
Press the Control key and click the left mouse button to deselect a node.
Select Customize Defaults to specify display options.

Hierarchy Browser (continued)


To read the source for the selected node into the LSE, click the right mouse button and
select Read Source.
To set scope with the HB:
Single click on the node you want and then select Set Scope (or press the Scope
button).
Single click on the node you want, click the right mouse button and select
Read Source.

12/8/95 Cadence Design Systems, Inc. 18-40


Verilog Environment 18-41

Hierarchy Browser (continued)


Use the Hierarchy Customization Options form to set display options.

Display these types


of nodes.

Dont expand nodes


Display only instance listed here.
name, only component
name, or both.
Display compact form
with no object names.

Specify number of
levels to expand.

Hierarchy Browser (continued)


Use the Hierarchy Customization Options form to:
Specify which objects to display.
Restrict expansion of objects (to hide subscopes of instances that you have restricted).
If you specify more than one object, separate names with spaces.
Specify how to display instance names. By default, HB displays instance names as:
instance_name:component_name
You can specify that HB display only the instance name, only the component name, or
both.
Display a compact view of nodes with no node names. (HB displays the node name
when you move the mouse cursor over a node.)
Change the number of levels of scope that HB displays when you expand a node. By
default, HB displays only the next level of scope.

12/8/95 Cadence Design Systems, Inc. 18-42


Verilog Environment 18-43

The Verilog Results Analyzer (VRA)


A postprocessing environment for analyzing the results of simulation jobs run in
batch mode.
The VRA has no simulation capability. Commands interact with the SHM
database.
The VRA environment consists of:
LSE, HB, and cWaves
The VRA toolbox
Buttons for invoking LSE, the HB, and cWaves
A menu for file and session handling operations, such as opening a new
database to load a different design and exiting the session

The Verilog Results Analyzer (VRA)

12/8/95 Cadence Design Systems, Inc. 18-44


Verilog Environment 18-45

The Verilog Results Analyzer (VRA) (continued)


The VRA requires the following items from the batch simulation:
An SHM file
A TMS file
An ASCII representation of the lexical and hierarchical information for a
design. Use the +vra or +venv option to create it.
The design files
Same as those used for the simulation. Required so they can be read into
the editor for source code debugging and editing. File names are contained
in the TMS file.

Invoke the VRA toolbox with:


% vra -f <shm db> -t <tms file>

The Verilog Results Analyzer (VRA) (continued)


SHM file
Set up the simulation run with a specified SHM directory covering the right number of
signals and scopes using the $shm_open and $shm_probe system tasks. Multiple SHM
databases running concurrently are not supported.
TMS file
Use +vra to create a TMS file and place it in the SHM directory structure for the
design.
The +venv option will do the same so that interactive sessions can be reanalyzed.
Both command line arguments are optional.
You can open the database after you are in the VRA by selecting the cWaves icon.
Use the -t option to specify the location of a TMS file if it is to be obtained from a
different location other than the SHM file. If a TMS file is needed and cannot be
found in the SHM database, the VRA will prompt you for the file name and location.

12/8/95 Cadence Design Systems, Inc. 18-46


Verilog Environment 18-47

The VRA (continued)

Dumping a large database of simulation results slows down the simulation and
can create very large files.
Try to limit the results being dumped to the results file.

VRA (continued)
Some ideas for limiting the amount of data in the results file:
Dump data only from the part of the design that you are interested in, plus some other
vital design nodes.
Dump only the registers and not the nets. These can often provide enough information
in a synchronous design to identify problems.
Dump areas that you have changed and treat all other areas as library components that
cannot be debugged.
Take checkpoints (saving the simulation state) throughout the simulation at regular
intervals so that a section of simulation time can be rerun with the data being dumped
later.
Take checkpoints regularly, and use the Verilog language to instruct the simulator to
return automatically to the previous checkpoint and dump data if a problem is found.
Break the simulation down into smaller units.

12/8/95 Cadence Design Systems, Inc. 18-48


Verilog Environment 18-49

Labs

Lab 11 Using the Graphical Environment


Debugging an 8-bit Register Using the Graphical Environment
Verilog-XL Twin Turbo Mode Appendix A

Appendix A

Verilog-XL Twin Turbo Mode

6/29/95 Cadence Design Systems, Inc. A-1


Appendix A Appendix A

Introduction
Performance Expectations
The information in this appendix comes from an application note written by Cadence Technical
Marketing. The results of over 35 customer design test cases show that running in the Twin Turbo mode improves
performance at various levels, depending on the design style used and Turbo options invoked. An
Purpose average performance improvement of 1.5 X over Verilog-XL Turbo can be expected at the behavioral
and RTL level, with performance gains up to 2 X.
This appendix
Introduces the new Verilog-XL Twin Turbo enhancements All performance improvements in this document are relative to Verilog-XL version 2.0.5 run in
turbo+2 and turbo+3 modes, the highest performance configuration available prior to Verilog-XL 2.1.
Describes the implementation The table below shows performance data from seven customer test cases.
Shows how to invoke the new capability
Shows how to achieve optimal performance

This document provides Verilog users with an overview of the new Verilog-XL Twin Turbo DESIGN LEVEL SOURCE STIMULUS TIME IMPROVEMENT
performance enhancements. It describes the technology implementation, how to invoke this new
Memory Controller RTL/gate 1,100 lines 57,400 cycles 196 sec 1.7 X over Turbo
capability, and how to achieve optimal performance from Verilog-XL Turbo simulations.
Graphics Processor behavioral 1,000 lines 144 cycles 12 sec 1.5 X over Turbo
The new Compiled Code implementation called Twin Turbo gives the Verilog-XL Turbo 2.1 release Microcontroller RTL 56,000 lines 633 cycles 38 sec 2.0 X over Turbo
(9404) behavioral performance enhancements over existing Verilog-XL Turbo. Twin Turbo improves ALU RTL 23,000 lines 296 cycles 28 sec 1.5 X over Turbo
the simulation performance of designs that are predominately modeled at the behavioral and RTL level
by up to 2 X. Cache Controller RTL/gate 2,000 lines 1,024 cycles 897 sec 1.6 X over Turbo
RISC CPU RTL/gate 86,900 lines 5,704 cycles 816 sec 1.4 X over Turbo
The initial release of Twin Turbo has some minor usage restrictions, which are discussed in this LFSR RTL/gate 3,171 lines 20,000 cycles 113 sec 1.7 X over Turbo
document. Subsequent Verilog-XL Turbo releases will include a robust Twin Turbo implementation
without these restrictions.

6/29/95 Cadence Design Systems, Inc. A-1 A-2 Cadence Design Systems, Inc. 6/29/95
Appendix A Appendix A

Figure 1 illustrates a simple Verilog procedural assignment, its corresponding interpreted data
Compiled Code Simulation structure, pseudocode generated in Turbo mode, and machine code generated in Twin Turbo mode.

The terms compiled code simulation and interpreted simulation refer to the way in which a simulator
operates on a designs source description. An interpreted simulator reads the source code of a LOAD A
=
design/stimulus description and from it builds an internal representation or data structure of primitive
LOAD B
operations. During simulation, these operations representing the designs behavior are interpreted, or initial Z - Z = function(A,B,C)
processed, by the simulator one at a time. A Compiled Code (CC) simulator converts the HDL CALL multiply
Z = ((A * B) - C);
description into a computer program, then executes the program to run the simulation. Many CC * C LOAD C
simulators convert the HDL description into a standard programming language (e.g., C) and then use
CALL subtract
the machine compiler to convert the program into an executable. The Twin Turbo mode is a Direct A B
Compiled Implementation that converts the description directly into machine code, thus bypassing the STOR Z
inefficient step of running the standard compiler.
Behavioral source code Data structure Pseudocode Machine instructions
Versions of Verilog-XL prior to the 1.7 release (9303) were based solely on a interpreted simulation
implementation. At compile and link time, the design and stimulus descriptions are parsed and used to Figure 1: Examples of the various levels of code representation
build an internal representation or data structure of the designs functionality. During simulation, a
significant amount of time is spent manipulating the internal data structure tree in order to fetch and
store simulation values. In versions 1.7 and higher, the Turbo mode enhances performance by adding
highly efficient function calls or pseudocode to the data structure and optimizing memory transfers.

With the introduction of the Twin Turbo mode in the Verilog-XL Turbo 2.1 release (9404),
performance enhancements have been added by augmenting Turbos interpreted simulation method
with a new compiled code implementation. In Twin Turbo mode, machine code instructions are
generated for all behavioral source code prior to simulation. During simulation, machine instruction
sequences representing behavioral code execute at the system speed of the host computer. In Twin
Turbo mode, the compiled code executes considerably faster than the interpreted pseudocode utilized
in the Turbo mode, yet all of the flexibility and interactive debugging capabilities are maintained.

6/29/95 Cadence Design Systems, Inc. A-3 A-4 Cadence Design Systems, Inc. 6/29/95
Appendix A Appendix A

The +twin_turbo Command Line Option Twin Turbo Restrictions

The new Twin Turbo functionality operates in conjunction with each of the existing Turbo modes. The new Twin Turbo mode of the Verilog-XL Turbo 2.1 release (9404) has some usage restrictions. No
Specifying the Twin Turbo option causes the simulation to generate and utilize compiled code for Twin Turbo mode restrictions apply to any Verilog hardware description language constructs. These
processing behavioral constructs in the selected Turbo mode. Because Twin Turbo is an extension of restrictions affect simulation checkpointing, using the behavioral profiler, and single-step tracing:
the existing Verilog-XL Turbo capability, no additional licensing is required. The VXL-TURBO feature
string in the license file supports both Turbo and Twin-Turbo. - The interrupt button in the Verilog Control Window (VCW) may disappear when Twin
Turbo is invoked along with the Verilog Environment (-s +venv +twin_turbo).
Running with +noxl on the command line provides a workaround, but at the expense of
gate-level acceleration.

- The checkpointing system tasks $save and $restart and the (-r) command line option
are not supported in the current release of Verilog 2.1 in +twin_turbo mode, but will be
COMMAND LINE OPTIONS PERFORMANCE LEVEL EFFECT supported in subsequent releases.
+twin_turbo Twin Turbo extension of - $listcounts disabled
default Turbo mode - Twin Turbo optimizations
- The behavioral profiling system tasks $startprofile and $listcounts and the
+profile command line option are not supported in the current release of Verilog in
+twin_turbo with +turbo Twin Turbo extension of - Even count and profiler disabled +twin_turbo mode.
first-level Turbo mode - Default Turbo mode optimizations
- Twin Turbo optimizations - The $settrace system task (-t) command line option and the single step (,) interactive
command display incorrect results in +twin_turbo mode. These mistaken values are the
+twin_turbo with +turbo+2 Twin Turbo extension of - Assignment optimizations
second-level Turbo mode - Scalar to compact node conversion
result of an optimization that causes the right-hand side of expressions to be displayed as
- First-level Turbo mode optimizations unknown (x), even though the actual values are known. The user may add the +settrace
- Twin Turbo optimizations option on the command line to get the proper display values, but at the expense of some
optimization.
+twin_turbo with +turbo+3 Twin Turbo extension of - Delayed evaluation of complex
third-level Turbo mode continuous assignment expressions - The performance enhancements of +twin_turbo are currently disabled when Verilog-XL
(can impact event order)
- Second-level Turbo mode
is run in the Verilog Model Export mode in a VHDL/Verilog cosimulation.
optimizations
- Twin Turbo optimizations

6/29/95 Cadence Design Systems, Inc. A-5 A-6 Cadence Design Systems, Inc. 6/29/95
Appendix A Appendix A

Other Considerations Quantifying Simulation Performance

Because machine code instructions are generated in Twin Turbo mode to represent sequences of Users evaluating a simulation for performance considerations should not assume that a design is
behavioral code statements, the linking time of the simulation increases approximately 20 to 60%, with composed of an absolute percentage of behavioral and nonbehavioral (gate) level functionality. The
an additional increase in the memory size of approximately 3 to 5%. Although this process incurs critical task in accurately quantifying simulation performance is to determine exactly how much CPU
additional link time, the increase in simulation performance easily makes up for this time. time is spent in behavioral portions of the design relative to nonbehavior portions. This ratio depends
on the stimulus exercises in the design as well as on how efficiently the models implement the designs
Using the third-level Turbo mode (+turbo+3) may create event-ordering differences. Execution of behavior.
certain statements may take place in a different order compared to the regular Verilog-XL behavioral
engine. Event-reordering typically does not occur in synchronous designs, in which non-blocking As the performance improvement of the Turbo modes applies only to the behavioral code, a users
assignments have been used to allow all the inputs of the behavioral statements to be updated before expectations of overall performance must take into account the proportion of time spent processing
the corresponding outputs are evaluated. If result mismatches are observed when comparing the output nonbehavioral code. For example, if 20% of the simulation time is spent processing a users PLI
of two engines, a more severe problem may exist with the design. If event reordering presents a application and/or gate-level portions of a given design, the expected performance improvement
problem, then the design should be simulated using the second-level Turbo optimizations should be reduced by 20%.
(+turbo+2), which executes statements exactly like Verilog-XL, but at the cost of some
performance. The behavior profiler, a utility within Verilog-XL Turbo, identifies the percentage of total CPU time
spent processing behavioral constructs and modules in the source description. The profiler takes
regular samples of the simulation activity and identifies areas that are consuming large portions of
simulation time. The profiler can generate summaries of the simulations performance characteristics
or identify the lines of code that require significant processing. With this information, users can set
proper performance expectations and perhaps rewrite specific sections of code to increased simulation
performance.

To run the profiler in Turbo mode, Verilog-XL must be invoked with the +verbose_profile and
+listcounts options. The profiler is activated by issuing the $startprofile system task from
within a procedural block at time 0 or on the interactive command line. The two system tasks
$reportprofile and $listcounts display in the logfile the activity within the simulation and
how many times particular lines of code were executed. To obtain the most complete profile
information, the $reportprofile and $listcounts tasks should be issued at the end of the
simulation just before the $finish; however, they can be issued interactively at any point in the
simulation.

6/29/95 Cadence Design Systems, Inc. A-7 A-8 Cadence Design Systems, Inc. 6/29/95
Appendix A Appendix A

In Figure 3 a report produced by the $reportprofile task details the percentage of overall CPU
time spent simulating each type of behavioral construct. In this example, the simulator spent 63.6% of
its time in nonblocking procedural assignments and 11.6% in continuous assignments. The OTHERS
Profile ranking by statement: category represents the combination of XL, XL -> NONXL, and SCHEDULING activity and should
be taken into account when calculating overall Turbo performance improvements. It is also useful to
Self% Cum.% Samples Statement know how much simulation time spent initiating calls to system tasks and functions
----- ----- ------- ----------------------- (enable_task_stat) does not benefit from Turbo.
3.3% 3.3% 5668 SCHEDULING
2.3% 5.6% 4038 XL
1.3% 6.9% 2186 test.v, L36, test
0.9% 7.8% 1638 XL -> NON-XL
0.7% 8.5% 1139 cpu.v, L83, test.u1 Profile by statement type:
0.6% 9.1% 1034 cpu.v, L86, test.u1
0.6% 9.6% 1011 alu.v, L17, test.u8 Self% Cum.% Samples Statement type
0.6% 10.2% 982 mem.v, L17, test.u27 ----- ----- ------- --------------
... Report halted at 8 lines 63.6% 63.6% 110344 rtl_delay_stat
11.6% 75.2% 20112 cont_assign
6.5% 81.8% 11344 OTHERS
Figure 2: Profile of statements by ranking 3.9% 85.6% 6734 modport
2.9% 88.6% 5111 event_stat
2.7% 91.3% 4681 norm_node
2.0% 93.3% 3548 if_stat
Figure 2 shows a report produced by the $reportprofile task that lists the percentage of overall 1.7% 95.0% 2924 assign_stat
CPU time spent simulating individual statements in the design. Here, the XL statement indicates the 1.6% 96.6% 2718 seq_block
percentage of time that the XL gate engine is running. The XL -> NONXL is the proportion of time the 1.3% 97.9% 2202 enable_task_stat
simulator is transferring data between the XL and Turbo engines. As the Turbo engine does not 0.8% 98.7% 1387 if_else_stat
improve gate-level simulation, these numbers may be used to calculate the effect of the gate- level 0.6% 99.2% 988 delay_stat
portion of the design compared to the behavioral portion. For example, if one quarter of the design is 0.6% 99.8% 960 expand_decl
simulated using the XL engine (percentage of XL activity = 25%) and then Turbo is invoked, the 0.1% 99.9% 214 forever_stat
resulting performance improvement that Turbo provides only applies to three-quarters of the design 0.1% 100.0% 155 null_stat
because the gate-level part is already accelerated by XL.

Figure 3: Profile of statements by type

Any design should be checked for statements that are taking up a large proportion of the simulation
activity. These proportions may be examined using the $listcounts task, which reports on the
amount of activity within a statement or hierarchical boundary. The design may be examined on a
module-by-module basis through the hierarchy, and any statements with a high sample number should
be checked for efficiency. If these statements are a central part of the designs functionality, they may
be being used efficiently by the simulation; however, often a redundant item of code takes up an
excessive amount of simulation.

6/29/95 Cadence Design Systems, Inc. A-9 A-10 Cadence Design Systems, Inc. 6/29/95
Appendix A Appendix A

3. Add both +verbose_profile and +listcounts on the


command line to get the behavioral code execution counts report.
// test.v
100: 27 begin
100: 28 sc = 1;
100: 29 repeat(pipeline) // profile.v
2400: 30 begin
2400: 31 elem = 1; module profile;
2400: 32 repeat(sc_length) parameter
84000: 33 begin finish_time = 1000;
84000: 34 res = vect[elem]; initial
84000: 35 vect[elem] = res[sc]; begin
84000: 36 elem = elem + 1; if($test$plusargs(verbose_profile))
37 end begin
2400: 38 sc = sc + 1; $startprofile;
39 end #finish_time
40 end $reportprofile(50);
if($test$plusargs(listcounts))
$listcounts(target_instance);
Figure 4: Listing of code execution counts $finish(2);
end
else
#finish_time
Figure 4 shows an example listing produced by the $listcounts task. The decompiled design is
$finish(2);
displayed with the number of times each line of code was sampled while executing. This information is
end
extremely useful for tracing potential inefficiencies down to the individual lines of code. Using the
$listcounts task to generate code execution counts incurs some overhead, but this task can be left endmodule
in the source code and disabled by not including the +listcounts option on the command line.
Figure 5: Example profile module for design profiling use
The behavioral profiler is valuable for accurately quantifying simulation performance by displaying
exactly how much simulation time is spent in various portions of the design. The profiler is also a quick
means of highlighting sections of code that could be improved to increase simulation performance. The
Verilog module illustrated in figure 5 can be compiled with a set of design files to facilitate profile
report generation through command line options.

Usage:

1. Set the parameter finish_time equal to the desired simulation


finish time.

2. Add +verbose_profile on the command line to generate


behavioral statement profile reports.

6/29/95 Cadence Design Systems, Inc. A-11 A-12 Cadence Design Systems, Inc. 6/29/95
Appendix A Appendix A

For example, in synchronous designs many procedural blocks that are triggered only by the positive
Achieving Optimal Performance edge of the system clock can be consolidated for more efficient processing.

Several optimizations can be implemented to improve the performance of the design. In general, the always@(posedge clk) always@(posedge clk)
focus should be on keeping the number of scheduled events scheduled as low as possible. The methods Y = C + D; begin
Y = C + D;
of optimization are: always@(posedge clk) Z = A * B;
Z = A * B; X = E + F;
Use of file I/O and debug statements end
always@(posedge clk)
X = E * F;
Although the performance of file I/O system tasks such as $monitor and $display has been
improved, it is generally best to minimize the use of debug statements that write to file or display
information. Because of the relatively slow access to the computers devices, calls to file I/O system
tasks can significantly affect simulation performance.

Event control
Flow control
Inefficient use of event controls may cause the simulator to execute a particular statement or group
Better performance can be achieved by reducing the simulators workload. For example, combining of statements unnecessarily. Careful attention to specifying the conditions when procedural blocks
several if statements into a single case statement causes the simulator to evaluate the case execute ensures the desired functionality in the fewest possible scheduled events. Of course, if a
statement once to understand the branching condition. If a sequence of if statements is used synthesis tool is used, the HDL rules must not be violated.
instead, the simulator has to evaluate the conditions repeatedly.

always@(d)
always(clk) always@(clk) always@(posedge clk) @(posedge clk)
begin case(status) q = d; q = d;
if (status == 2b00) 2b00: out = Y;
out = Y; 2b01: out = A;
2b10: out = 1bz;
if (status == 2b01) 2b11: out = B;
out = A; endcase

if (status == 2b10)
out = 1bz;

if (status == 2b11)
out = B;
end

Procedural block grouping

Where possible, consolidate multiple procedural blocks that are triggered by the same conditions.

6/29/95 Cadence Design Systems, Inc. A-13 A-14 Cadence Design Systems, Inc. 6/29/95
Appendix A Appendix A

Use of nonbehavioral constructs


Summary
Because nonbehavioral constructs are not accelerated by Turbo and Twin Turbo modes, they detract
from the simulations overall performance gain in these modes. Two common sets of constructs that
detract from Turbo and Twin Turbo performance are instances of gate and UDP primitives and This document provides a basic understanding of the operation of the new Twin Turbo Compiled Code
system tasks and functions, including PLI applications. If speed does not improve as expected, the behavioral engine within the Verilog-XL Turbo simulator. It gives guidelines for the kinds of
simulation must be profiled using the behavioral profiler (described in the previous section) to performance improvement that can be expected and describes how to achieve those performance goals
determine where the simulator is spending its time. and analyze the design in terms of performance. Finally, this document introduces ways to use the
engine and discusses the relative trade-offs when applying this technology to a design. Armed with this
information, Verilog-XL users can successfully use the new engine to achieve significant performance
improvements on many of their design problems.

6/29/95 Cadence Design Systems, Inc. A-15 A-16 Cadence Design Systems, Inc. 6/29/95
Appendix B

Statistical Modeling
Statistical Modeling B-1

Statistical Modeling
Objectives
Learn about statistical modeling.

Terms and Definitions

6/9/95 Cadence Design Systems, Inc. B-2


Statistical Modeling B-3

What Is Statistical Modeling?

Statistical modeling is the highest level of abstraction that you can use to
analyze a design.
The goal of statistical modeling is to improve performance.
You can detect deadlocks and buffer overflows.

What Is Statistical Modeling?

6/9/95 Cadence Design Systems, Inc. B-4


Statistical Modeling B-5

Top-Down Modeling Levels


always #($dist_poisson(seed,32))
begin
if $q_full(qid)
Statistical
$q_remove(qid,job,job_id,status);
else
Decreasing -> fill_queue;
Levels of end
Abstraction
always @(fetch_done)
begin
Behavioral casez (IR[7:6]) behavioral
2b00: LDA(acc,IR[5:0]); (non-structural)
2b01: STR(acc,IR[5:0]);
2b10: JMP(IR[5:0]);
2b11: ; // NOP
endcase
end

assign rt1 = (i1&buserr)|zero;


RTL assign sub = rt1^|op;
assign out1 = i1&i2|op;

Gate/Switch
gate/switch
(structural)

Top-Down Modeling Levels


Statistical allows you to investigate the performance ramifications of statistical
decisions.
You can detect problems like deadlocks and poor performance before the real
implementation of the design.
Behavioral is used to describe high-level models.
You describe behavioral models in Verilog by specifying a set of concurrently active
procedural blocks.
RTL (Register Transfer Logic).
Gate/Switch describes the functionality of a device in term of gates.
Structural modeling is equivalent to a gate-level schematic.

6/9/95 Cadence Design Systems, Inc. B-6


Statistical Modeling B-7

Queues and Random Functions

In order to support statistical modeling, Verilog provides:


A set of predefined queueing models, to simulate the operation of the
system under varying loads.
FIFO and LIFO queues are available.
A set of built-in tasks and functions which manage queues and provide
random numbers with specific distributions.
These tasks and functions can be used to reproduce real-world stimuli.

Queues and Random Functions

6/9/95 Cadence Design Systems, Inc. B-8


Statistical Modeling B-9

A Simple Example

DISK
COMPUTER

The computer The disk reads


writes messages messages from
in to the buffer the buffer

BUFFER

A Simple Example

A simple example consist of the following three components.

Module Computer The Computer writes messages into the


buffer with a frequency that
approximately follows a Poisson
Distribution.
Module Disk The Disk reads messages from the buffer
with a frequency that approximately
follows a Uniform Distribution.
Module Buffer The Buffer defines a queue.

The problem is to appropriately size the buffer to avoid overflows.

6/9/95 Cadence Design Systems, Inc. B-10


Statistical Modeling B-11

Probabilistic Distribution Functions

p(e)
Poisson Distribution

pdf

e
mean

p(e)
Uniform Distribution
pdf

e
start end

Probabilistic Distribution Functions


System analysis using queueing models requires that job-arrival rates and processing
times be represented by random functions which approximate the real world. Experience
has shown that certain probabilistic distributions occur often in real systems.
Verilog-XL provides random number generators which return integer values distributed
according to standard probabilistic functions.
The two probabilistic distributions used in our example are the following:
$dist_poisson(<seed>, <mean>)
$dist_uniform(<seed>, <start>, <end>)
All parameters are integer values.
In the $dist_uniform function, the start and end parameters are integer inputs used with
the $dist_uniform function which bound the values returned. The start value should be
smaller than the end value.
The mean parameter is an integer input which forces the average value returned by the
function to approach the value specified. This average will only be achieved after many
calls to the function.

6/9/95 Cadence Design Systems, Inc. B-12


Statistical Modeling B-13

Initializing a Queue
module buffer;

/* A number of 20 overflows,
BUFFER
over a period of 40.000 time unit,
is acceptable */

integer MAX_LENGTH;
integer status;
reg queue_value;

initial
begin
MAX_LENGTH = 10;
// Initialize the queue and check for errors
$q_initialize (QUEUE_ID, 1, MAX_LENGTH, status); $q_initialize creates
a new queue.
if(status !==0)
begin
// $display(status = %d, status);
$display(ERROR INITIALIZING THE QUEUE IN THE BUFFER);
$finish;
end
end
endmodule

Initializing a Queue
You can create a new queue using the $q_initialize system task.
$q_initialize (<q_id>, <q_type>, <max_length>, <status>)
The q_id parameter is an integer input which must uniquely identify the new queue.
The q_type parameter is an integer input. The value of the q_type parameter specifies
the following:
1. that the queue should be first-in/first-out
2. that the queue should be last-in/first-out
The max_length parameter is an integer input which specifies the maximum number of
entries that will be allowed on the queue.
The success or failure of the creation is returned as an integer in status.
status What it Means
Parameter Values

0 OK
1 queue full, cannot add
2 undefined q_id
3 queue empty, cannot remove
4 unsupported queue type, cannot create queue
5 specified length <= 0, cannot create queue
6 duplicate q_id, cannot create queue
7 not enough memory, cannot create queue

6/9/95 Cadence Design Systems, Inc. B-14


Statistical Modeling B-15

Placing a Job in a Queue


module computer;
integer SEED, MEAN; COMPUTER
integer job_id;
integer delay;
integer status;
integer NUMBER_OF_OVERFLOWS;
...
always
/* Print Warning Messages if the queue is full */
begin BUFFER
delay= $dist_poisson(SEED, MEAN);
#delay;
$q_full checks
if($q_full(QUEUE_ID, status))
room in queue.
begin
$display(WARNING - OVERFLOW at time%d for job_id#%d,
$time,job_id);
NUMBER_OF_OVERFLOWS = NUMBER_OF_OVERFLOWS + 1;
end
else
begin
$q_add places a
$q_add(QUEUE_ID, job_id, 0,status);
job in the queue.
job_id = job_id + 1;
end
end
endmodule

Placing a Job in a Queue


You can place a job in the queue using the $q_add system task.
$q_add (<q_id>, <job_id>, <inform_id>, <status>).
The q_id parameter is an integer input that indicates which queue to add to.
The job_id parameter is an integer input that identifies the job.
The inform_id parameter is an integer input that the queue manager will store. Its
meaning is user-defined. An example would be job execution time in a CPU model.
The status parameter reports on the success of the operation.
The $q_full system function checks whether there is room for another job on a queue. It
returns 0 when the queue is not full, and 1 when the queue is full.

6/9/95 Cadence Design Systems, Inc. B-16


Statistical Modeling B-17

Processing a Job from the Queue

module disk;
integer SEED, START, END;
integer job_id;
integer delay; DISK
integer status;
integer inform_id;

always
begin BUFFER
delay = $dist_uniform(SEED,START, END);
#delay;
$q_remove(QUEUE_ID, job_id, inform_id, status);

end $q_remove processes


a job in the queue.
endmodule

Processing a Job from the Queue


You can process a job in the queue using the $q_remove system task.
$q_remove (<q_id>, <job_id>, <inform_id>, <status>).
The q_id parameter is an integer input which indicates which queue to remove from.
The job_id parameter is an integer output which identifies the job being removed.
The inform_id parameter is an integer output which the queue manager stored during
$q_add. Its meaning is user-defined.
The status parameter reports on the success of the operation.

6/9/95 Cadence Design Systems, Inc. B-18


Statistical Modeling B-19

Statistical Information About the Queue


define QUEUE_ID 1
module system;
integer status;
integer queue_length, max_queue_length, lwt, awt;
...
// Display Statistic Values
always
begin
#1000
$display(\n\n********************************); $q_exam reports
$display(* TIME=%d,$stime); statistical information
$q_exam(QUEUE_ID, 1, queue_length, status); about a queue.
$display(* CURRENT QUEUE LENGTH= %d, queue_length);

...

$q_exam(QUEUE_ID, 6, awt, status);


$display(* AVERAGE WAIT TIME=%d, awt);
$display(* NUMBER OF OVERFLOWS=%d, I2.NUMBER_OF_OVERFLOWS);
$display(****************************************************);
end

Statistical Information about the Queue


You can get statistical information about a queue using the $q_exam system task.
$q_exam (<q_id>, <q_stat_code>, <q_stat_value>, <status>).
The q_id parameter is an integer input which indicates the current queue being analyzed.
The q_stat_value is a return value which depends upon the information requested in
q_stat_code.

Value Requested Information Received Back from


in q_stat_code q_stat_value

1 current queue length


2 mean inter-arrival time
3 maximum queue length
4 shortest wait time ever
5 longest wait time for jobs still in the queue
6 average wait time in the queue

When the current value associated with a bar exceeds the predefined height, the bar
changes color to indicate this off-the-scale condition.

6/9/95 Cadence Design Systems, Inc. B-20


Statistical Modeling B-21

Labs

Lab A Statistical Modeling


A Simple Example of Statistical Modeling.
Modeling an ATM System (Optional).

6/9/95 Cadence Design Systems, Inc. B-22


Statistical Modeling B-23
Appendix C

Switch-Level Modeling
Switch-Level Modeling C-1

Switch-Level Modeling

Objectives
Introduce switch-level modeling.
Introduce the Switch-XL algorithm.
Introduce the Switch-RC algorithm.
Learn how to choose an algorithm.

Terms and Definitions

XL Algorithm The XL Algorithm accelerates the simulation of gate-level and


switch-level descriptions.
non-XL Algorithm The non-XL Algorithm (or standard algorithm) does not provide
acceleration.
Switch-XL The switch-XL algorithm accelerates the simulation of
bidirectional switches, delays are based on strength values.
Switch-RC The switch-RC algorithm derives transistor delays from
length/width sizes and an RC model.
It uses a characterization file or technology file.

6/9/95 Cadence Design Systems, Inc. C-2


Switch-Level Modeling C-3

Advantages of Switch-Level Modeling

For cmos and nmos circuits, modeling at the switch level better represents
the hardware implementation of a design than modeling at the gate level.
Verilog-XL allows you to simulate switch-level networks with either a default
algorithm or the Switch-XL or the Switch-RC algorithm.

Advantages of Switch-Level Modeling

6/9/95 Cadence Design Systems, Inc. C-4


Switch-Level Modeling C-5

Verilog Primitive Switches

Verilog provides a set of primitives that model unidirectional and


bidirectional switches.
The following are bidirectional switches:
tran rtran tranif1
tranif0 rtranif1 rtranif0

The following are unidirectional switches. The Switch-RC algorithm must


model them as bidirectionals.
nmos pmos cmos rnmos
rpmos rcmos pullup pulldown

Verilog Primitive Switches

6/9/95 Cadence Design Systems, Inc. C-6


Switch-Level Modeling C-7

Switch-Level Networks

Switch-level networks are composed of bidirectional switches,


unidirectional switches or both.

Different regions of
channel-connected switches

The default algorithm, the Switch-XL and the Switch-RC simulate regions of
channel-connected switches.

Switch-Level Networks
Switch-level networks are composed of bidirectional switches, unidirectional switches
or both, which are those complying with either of the following criteria:
a single switch and the nets that connect to its source and drain terminals.
a group of switches connected together through their source and drain terminals, and
nets connected to the switches source and drain terminals.
The default algorithm, the Switch-XL and the Switch-RC simulate regions of
channel-connected switches.

6/9/95 Cadence Design Systems, Inc. C-8


Switch-Level Modeling C-9

Switch Instantiation

Drain Source Gate


ctl

in out nmos (out, in, ctl);


ctl

in out pmos (out, in, ctl);

pctl

in out cmos (out, in, nctl, pctl);

nctl

data1 data2 tran (data1, data2);

Switch Instantiation

6/9/95 Cadence Design Systems, Inc. C-10


Switch-Level Modeling C-11

Delay Timing Models for Switches


Verilog-XL uses the following two-delay timing models for switches:
Turn-on/turn-off for bidirectional switches.

tranif1 #(5,6) tr1_1(d,s,g)

turn-on delay turn-off delay

Channel delay plus turn-off delay for unidirectional switches.


nmos #(5,6,7) nm_1(d,s,g)

rise delay fall delay turn-off delay


channel delay

Note:Verilog-XL employs no delays for the pullup and pulldown unidirectional switches.
You cannot specify delays for these switches.

Delay Timing Models for Switches


Verilog-XL uses the following two-delay timing models for switches:
Turn-on/turn-off
Channel delay
The channel-delay timing model
Verilog-XL uses the channel-delay timing model for unidirectional switches that are
not accelerated by the Switch-XL algorithm.
A channel delay specifies an interval of simulation time for a value change on the
source terminal to propagate to the drain terminal.
A transition on the gate terminal enables or disables the propagation of a value from
the source terminal to the drain terminal.
The turn-on/turn-off delay timing model
A turn-on/turn-off delay specifies an interval of simulation time between a transition
on the gate terminal and the enabling or disabling of the propagation of values
between the source and drain terminal.
In switches that use only the turn-on/turn-off delay timing model, no simulation time
elapses in the propagation of values.

6/9/95 Cadence Design Systems, Inc. C-12


Switch-Level Modeling C-13

Strength Reduction

Unidirectional Switches
input strength Reduced Input Strength Reduced Strength
Strength
ctl
supply drive pull drive
strong drive pull drive
in out pull drive weak drive
rpmos p1(out, in, ctl);
large capacitor medium capacitor
weak drive medium capacitor
medium capacitor small capacitor
Bidirectional Switches
small capacitor small capacitor
bd1 high impedance high impedance

rtran t1(bd1, bd2);


Strength Reduction Table
bd2
for Resistive Models
Pullup and Pulldown Bodies

pullup(a)
pulldown(b)
and (c, a, b);

Strength Reduction
The nmos, pmos and cmos devices pass trough the strength from the data input to the
output, except that a supply strength is reduced to a strong strength.
The rnmos, rpmos, rcmos, rtran, rtranif1, rtranif0 devices reduce the strength of signals
that pass through them according to the table.

6/9/95 Cadence Design Systems, Inc. C-14


Switch-Level Modeling C-15

The Switch-XL Algorithm


Verilog-XL allows you to execute a simulation under the control of the Switch-XL
algorithm. Running this kind of simulation provides you with the following
capabilities:
High-speed simulation of bidirectional switches.
Enhanced strength model:
Specify up to 250 drive strengths to switches.
Specify charge strengths to nets.

S1
2

Strength of Transistors

S2 S3
1 1

The Switch-XL Algorithm

Verilog-XL allows you to execute a simulation under the control of the switch-XL algorithm.
Doing so provides you with the following capabilities:
High-speed simulation of bidirectional switches.
Enhanced strength model:
Specify up to 250 drive strengths to switches
Specify charge strengths to nets
The XL algorithm accelerates the simulation of gates and unidirectional switches. The
switch-XL algorithm accelerates the simulation of bidirectional switches. With the switch-XL
algorithm, you can model bidirectional switches without paying a high performance cost.

6/9/95 Cadence Design Systems, Inc. C-16


Switch-Level Modeling C-17

Timing Model Conversion of Unidirectional Switches

nmos tranif1

not converted to turn on/ turn off


nmos #(5,6,7) nm_1(d,s,g)

nmos
turn-on delay turn-off delay
ignore
nmos tranif1 nmos nmos

converted to turn on/turn off

Timing Model Conversion of Unidirectional Switches


If the switch-XL finds a bidirectional switch in a channel-connected switch network, it
converts all the unidirectional switches in that channel-connected switch network from
the combination of channel delay and turn-on/turn-off delay timing models to
exclusively turn-on/turn-off delay timing models so that all switches in the channel
connected have the same delay timing model. These unidirectional switches remain
unidirectional, but their delay timing model changes.
If you specify a rise, fall, and turn-off delay for a MOS switch, the switch-XL algorithm
ignores the larger of the rise and fall delays (channel delays) and uses the smaller delay
as the turn-on delay. The turn-off delay is still used as the turn-off delay.
If you specify only a rise and fall delay for a MOS switch when the switch-XL algorithm
converts its delay timing model to exclusively the turn-on/turn-off delay model, then the
rise and fall delays become the turn-on and turn-off delays.

6/9/95 Cadence Design Systems, Inc. C-18


Switch-Level Modeling C-19

The Switch-XL Strength Model

Specifying charge strengths when declaring triregs net.

trireg strength(25) a; trireg a has the largest capacitance


trireg strength(10) b; relative to b, c and d. The expression,
followed the strength keyword, must
trireg strength(5) c; evaluates to a number from 0 to 250
trireg strength(1) d; for any triregs declaration

Specifying drive strengths when declaring switches.


tranif1 strength(3) t1a(s0,d0,g0);
tranif0 strength(2) t0a(s1,d1,g1);
rtran strength(1) rt1(s2,d2);

tranif1 t1 has the largest conductance relative to tranif0 t0


and rtran rt1. The expression, followed the strength keyword,
must evaluate to a number from 1 to 250 for any switches
declaration

The Switch-XL Strength Model


The switch-XL algorithm strength model allows you to specify a wider range of charge
strengths (capacitance) for triregs and drive strengths (conductance) for switches.
You can specify charge strengths and drive strengths with the strength keyword
followed by an expression in parentheses.
The expression specifies a relative capacitance of a trireg or a relative conductance of
transistor compared to other triregs or transistors in a channel-connected network.
The Verilog-XL algorithm must be able to evaluate the expression to a constant value.
If the expression evaluates to a real number, the Verilog-XL algorithm truncates it to the
nearest integer.

6/9/95 Cadence Design Systems, Inc. C-20


Switch-Level Modeling C-21

How to Invoke the Switch-XL Algorithm

You can use two methods to invoke the switch-XL algorithm:


Enter the +switchxl plus option on the command line.
Use the switch-XL strength model in your source description.
Example:
verilog file1.v file2.v +switchxl

How to Invoke the Switch-XL Algorithm

You can use two methods to invoke the switch-XL algorithm:


Enter the +switchxl plus option on the command line.
Use the switch-XL strength model in your source description.
The following examples shows how to enter the +switchxl plus option:
Example:
verilog file1.v file2.v +switchxl
In this example, switch-XL enables the bidirectional switches in file1.v and file2.v to simulate
at high speed.

6/9/95 Cadence Design Systems, Inc. C-22


Switch-Level Modeling C-23

The Switch-RC Algorithm

Verilog-XL allows you to execute a simulation under the control of the Switch-RC
algorithm.
The Switch-RC algorithm incorporates detailed timing based on the sizes of
transistors and resistance and capacitance of nets.
It provides more accurate logic and timing analysis of large circuits than the
default or Switch-XL algorithm.

The Switch-RC Algorithm


The Switch-RC algorithm incorporates detailed timing based on the sizes of transistors
and resistance and capacitance of nets.
It provides more accurate logic and timing analysis of large circuits than the default or
Switch-XL algorithm without the major degradation in speed associated with detailed
circuit simulation tools.
The Switch-RC algorithm does not support unidirectional signal flow. Unidirectional
switches you specify for Switch-RC simulation are converted into bidirectionals.

6/9/95 Cadence Design Systems, Inc. C-24


Switch-Level Modeling C-25

The Switch-RC Algorithm (continued)


The Switch-RC algorithm incorporates detailed timing based on the sizes of
transistors in the schematic.

R1
W/L
S1

Size of Transistor

R2 R3

W/L W/L
S2 S3

RC Model

Takes W/L of switches and creates an RC model


with technology specification

The Switch-RC Algorithm (continued)

The Switch-RC algorithm incorporates detailed timing based on the sizes of transistors in the
schematic.
The Switch-RC algorithm has its own model for switches and nets that requires additional
information. You supply information for this model in several ways:
Compiler directives define different manufacturing technologies that include mappings
between the real resistances and capacitances in the Switch-RC and the Verilog-XL
standard-strength model.
Switch declarations have lengths and widths that map to resistances defined by the
manufacturing technology.
Net declarations include capacitances and high and low voltage thresholds.
Compiler directives associate each switch or net with a manufacturing technology.

6/9/95 Cadence Design Systems, Inc. C-26


Switch-Level Modeling C-27

Timing Specification

Use RC networks to determine final state and final delay.

VCC

R1

OUT
R2//R3 C

R2//R3

Delay

Final State

Timing Specification
Use RC networks to determine final state and final delay.
Using different approximation the Switch-RC algorithm estimates the delay associated
to a network.
The delay is a function of R and C.

6/9/95 Cadence Design Systems, Inc. C-28


Switch-Level Modeling C-29

Model Pull-Up/Pull-Down Ratio

Design mistakes in
pullup/pulldown ratio will
w/l be detected by the Switch-RC
algorithm

w/l w/l w/l

Model Pull-Up/Pull-Down Ratio


Use the Switch-RC algorithm to model pull-up/pull-down ratio based on switch width
and length.
Design mistakes in pullup/pulldown ratio are detected by the Switch-RC algorithm.

6/9/95 Cadence Design Systems, Inc. C-30


Switch-Level Modeling C-31

Technical Advantages of Timing Accuracy

State-dependent delay
Delay due to the side-path capacitor
Slope-dependent delay

Technical Advantages of Timing Accuracy

6/9/95 Cadence Design Systems, Inc. C-32


Switch-Level Modeling C-33

State Dependent Delay

case A case B

R
1 -> 0 R 1 -> 0 ----
C 2 C

R
= RC = ---- C
2

State Dependent Delay


State Dependent Delay means that the delay through a net is calculated dynamically
during simulation.
case A represent a particular state, during simulation, in which only one transistor,
driving the output, is on; the shaded-drawn transistors are off. In this state of the circuit
the delay is T=1/RC.
case B represent another state in which two transistor, driving the output, are on. The
delay is this case is T=2/RC.

6/9/95 Cadence Design Systems, Inc. C-34


Switch-Level Modeling C-35

Delay Due to Side Path Capacitance

0 -> 1 @ 2.0ns 0 -> 1 @ 2.0ns


1 -> 0 @ 2.43ns 1 -> 0 @ 2.038ns

Delay is Larger When Capacitance Is on Side Path

Delay Due to Side Path Capacitance


The delay due to side path capacitance takes into account delays due to side capacitance.
The delay is larger when capacitance is on side path.

6/9/95 Cadence Design Systems, Inc. C-36


Switch-Level Modeling C-37

Slope Dependent Delay

0->1
out

Delay is Calculated as a Function of Input Slope

Slope Dependent Delay

The delay calculation takes in consideration the effect of an input slope.

6/9/95 Cadence Design Systems, Inc. C-38


Switch-Level Modeling C-39

Invoking the Switch-RC Algorithm

You can use either of two methods to invoke the switch-RC algorithm:
Enter the +switch_res plus option on the command line.
Use the switchrc compiler directive.
Example:
verilog file1.v file2.v +switch_res

Invoking the Switch-RC Algorithm

You can use two methods to invoke the switch-RC algorithm:


Enter the +switch_res plus option on the command line.
Use the switchrc compiler directive.
Example:
verilog file1.v file2.v +switch_res
The example shows how to invoke the Switch-RC algorithm globally.

6/9/95 Cadence Design Systems, Inc. C-40


Switch-Level Modeling C-41

The Algorithms Major Features


Default Switch-XL Switch-RC
Algorithm Algorithm Algorithm
Strength Model Standard Standard-strength Uses resistance and
Strength with exceptions. capacitance instead
Also 256 strength of strength
model.
Switch Strength None - Maintain Integer strength Calculates resistance
or drop by one based on width and
length
Net Strength None, small, None, small, Uses continuous
medium, and medium and large. valued capacitance
large Also integer
strength.
Delay User-specified User-specified Based on resistance,
Calculation capacitance, and
input slope values
Spikes Not handled Not handled Suppresses small
spikes, propagates
large spikes

The Algorithms Major Features

6/9/95 Cadence Design Systems, Inc. C-42


Switch-Level Modeling C-43

Choosing an Algorithm
When do I use the Switch-XL algorithm?
Maximum speed is required.
Simulation focus on functionality checking instead of
timing accuracy.
Speed
Pumping test vectors for regression test.

When do I use the Switch-RC algorithm?


Give up speed for timing accuracy.
Check capacitive loading effect.

Accuracy
Check timing and some functionality using a
reasonable number of vectors.

Choosing an Algorithm
If you are interested in functional simulation and specifying discrete delays, your choice
is between the default and Switch-XL algorithms. If the standard-strength model cannot
simulate the circuit, Switch-XL remains as the only option with its integer-strength
model.
The difficult decision is whether to use the default algorithm or the Switch-XL
algorithm when the standard-strength model can simulate the circuit. The choice is
dependent upon the topology of the circuit. If the circuit is a sea of gates implemented
with bidirectionals, Switch-XL outperforms the default algorithm by a factor of five to
fifteen.
If you want a simulation with actual widths, lengths, capacitances, and detailed timing
estimation, you must use Switch-RC. In this case, you want to model some behavior that
is outside the scope of the default and Switch-XL algorithms, such as spike analysis, or
parallel and serial combination of resistors.

6/9/95 Cadence Design Systems, Inc. C-44


Switch-Level Modeling C-45

Labs

Lab B Switch-Level Modeling


Using the Switch-RC Algorithm

6/9/95 Cadence Design Systems, Inc. C-46


Switch-Level Modeling C-47
mux.v Appendix D Lab 1

Appendix D
Lab 1

Solution Files for Labs mux.v


module MUX2_1 (out,a,b,sel);
// Port declarations
output out;
input a,b,sel;

// The netlist
not (sel_, sel);
and (a1, a, sel_);
and (b1, b, sel);
or (out, a1, b1);

endmodule

6/29/95 Cadence Design Systems, Inc. D-1


Appendix D Lab 1 testfixture.v clock.v Appendix D Lab 2

testfixture.v Lab 2
module testfixture;
clock.v
reg a, b, sel; module clock(clk);
output clk;
//MUX instance reg start;
MUX2_1 mux (out, a, b, sel);
// Apply Stimulus nand #10 (clk, clk, start); //clock oscilator

initial //start the clock oscillator


initial
begin
begin start = 0;
a = 0; b = 1; sel = 0; #10 start = 1;
#5 b = 0; end
#5 b = 1; sel = 1;
#5 a = 1;
endmodule
#5 $finish;
end

// Display Results

initial
$monitor($time, " a = %b b = %b sel = %b out = %b", a,b,sel,out);

/*
// This will be used for cWaves during lab 1-3

initial

begin
$shm_open("file.shm");
$shm_probe("A");
#0 $stop;
end

*/

endmodule

D-2 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-3
Appendix D Lab 2 dff.v register.v Appendix D Lab 2

dff.v register.v
timescale 1 ns/100 ps /*************************************************************************
module dff(q, qb, clk, d, rst); * 8-bit register with hierarchy, Verilog Training Course
output q, qb; *************************************************************************/
input clk, d, rst;
timescale 1 ns / 100 ps
module register(r, clk, data, ena, rst);
nand n1 (cf, dl, cbf);
output [7:0] r;
nand n2 (cbf, clk, cf, rst);
input [7:0] data;
nand n3 (dl, d, dbl, rst);
input clk, ena, rst;
nand n4 (dbl, dl, clk, cbf);
nand n5 (q, cbf, qb);
wire [7:0] data, r;
nand n6 (qb, dbl, q, rst);
and a1(load, clk, ena);
endmodule
dff d0 (r[0], , load, data[0], rst),
d1 (r[1], , load, data[1], rst),
d2 (r[2], , load, data[2], rst),
d3 (r[3], , load, data[3], rst),
d4 (r[4], , load, data[4], rst),
d5 (r[5], , load, data[5], rst),
d6 (r[6], , load, data[6], rst),
d7 (r[7], , load, data[7], rst);

endmodule

D-4 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-5
Appendix D Lab 2 register_test.v dff.v Appendix D Lab 3

register_test.v Lab 3
/*************************************************************************
* Stimulus for testing the 8-bit Register - Verilog Training Course dff.v
timescale 1 ns/100 ps
*************************************************************************/ module dff(q, qb, clk, d, rst);
timescale 1 ns / 100 ps output q, qb;
module test; input clk, d, rst;
wire [7:0] reg_out; //declare vector for register output
reg [7:0] data; nand n1 (cf, dl, cbf);
reg ena, rst; nand n2 (cbf, clk, cf, rst);
nand n3 (dl, d, dbl, rst);
nand n4 (dbl, dl, clk, cbf);
register r1(reg_out, clk, data, ena, rst); nand n5 (q, cbf, qb);
nand n6 (qb, dbl, q, rst);
clock c1 (clk); //clock oscilator
specify

$setuphold(posedge clk &&& rst, d &&& rst, 3:5:6, 2:3:6);


initial //apply stimulus to register inputs
begin (rst *> q, qb) = 3;
rst = 0; //should reset register to hex 00 (clk *> q) = (2:3:5, 4:5:6);
ena = 1; data = 8'hff; //assert ena to enable loading the register (clk *> qb) = (2:4:5, 3:5:6);
@(posedge clk) ; //should NOT load data with reset asserted
#2 rst = 1; //de-assert reset endspecify
@(posedge clk) ; //should load data (hex FF) endmodule
@(negedge clk) data = 8'h55; //sync to negedge clock to meet setup spec.
@(posedge clk) ; //should load data (hex 55)
#10 ena = 0; data = 8'hff; //de-assert enable
@(posedge clk) ; //should NOT load data with ena de-asserted
#20 $stop;
#10 $finish;
end

//display inputs & outputs as waveform

initial
begin
$shm_open("lab2.shm");
$shm_probe("A");
#100 $stop;
end

endmodule

D-6 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-7
Appendix D Lab 3 test.v test.v Appendix D Lab 3

test.v
/************************************************************************* initial
* Stimulus to test the D Flip-Flop model with timing checks - Verilog begin
* Training Course, Lab3. $shm_open("database.shm");
* $shm_probe("A");
* This stimulus should cause timing violations under the following #100 $stop;
conditions: end
* with Minimum Delays: No violations
* with Typical Delays: A setup violation endmodule
* with maximum Delays: A setup and a hold violation
*************************************************************************/
module test;

reg data, rst, start;

dff d1 (out, outb, clk, data, rst);

nand #10 (clk, clk, start); //a 20ns clock oscillator

initial //initialize the clock oscillator


begin
start = 0;
#20 start = 1;
end

initial
begin
rst = 0; //check that the flip-flop resets
#15 rst = 1;

#15 //sync to negedge of clock to avoid timing violation


data = 1; //check to see if can clock in a 1

#20 //sync to negedge of clock to avoid timing violation


data = 0; //check to see if can clock in a 0

#20 //sync to negedge of clock


#6 data = 1; //check to see if get setup violation

#4 //sync to posedge of clock


#5 data = 0; //check to see if get hold violation

#50 $finish;
end

D-8 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-9
Appendix D Lab 4 counter.v counter_test.v Appendix D Lab 4

Lab 4 counter_test.v
/********************************************************************
counter.v * Stimulus to test the 5-bit counter - Verilog Training Course
/******************************************************************* *********************************************************************/
* Netlist of a 5-bit counter - Verilog Training course
* timescale 1 ns/1 ns //DELAYS ARE IN NANOSECONDS WITH NO DECIMAL PLACES
*******************************************************************/
timescale 1ns / 1ns module counter_test;
module counter(cnt,clk,data,rst,load); reg [4:0] data;
output [4:0] cnt;
reg rst, load,tmp, clk;
input [4:0] data;
input clk, rst, load; wire [4:0] cnt;

reg [4:0] cnt; define period 20

always @(rst) counter c1(cnt, clk, data, rst, load);


if(!rst)
# 3 assign cnt = 5'b0;
else // Define the clock oscillator
deassign cnt; always #10 clk = ~clk;

always @(posedge clk) initial


begin $timeformat(-9, 1, " ns", 9);
if (rst == 1 && load == 1)
#3 cnt = data;
initial // display output values
else if (rst == 1 && load == 0)
#4 cnt = cnt +1; $monitor($stime,,"data %h ",data," clk = ",clk," rst = ",rst," load =
end ",load," cnt = ",cnt);

endmodule initial //displays the waveform


begin
$shm_open("lab4.shm");
$shm_probe(data);
$shm_probe(clk);
$shm_probe(rst);
$shm_probe(load);
$shm_probe(cnt);
#1 $stop;
end

D-10 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-11
Appendix D Lab 4 counter_test.v alu.v Appendix D Lab 5

initial Lab 5
begin
clk= 0;
alu.v

//CHECK THAT THE COUNTER RESETS /**********************************************************************


load = 0; //load is NOT asserted * Model of an ALU - Verilog Training Course.
data = 5'h15; //this value should NOT be loaded *********************************************************************/
rst = 0; #period rst = 1; //assert reset for 1 clock cycle timescale 1ns / 100ps
module alu(alu_out, zero, opcode, data, accum, clock);
input [7:0] data, accum;
//ALLOW COUNTER TO COUNT TO 5 input [2:0] opcode;
#(period * 5) ; input clock;
output [7:0] alu_out;
//LOAD COUNTER WITH HEX 1D output zero;
data = 5'h1D;
reg zero;
load = 1; #period load = 0; //assert load for 1 clock cycle
reg [7:0] alu_out;
//increment counter 5 times - should cause overflow to 0
#(period * 5) ; define pass_acum_0 3'b000
define pass_acum_1 3'b001
$stop; define Add 3'b010
end define And 3'b011
define Xor 3'b100
define pass_data 3'b101
endmodule define pass_acum_6 3'b110
define pass_acum_7 3'b111

always @(accum)
#1.2 zero= (!accum);

always
@(negedge clock) #3.5
case (opcode)
Add : alu_out = accum + data;
And : alu_out = accum & data;
Xor : alu_out = accum ^ data;
pass_data : alu_out = data ;
pass_acum_0,

D-12 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-13
Appendix D Lab 5 alu.v alu_test.v Appendix D Lab 5

pass_acum_1, alu_test.v
pass_acum_6,
/*********************************************************************
pass_acum_7 : alu_out = accum;
default : begin * Stimulus for the ALU design - Verilog Training Course
$display("\nWARNING FROM ALU: Undefined opcode: %b\n", opcode); *********************************************************************/
alu_out = 8'bx; timescale 1ns / 1ns
end module alu_test;
endcase wire [7:0] alu_out;
reg [7:0] data, accum;
endmodule reg [2:0] opcode;
reg start_clk;
integer i;

alu alu1 (alu_out, zero, opcode, data, accum, clk);

//define mnemonics to represent opcodes


define PASS1 3'b000
define PASS2 3'b001
define ADD 3'b010
define AND 3'b011
define XOR 3'b100
define PASSD 3'b101
define PASS3 3'b110
define PASS4 3'b111

define period 20
define prop_delay 4

initial //display time in nanoseconds


$timeformat(-9, 1, " ns", 9);

/**********************************************************************
* GATE LEVEL CLOCK OSCILLATOR
**********************************************************************/
nand #(period/2) (clk, clk, start_clk);

initial
begin
start_clk = 0;
#(period/2) start_clk = 1;
end

D-14 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-15
Appendix D Lab 5 alu_test.v alu_test.v Appendix D Lab 5

/********************************************************************** $realtime, accum, !accum);


* APPLY STIMULUS TO THE INPUT PINS end
*********************************************************************/ ADD : begin
$display("ADD OPERATION :",
initial
" %b %b %b | %b %b",
begin
opcode, data, accum, alu_out, zero);
accum = 8'hDA;
if ((alu_out !== (accum + data)) || (zero !== !accum))
data = 8'h37;
$display("\t\t\t ERROR AT %t, EXPECTED : %b %b\n",
for (i = 0; i <= 7; i = i+1) //VERIFY OPERATION FOR ALL 8 OPCODES
$realtime, accum + data, !accum);
begin
end
@(posedge clk) //change inputs just before negedge of clock
AND : begin
#(period/2 - 1) opcode = i;
$display("AND OPERATION :",
@(negedge clk) //ALU clocks in inputs at negedge of clock
" %b %b %b | %b %b",
//call a subroutine to verify outputs
opcode, data, accum, alu_out, zero);
#prop_delay check_outputs;
if ((alu_out !== (accum & data)) || (zero !== !accum))
end
$display("\t\t\t ERROR AT %t, EXPECTED : %b %b\n",
$realtime, accum & data, !accum);
@(posedge clk) //VERIFY OPERATION WITH UNKNOWN OPCODE
end
#(period/2 - 1) opcode = 3'b00x;
XOR : begin
@(negedge clk)
$display("XOR OPERATION :",
#prop_delay check_outputs;
" %b %b %b | %b %b",
opcode, data, accum, alu_out, zero);
@(posedge clk) //VERIFY OPERATION OF ZERO BIT
if ((alu_out !== (accum ^ data)) || (zero !== !accum))
#(period/2 - 1) accum = 8'h00; opcode = ADD;
$display("\t\t\t ERROR AT %t, EXPECTED : %b %b\n",
@(negedge clk)
$realtime, accum ^ data, !accum);
#prop_delay check_outputs;
end
PASSD : begin
repeat (2) @(posedge clk) ; //WAIT 2 CLOCK CYCLES AND THEN
$display("PASS DATA OPERATION :",
$stop; //GO TO INTERACTIVE DEBUG MODE
" %b %b %b | %b %b",
end
opcode, data, accum, alu_out, zero);
if ((alu_out !== data) || (zero !== !accum))
initial
$display("\t\t\t ERROR AT %t, EXPECTED : %b %b\n",
//allow time for interactive debugging before finishing
$realtime, data, !accum);
#1000 $finish;
end
/********************************************************************** default: begin
* SUBROUTINE TO COMPARE THE ALU OUTPUTS TO EXPECTED RESULTS $display("UNKNOWN OPERATION :",
*********************************************************************/ " %b %b %b | %b %b",
task check_outputs; opcode, data, accum, alu_out, zero);
begin if ((alu_out !== 8'bx) || (zero !== !accum))
casez (opcode) $display("\t\t\t ERROR AT %t, EXPECTED : %b %b\n",
PASS1, $realtime, 8'bx, !accum);
PASS2, end
PASS3, endcase
PASS4 : begin end
$display("PASS ACCUM OPERATION:", endtask
" %b %b %b | %b %b",
opcode, data, accum, alu_out, zero);
if ((alu_out !== accum) || (zero !== !accum))
$display("\t\t\t ERROR AT %t, EXPECTED : %b %b\n",

D-16 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-17
Appendix D Lab 5 alu_test.v scale_mux.v Appendix D Lab 6

initial //display a header for the test output Lab 6


begin
$display("\t\t\t INPUTS OUTPUTS \n");
$display("\t\t\t OPCODE DATA IN ACCUM IN | ALU OUT ZERO BIT"); scale_mux.v
$display("\t\t\t ------ -------- -------- | -------- --------"); module scale_mux(out, a, b, sel);
end parameter size = 1;
/********************************************************************** output [size-1:0] out;
* SETUP THE GRAPHICAL WAVEFORM DISPLAY input [size-1:0] a, b;
**********************************************************************/ input sel;
initial
assign out = sel==1 ? a :
begin
sel==0 ? b :
$shm_open("lab5.shm");
bx;
$shm_probe("A");
#1 $stop; endmodule
end

endmodule

D-18 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-19
Appendix D Lab 6 test_mux.v mem.v Appendix D Lab 7

test_mux.v Lab 7
module test_mux;
mem.v
reg [7:0] a, b; /*********************************************************************
wire [7:0] out; * Model of RAM Memory - Verilog Training Course.
reg sel; *********************************************************************/

scale_mux #8 m1(out, a, b, sel); timescale 1ns / 1ns

initial module mem(data,addr,read,write);


$monitorb("%d out=%b a=%b b=%b sel=%b",$time,out,a,b,sel); inout [7:0] data;
input [4:0] addr;
input read, write;
initial
begin reg [7:0] memory [0:31];
$shm_open("lab6.shm");
$shm_probe(out,a, b, sel); assign data = (read ? memory[addr] : 8'bz);
#0 $stop;
end always @(posedge write)
memory[addr] = data;
initial endmodule
begin
#10 a = 8'b0; b = 8'b10; sel = 'bx;
#20 sel = 1;
#10 sel = 1'b0;
#20 $stop;
end
endmodule

D-20 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-21
Appendix D Lab 7 mem_test.v mem_test.v Appendix D Lab 7

mem_test.v #9 read = 0;
/*************************************************************************
* Stimulus for the RAM model - Verilog Training Course $display("\n Setting all memory cells to alternating patterns...",$stime);
*************************************************************************/ #10 addr = 0;
timescale 1ns / 1ns repeat (16)
begin
module memtest; data = 8'hAA;
#1 write = 1; #9 write = 0;
reg read, write; #10 addr = addr + 1;
reg [4:0] addr; data = 8'h55;
wire [7:0] data; #1 write = 1; #9 write = 0;
reg [7:0] expected; #10 addr = addr + 1;
integer error_cnt; end

mem m1(data,addr,read,write); $display("\n Doing block read from five memory addresses...");
#10 addr = 5'h05;
initial //display time in nanoseconds expected = 8'h55;
$timeformat(-9, 1, " ns", 9); read = 1;
repeat (5)
initial begin
begin #1 if (data !== expected)
error_cnt = 0; begin
$display("\n Setting all memory cells to zero..."); $display("** ERROR at %t! read back %h from address %h:",
data = 8'h0; $realtime, data, addr, " Expected to read %h", expected);
write = 0; error_cnt = error_cnt + 1;
read = 0; end
addr = 0; #9 addr = addr + 1;
repeat (32) expected = ~expected;
begin end
#1 write = 1; #9 write = 0; read = 0;
#10 addr = addr + 1; #10 addr = 0;
end $display("\n Completed Memory Tests With %0d Errors!\n", error_cnt);
data = 8'hFF; #1 $stop;
end
$display("\n Reading from one memory address...");
#10 addr = 5'h0A; initial
read = 1; begin
#1 if (data !== 8'h00) $shm_open ("lab7.shm");
begin $shm_probe (write,read,addr,data);
$display("** ERROR at %t! read back %h from address %h:", #1 $stop;
$realtime, data, addr, " Expected to read 00"); end
error_cnt = error_cnt + 1; endmodule
end

D-22 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-23
Appendix D Lab 7 mem_test.v_fixed mem_test.v_fixed Appendix D Lab 7

mem_test.v_fixed #1 if (data !== 8'h00)


/********************************************************************** begin
* Stimulus for the RAM model - Verilog Training Course $display("** ERROR at %t! read back %h from address %h:",
**********************************************************************/ $realtime, data, addr, " Expected to read 00");
error_cnt = error_cnt + 1;
timescale 1ns / 1ns end
#9 read = 0;
module memtest;
$display("\n Setting all memory cells to alternating patterns...", $stime);
reg read, write; #10 addr = 0;
reg [4:0] addr; repeat (16)
wire [7:0] data; begin
reg [7:0] expected; data_reg = 8'hAA; //ASSIGN VALUES TO SHADOW REGISTER
integer error_cnt; #1 write = 1; #9 write = 0;
#10 addr = addr + 1;
reg [7:0] data_reg; //SHADOW REGISTER FOR PROCEDURAL ASSIGNMENTS data_reg = 8'h55; //ASSIGN VALUES TO SHADOW REGISTER
#1 write = 1; #9 write = 0;
assign data = write? data_reg: 8'bz; //TRANSFER SHADOW REGISTER TO DATA BUS #10 addr = addr + 1;
end
mem m1(data,addr,read,write);
$display("\n Doing block read from five memory addresses...");
initial //display time in nanoseconds #10 addr = 5'h05;
$timeformat(-9, 1, " ns", 9); expected = 8'h55;
read = 1;
initial repeat (5)
begin begin
error_cnt = 0; #1 if (data !== expected)
$display("\n Setting all memory cells to zero..."); begin
data_reg = 8'h0; //ASSIGN VALUES TO SHADOW REGISTER $display("** ERROR at %t! read back %h from address %h:",
write = 0; $realtime, data, addr, " Expected to read %h", expected);
read = 0; error_cnt = error_cnt + 1;
addr = 0; end
repeat (32) #9 addr = addr + 1;
begin expected = ~expected;
#1 write = 1; #9 write = 0; end
#10 addr = addr + 1; read = 0;
end #10 addr = 0;
data_reg = 8'hFF; //ASSIGN VALUES TO SHADOW REGISTER $display("\n Completed Memory Tests With %0d Errors!\n", error_cnt);
#1 $stop;
$display("\n Reading from one memory address..."); end
#10 addr = 5'h0A;
read = 1;

D-24 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-25
Appendix D Lab 7 mem_test.v_fixed control_decoder.v Appendix D Lab 8

initial Lab 8
begin
$shm_open ("lab7.shm");
control_decoder.v
$shm_probe (write,read,addr,data);
#1 $stop; /*************************************************************************
end * This is a COMBINATIONAL LOGIC model of the Sequence Controller -
* Verilog Training Course.
endmodule *
* This model uses combinational logic to generate the control lines used in
* the VeriRisc CPU design. The combinational logic is sensitive to changes
* in logic value on any of the inputs. When any of these inputs change
* value, the model will decode all inputs and apply appropriate values to
* the output control signals.
*************************************************************************/
timescale 1ns / 1ns
module control(load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt,
opcode, fetch, zero, clk, clk2, reset);

output load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt;


input [2:0] opcode;
input fetch, zero, clk, clk2, reset;

reg load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt;


wire [2:0] opcode;

define HLT 3'h0


define SKZ 3'h1
define ADD 3'h2
define AND 3'h3
define XOR 3'h4
define LDA 3'h5
define STO 3'h6
define JMP 3'h7

always @ (clk or clk2 or fetch or opcode or zero or reset)


begin
if (reset == 0)
begin
inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
wait (reset == 1) ; //stay reset as long as reset is low
wait (clk & !clk2 & !fetch) ; //hold reset until next fetch cycle
end
else
case ({clk, clk2, fetch})
3'b011 : instruction_fetch_setup;
3'b111 : instruction_fetch;
3'b001 : instruction_load;
3'b101 : idle;

D-26 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-27
Appendix D Lab 8 control_decoder.v control_decoder.v Appendix D Lab 8

3'b010 : operand_fetch_setup; LDA : begin


3'b110 : operand_fetch; inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=1; load_ir=0; halt=0;
3'b000 : instruction_operation; end
3'b100 : store_result; default: begin
endcase inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
end end
endcase
task instruction_fetch_setup; end
begin endtask
inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
end task instruction_operation;
endtask begin
case (opcode)
task instruction_fetch; SKZ : begin
begin if (zero)
inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=1; load_ir=0; halt=0; begin
end inc_pc=1; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
endtask end
else
task instruction_load; begin
begin inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=1; load_ir=1; halt=0; end
end end
endtask ADD,
AND,
task idle; XOR,
begin LDA : begin
inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=1; load_ir=1; halt=0; inc_pc=0; load_acc=1; load_pc=0; mem_wr=0; mem_rd=1; load_ir=0; halt=0;
end end
endtask HLT,
STO : begin
task operand_fetch_setup; inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
begin end
case (opcode) JMP : begin
HLT : begin inc_pc=0; load_acc=0; load_pc=1; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
inc_pc=1; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=1; end
end endcase
default: begin end
inc_pc=1; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0; endtask
end
endcase task store_result;
end begin
endtask case (opcode)
HLT : begin
task operand_fetch; inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
begin end
case (opcode) SKZ : begin
ADD, if (zero)
AND, begin
XOR, inc_pc=1; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;

D-28 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-29
Appendix D Lab 8 control_decoder.v control_state.v Appendix D Lab 8

end control_state.v
else
/************************************************************************
begin
inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0; * This is a State Machine model of the Sequence Contoller -
end * Verilog Training Course.
end *
ADD, * This model uses sequential logic (a state counter) to generate the
AND, * control lines used in the VeriRisc CPU design. Only the "clk" and "fetch"
XOR, * clock inputs are used when this controller is modeled as a state machine.
LDA : begin
* The "clk2" input is not used.
inc_pc=0; load_acc=1; load_pc=0; mem_wr=0; mem_rd=1; load_ir=0; halt=0;
*************************************************************************/
end
JMP : begin
inc_pc=1; load_acc=0; load_pc=1; mem_wr=0; mem_rd=0; load_ir=0; halt=0; timescale 1ns / 1ns
end module control(load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt,
STO : begin opcode, fetch, zero, clk, clk2, reset);
inc_pc=0; load_acc=0; load_pc=0; mem_wr=1; mem_rd=0; load_ir=0; halt=0;
end output load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt;
endcase input [2:0] opcode;
end input fetch, zero, clk, clk2, reset;
endtask
endmodule reg load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt;
wire [2:0] opcode;

define HLT 3'h0


define SKZ 3'h1
define ADD 3'h2
define AND 3'h3
define XOR 3'h4
define LDA 3'h5
define STO 3'h6
define JMP 3'h7

always @(negedge reset) //RESET ALL CONTROLLER OUTPUTS


begin
assign load_acc = 0; //hold outputs in reset state when reset = 0
assign load_pc = 0;
assign mem_wr = 0;
assign mem_rd = 0;
assign inc_pc = 0;
assign load_ir = 0;
assign halt = 0;
wait (reset == 1) ; //stay reset as long as reset is low
wait (clk & !clk2 & !fetch) ; //hold reset until next fetch cycle
deassign load_acc;
deassign load_pc;
deassign mem_wr;
deassign mem_rd;
deassign inc_pc;
deassign load_ir;

D-30 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-31
Appendix D Lab 8 control_state.v control_state.v Appendix D Lab 8

deassign halt; task instruction_operation; //state 6


end begin
case (opcode)
always //START OF FETCH INSTRUCTION / FETCH OPERAND CYCLE HLT : ;
begin SKZ : if (zero) inc_pc = 1;
@(posedge fetch) //STATE 0: setup for instruction fetch else inc_pc = 0;
instruction_fetch_setup; ADD,
@(posedge clk) //STATE 1: instruction fetch AND,
mem_rd = 1; XOR,
@(negedge clk) //STATE 2: instruction load LDA : load_acc = 1;
load_ir = 1; STO : ;
@(posedge clk) //STATE 3: idle JMP : load_pc = 1;
; endcase
@(negedge clk) //STATE 4: setup for operand fetch end
operand_fetch_setup; endtask
@(posedge clk) //STATE 5: operand fetch
operand_fetch; task store_result; //state 7
@(negedge clk) //STATE 6: perform ALU operation begin
instruction_operation; if (opcode == STO) mem_wr = 1;
@(posedge clk) //STATE 7: store results if (opcode == JMP) inc_pc = 1;
store_result; end
end //END OF FETCH INSTRUCTION / FETCH OPERAND CYCLE endtask

task instruction_fetch_setup; //state 0 endmodule


begin
inc_pc=0; load_acc=0; load_pc=0; mem_wr=0; mem_rd=0; load_ir=0; halt=0;
end
endtask

task operand_fetch_setup; //state 4


begin
inc_pc=1; mem_rd=0; load_ir=0;
if (opcode == HLT) halt=1;
end
endtask

task operand_fetch; //state 5


begin
inc_pc=0;
case (opcode)
HLT : halt = 0;
ADD,
AND,
XOR,
LDA : mem_rd = 1;
default: mem_rd = 0;
endcase
end
endtask

D-32 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-33
Appendix D Lab 8 control_test.v control_test.v Appendix D Lab 8

control_test.v /*************************************************************************
/************************************************************************* * Generate the three input clocks
*************************************************************************/
* Stimulus to test the Sequence Controller - Verilog Training Course
initial
*
fork
* This module contains the following parts: clk=0;
* clk2=1;
* 1. A routine which reads stimulus from a test pattern file and compares fetch=1;
* the simulation results to an expected results file. forever #(period/2) clk = ~clk;
* forever #(period) clk2 = ~clk2;
forever #(period*2) fetch = ~fetch;
* 2. A task which can be invoked interactively to generate a new expected
join
* results file.
*************************************************************************/
/*************************************************************************
* Load in the test vector pattern file and apply each pattern to the
timescale 1ns / 1ns
module controller_test; * controller inputs.
*************************************************************************/
define period 20 initial
define setup_time 2 begin
define prop_delay 6 /* time for changes on inputs to reach outputs */
$readmemb("test_vectors.pat", test_vectors); //load input vector file
define num_vectors 16
define num_results 128 {reset, zero, opcode} = test_vectors[1]; //apply 1st test vector

define actual_results for (vector = 2; vector <= num_vectors; vector = vector + 1)


{load_acc,mem_rd,mem_wr,inc_pc,load_pc,load_ir,halt} @(negedge fetch)
#((period*2) -setup_time) //apply next vector just before fetch
reg [2:0] opcode; {reset, zero, opcode} = test_vectors[vector];
reg reset, zero, clk, clk2, fetch;
repeat (2) @(posedge fetch); //wait until last pattern has been processed
reg [4:0] test_vectors [1:num_vectors]; //arrays to hold pattern files $display("\n*** REACHED END OF TEST VECTORS ***");
reg [6:0] expected_results [1:num_results]; $display("\nThere were %0d errors detected!\n", num_errors);
reg [6:0] expected; $display("Enter \"$reset;\" to reset the simulation to time 0.");
$display("Enter \"gen_results;.\" to create a new expected results
reg[(3*8):0] mnemonic; //reg to hold 3 8-bit ASCII character opcode mnemonic file.\n");
$stop;
integer vector, result, num_errors; end

control i1(load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt,


opcode, fetch, zero, clk, clk2, reset);

initial //display time in nanoseconds


$timeformat(-9, 1, " ns", 9);

D-34 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-35
Appendix D Lab 8 control_test.v control_test.v Appendix D Lab 8

/************************************************************************* /*************************************************************************
* Load in the expected results pattern file and compare each pattern to the * Setup graphical waveforms display
* controller outputs. *************************************************************************/
*************************************************************************/ initial //waveforms display
initial begin
begin: DEBUG $shm_open("lab8.shm");
$shm_probe(reset);
$readmemb("expected_results.pat", expected_results); //load file
$shm_probe(clk);
result = 0; $shm_probe(clk2);
num_errors = 0; $shm_probe(fetch);
forever @(clk) //check outputs at every edge of clk $shm_probe(zero);
begin $shm_probe(opcode);
result = result + 1; $shm_probe(mnemonic);
#prop_delay if (actual_results !== expected_results[result]) $shm_probe(inc_pc);
begin
$shm_probe(load_acc);
num_errors = num_errors + 1;
expected = expected_results[result]; $shm_probe(load_pc);
$display("*** Error at %t:",$realtime, $shm_probe(mem_wr);
"\tTest Vector No. %0d: Expected Results No. %0d.", $shm_probe(mem_rd);
(vector - 1), result); $shm_probe(load_ir);
if (load_acc !== expected[6]) $shm_probe(halt);
$display(" load_acc = %b expected: %b",
#1 $stop;
load_acc, expected[6]);
if (mem_rd !== expected[5]) end
$display(" mem_rd = %b expected: %b",
mem_rd, expected[5]);
if (mem_wr !== expected[4]) always @(opcode) //get an ASCII mnemonic for each opcode
$display(" mem_wr = %b expected: %b", begin
mem_wr, expected[4]); case(opcode)
if (inc_pc !== expected[3]) 3'h0 : mnemonic = "HLT";
$display(" inc_pc = %b expected: %b", 3'h1 : mnemonic = "SKZ";
inc_pc, expected[3]); 3'h2 : mnemonic = "ADD";
if (load_pc !== expected[2]) 3'h3 : mnemonic = "AND";
$display(" load_pc = %b expected: %b", 3'h4 : mnemonic = "XOR";
load_pc, expected[2]); 3'h5 : mnemonic = "LDA";
if (load_ir !== expected[1]) 3'h6 : mnemonic = "STO";
$display(" load_ir = %b expected: %b", 3'h7 : mnemonic = "JMP";
load_ir, expected[1]); default : mnemonic = "???";
if (halt !== expected[0]) endcase
$display(" halt = %b expected: %b", end
halt, expected[0]);
// $stop; // Stop on errors for debugging
end
end
end

D-36 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-37
Appendix D Lab 8 control_test.v expected_results.pat Appendix D Lab 8

/************************************************************************* expected_results.pat
* Task to generate a new file of expected results based on the current test //EXPECTED RESULT PATTERNS FOR TESTING THE VeriRisc SEQUENCE CONTROLLER
* pattern file and decoder model. //
* //THE PATTERN ORDER IS: load_acc mem_rd mem_wr inc_pc load_pc load_ir halt
* This task may be called interactively by entering: gen_results; //
*************************************************************************/ 0000000
task gen_results; 0000000
integer results; 0000000
0000000
begin 0000000
$display("\n*** Generating a new expected results file..."); 0000000
if ($stime != 0) 0000000
begin 0000000
$display("\nERROR: The \"gen_results\" routine requires simulation ", 0100000
"be at time zero."); 0100010
$display("The simulation can be reset to time zero by entering ", 0100010
"\"$reset;\"\n"); 0001000
$stop; 0000000
end 0000000
#0 disable DEBUG; //turn off block that checks simulation results 0000000
0000000
results = $fopen("expected_results.pat"); 0100000
$fdisplay(results,"//EXPECTED RESULT PATTERNS FOR TESTING THE ", 0100010
"VeriRisc DECODER"); 0100010
$fdisplay(results,"//"); 0001000
$fdisplay(results,"//THE PATTERN ORDER IS: load_acc mem_rd mem_wr ", 0100000
"inc_pc load_pc load_ir halt"); 1100000
$fdisplay(results,"//"); 1100000
0000000
forever @(clk) 0100000
#prop_delay $fstrobe(results, load_acc, mem_rd, mem_wr, inc_pc, 0100010
load_pc, load_ir, halt); 0100010
end 0001000
endtask 0100000
1100000
endmodule 1100000
0000000
0100000
0100010
0100010
0001000
0100000
1100000
1100000
0000000
0100000
0100010
0100010
0001000

D-38 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-39
Appendix D Lab 8 expected_results.pat expected_results.pat Appendix D Lab 8

0100000 1100000
1100000 0000000
1100000 0100000
0000000 0100010
0100000 0100010
0100010 0001000
0100010 0100000
0001000 1100000
0000000 1100000
0000000 0000000
0010000 0100000
0000000 0100010
0100000 0100010
0100010 0001000
0100010 0000000
0001000 0000000
0000000 0010000
0000100 0000000
0001100 0100000
0000000 0100010
0100000 0100010
0100010 0001000
0100010 0000000
0001000 0000100
0000000 0001100
0001000 0000000
0001000 0100000
0000000 0100010
0100000 0100010
0100010 0001001
0100010 0000000
0001000 0000000
0100000 0000000
1100000
1100000
0000000
0100000
0100010
0100010
0001000
0100000
1100000
1100000
0000000
0100000
0100010
0100010
0001000
0100000
1100000

D-40 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-41
Appendix D Lab 8 run_dec.f test_vector_gen.v Appendix D Lab 8

run_dec.f test_vector_gen.v
/*************************************************************************
control_test.v * Procedural stimulus to test the Sequence Controller - Verilog Training
control_decoder.v * Course.
*
* This module contains the following parts:
run_state.f
*
* 1. A routine which provides procedural stimulus to the inputs of the
control_test.v * controller design.
control_state.v
*
* 2. A routine to generate a test vector file based on the procedural
* stimulus.
*
* 3. A routine to generate an expected results file based on the outputs
* of the controller design.
*************************************************************************/

timescale 1ns / 1ns


module test_vector_generator;

define period 20
define setup_time 2
define hold_time ((period * 4) - setup_time)

define prop_delay 5

reg [2:0] opcode;


reg reset, zero, clk, clk2, fetch;

integer vector_file, results_file, i;

control d1(load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt,


opcode, fetch, zero, clk, clk2, reset);

initial //DISPLAY TIME IN NANOSECONDS


$timeformat(-9, 1, " ns", 9);

initial //GENERATE THE 3 CLOCKS


fork
clk=0;
clk2=1;
fetch=1;
forever #(period/2) clk = ~clk;
forever #(period) clk2 = ~clk2;
forever #((period*2)) fetch = ~fetch;
join

D-42 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-43
Appendix D Lab 8 test_vector_gen.v test_vector_gen.v Appendix D Lab 8

initial //CREATE INPUT STIMULUS WITH PROCEDURAL STATEMENTS


begin results_file = $fopen("expected_results.pat");
//reset the system $fdisplay(results_file,"//EXPECTED RESULT PATTERNS FOR TESTING THE ",
zero = 0; "VeriRisc SEQUENCE CONTROLLER");
opcode = 0; $fdisplay(results_file,"//");
reset = 0; $fdisplay(results_file,"//THE PATTERN ORDER IS: load_acc mem_rd ",
#10 reset = 1; "mem_wr inc_pc load_pc load_ir halt");
$fdisplay(results_file,"//");
//test all instructions except halt with zero bit = 0
opcode = 1; forever @(clk)
for (i = 2; i <= 7; i = i+1) //change opcode just before posedge fetch #prop_delay $fstrobe(results_file, load_acc, mem_rd, mem_wr, inc_pc,
@(posedge fetch) #hold_time opcode = i; load_pc, load_ir, halt);
end
//test all instructions except halt with zero bit = 1 endmodule
@(posedge fetch) #hold_time zero = 1;
opcode = 1;
for (i = 2; i <= 7; i = i+1) //change opcode just before posedge fetch
@(posedge fetch) #hold_time opcode = i;

//test halt instruction


@(posedge fetch) #hold_time opcode = 0;

@(posedge fetch) #hold_time


$display("\n*** Completed generating new pattern files. ***\n");
$finish;
end

initial //WRITE INPUT STIMULUS TO TEST VECTOR FILE


begin
$display("\n*** Generating test vector file ",
"\"test_vectors.pat\"...");

vector_file = $fopen("test_vectors.pat");
$fdisplay(vector_file,"//TEST VECTORS FOR TESTING THE SEQUENCE
CONTROLLER");
$fdisplay(vector_file,"//");
$fdisplay(vector_file,"//THE VECTOR ORDER IS: reset zero_bit opcode");
$fdisplay(vector_file,"//");

//write first pattern to file at end of time 0


$fstrobe(vector_file,"%b_%b_%b", reset, zero, opcode);

forever @(posedge fetch) //write input pattern to file at every fetch


$fstrobe(vector_file,"%b_%b_%b", reset, zero, opcode);
end

initial //WRITE OUTPUTS TO AN EXPECTED RESULTS FILE


begin
$display("\n*** Generating expected results file ",
"\"expected_results.pat\"...");

D-44 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-45
Appendix D Lab 8 test_vectors.pat clkgen.v Appendix D Lab 9

test_vectors.pat Lab 9
//TEST VECTORS FOR TESTING THE SEQUENCE CONTROLLER
// clkgen.v
//THE VECTOR ORDER IS: reset zero_bit opcode
// /*************************************************************************
0_0_000 * A free-running 3 phase clock oscillator for the VeriRisc CPU system -
1_0_001 * Verilog Training Course.
1_0_010 *
1_0_011 * This module generates 3 clocks with the following specification:
1_0_100
*
1_0_101
* The period for clk = 20 ns, clk2 = 40 ns, and fetch = 60 ns
1_0_110
1_0_111 **************************************************************************
1_1_001 /
1_1_010
1_1_011 timescale 1ns / 1ns
1_1_100 module clkgen(fetch, clk2, clk);
1_1_101 output fetch, clk2, clk;
1_1_110
1_1_111 reg fetch, clk2, clk;
1_1_000
define period 20

initial
fork
clk=0;
clk2=1;
fetch=1;
forever #(period/2) clk = ~clk;
forever #(period) clk2 = ~clk2;
forever #(period*2) fetch = ~fetch;
join
endmodule

D-46 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-47
Appendix D Lab 9 cpu.log cpu.log Appendix D Lab 9

cpu.log
**************************************************************************
Host command: /net/ashley/usr1/9404/tools.sun4/verilog/bin/verilog
* THE FOLLOWING DEBUG TASKS ARE AVAILABLE: *
Command arguments:
* Enter "test1;" to load the 1st diagnostic program, and then continue
-f run.f
simulation.
cpu_test.v
* Enter "test2;" to load the 2nd diagnostic program, and then continue
cpu.v simulation.
clkgen.v * Enter "test3;" to load the Fibonacci program, and then continue simulation.
../lab2-register/register.v * Run cwaves if you would like to see the waveforms for this lab *
../lab4-counter/counter.v **************************************************************************
../lab5-alu/alu.v
../lab7-mem/mem.v L55 "cpu_test.v": $stop at simulation time 0.0 ns
../lab8-control/control.v Type ? for help
-y ../lab2-register/cells_lib C1 > test1;.
+libext+.v
+delay_mode_zero *** RUNNING CPUtest1 - THE BASIC CPU DIAGNOSTIC PROGRAM ***
+caxl *** (THIS TEST SHOULD HALT WITH THE PC AT 17 hex) ***

VERILOG-XL 2.1.2 log file created Feb 8, 1995 11:01:24 TIME PC INSTR OP DATA ADR
VERILOG-XL 2.1.2 Feb 8, 1995 11:01:24 ---------- -- ----- -- ---- ---
2.0 ns 00 HLT 0 zz 00
Copyright (c) 1994 Cadence Design Systems, Inc. All Rights Reserved. 111.0 ns 00 JMP 7 fe 00
Unpublished -- rights reserved under the copyright laws of the United States. 191.0 ns 1e JMP 7 e3 1e
271.0 ns 03 LDA 5 ba 03
Copyright (c) 1994 UNIX Systems Laboratories, Inc. Reproduced with 351.0 ns 04 SKZ 1 20 04
Permission. 431.0 ns 06 LDA 5 bb 06
511.0 ns 07 SKZ 1 20 07
For technical assistance please contact the Cadence Response Center at 591.0 ns 08 JMP 7 ea 08
1-800-CADENC2 or send email to crc_customers@cadence.com 671.0 ns 0a STO 6 dc 0a
751.0 ns 0b LDA 5 ba 0b
For more information on Cadence's Verilog-XL product line send email to 831.0 ns 0c STO 6 dc 0c
talkverilog@cadence.com 911.0 ns 0d LDA 5 bc 0d
991.0 ns 0e SKZ 1 20 0e
Compiling source file "cpu_test.v" 1071.0 ns 10 XOR 4 9b 10
Compiling source file "cpu.v" 1151.0 ns 11 SKZ 1 20 11
Compiling source file "clkgen.v" 1231.0 ns 12 JMP 7 f4 12
Compiling source file "../lab2-register/register.v" 1311.0 ns 14 XOR 4 9b 14
Compiling source file "../lab4-counter/counter.v" 1391.0 ns 15 SKZ 1 20 15
Compiling source file "../lab5-alu/alu.v" 1471.0 ns 17 HLT 0 00 17
Compiling source file "../lab7-mem/mem.v"
Compiling source file "../lab8-control/control.v" *** A HALT INSTRUCTION WAS PROCESSED BY THE CPU ***
Scanning library directory "../lab2-register/cells_lib"
Highest level modules:
cpu_test

D-48 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-49
Appendix D Lab 9 cpu.log cpu.log Appendix D Lab 9

************************************************************************** **************************************************************************
* THE FOLLOWING DEBUG TASKS ARE AVAILABLE: * * THE FOLLOWING DEBUG TASKS ARE AVAILABLE: *
* Enter "test1;" to load the 1st diagnostic program, and then continue * Enter "test1;" to load the 1st diagnostic program, and then continue
* simulation. simulation.
* Enter "test2;" to load the 2nd diagnostic program, and then continue * Enter "test2;" to load the 2nd diagnostic program, and then continue
simulation. simulation.
* Enter "test3;" to load the Fibonacci program, and then continue simulation. * Enter "test3;" to load the Fibonacci program, and then continue simulation.
* Run cwaves if you would like to see the waveforms for this lab * * Run cwaves if you would like to see the waveforms for this lab *
************************************************************************** **************************************************************************

L62 "cpu_test.v": $stop at simulation time 1510.0 ns L62 "cpu_test.v": $stop at simulation time 2710.0 ns
C2 > test2;. C3 > test3;.

*** RUNNING CPUtest2 - THE ADVANCED CPU DIAGNOSTIC PROGRAM *** *** RUNNING CPUtest3 - AN EXECUTABLE PROGRAM ***
*** (THIS TEST SHOULD HALT WITH THE PC AT 10 hex) *** *** This program should calculate the Fibonacci ***
*** number sequence from 0 to 144 ***
TIME PC INSTR OP DATA ADR
---------- -- ----- -- ---- --- TIME FIBONACCI NUMBER
1631.0 ns 00 LDA 5 bb 00 ---------- ----------------
1711.0 ns 01 AND 3 7c 01 2830.0 ns 0
1791.0 ns 02 XOR 4 9b 02 3550.0 ns 1
1871.0 ns 03 SKZ 1 20 03 4270.0 ns 1
1951.0 ns 05 ADD 2 5a 05 4990.0 ns 2
2031.0 ns 06 SKZ 1 20 06 5710.0 ns 3
2111.0 ns 07 JMP 7 e9 07 6430.0 ns 5
2191.0 ns 09 XOR 4 9c 09 7150.0 ns 8
2271.0 ns 0a ADD 2 5a 0a 7870.0 ns 13
2351.0 ns 0b STO 6 dd 0b 8590.0 ns 21
2431.0 ns 0c LDA 5 ba 0c 9310.0 ns 34
2511.0 ns 0d ADD 2 5d 0d 10030.0 ns 55
2591.0 ns 0e SKZ 1 20 0e 10750.0 ns 89
2671.0 ns 10 HLT 0 00 10 11470.0 ns 144

*** A HALT INSTRUCTION WAS PROCESSED BY THE CPU *** *** A HALT INSTRUCTION WAS PROCESSED BY THE CPU ***

D-50 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-51
Appendix D Lab 9 cpu.log cpu.v Appendix D Lab 9

************************************************************************** cpu.v
* THE FOLLOWING DEBUG TASKS ARE AVAILABLE: * /*************************************************************************
* Enter "test1;" to load the 1st diagnostic program, and then continue * Netlist for the VeriRisc CPU design - Verilog Training Course.
simulation. *************************************************************************/
* Enter "test2;" to load the 2nd diagnostic program, and then continue
simulation. timescale 1ns / 1ns
* Enter "test3;" to load the Fibonacci program, and then continue simulation. module cpu(reset);
* Run cwaves if you would like to see the waveforms for this lab * input reset;
**************************************************************************
wire [7:0] data, alu_out, accum;
L62 "cpu_test.v": $stop at simulation time 12230.0 ns wire [4:0] pc_addr, ir_addr, addr;
C4 > $finish; wire [2:0] opcode;
C4: $finish at simulation time 12230.0 ns
//Instantiate the main components in the design
31237 simulation events + 52300 accelerated events
CPU time: 0.7 secs to compile + 0.5 secs to link + 2.2 secs in simulation control cntl (load_acc, mem_rd, mem_wr, inc_pc, load_pc, load_ir, halt,
End of VERILOG-XL 2.1.2 Feb 8, 1995 11:02:15 opcode, fetch, zero, clock, clk2, reset);
alu alu1 (alu_out, zero, opcode, data, accum, alu_clock);
register acm (accum, clock, alu_out, load_acc, reset);
register ireg ({opcode, ir_addr}, clock, data, load_ir, reset);
mem mem1 (data, addr, mem_rd, mem_wr);
counter pc (pc_addr, inc_pc, ir_addr, reset, load_pc);
clkgen clk (fetch, clk2, clock);

//Glue logic

assign alu_clock = (fetch | clk2 | clock);


assign addr = (fetch ? pc_addr : ir_addr);
assign data = ((!fetch & !mem_rd & !clk2)? alu_out: 8'bz);

endmodule

D-52 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-53
Appendix D Lab 9 cpu_test.v cpu_test.v Appendix D Lab 9

cpu_test.v cpu1.halt,
/************************************************************************* cpu1.opcode,
* Test stimulus for the VeriRisc CPU design - Verilog Training Course. mnemonic, //display opcode as a mnemonic
* cpu1.data,
* This stimulus provides tasks to load and run 3 different diagnostic test cpu1.accum,
* programs. A program is loaded into the VeriRisc memory and the VeriRisc cpu1.alu_out,
* system is reset. The system should then execute the instructions cpu1.addr,
* in the program. cpu1.pc_addr,
* cpu1.ir_addr);
* This stimulus will monitor the program counter as the program runs, and $stop;
* display what instructions are being executed. The comments in the program end
* files can be used to determine if the program executed as expected.
*************************************************************************/ always @(posedge cpu1.halt) //STOP when HALT instruction decoded
begin
timescale 1ns / 1ns #30 $display("\n*** A HALT INSTRUCTION WAS PROCESSED BY THE CPU ***\n");
module cpu_test; display_debug_message;
$stop;
reg reset_req; end
integer test;
reg [(3*8):0] mnemonic; //array that holds 3 8-bit ASCII characters task display_debug_message;
begin
cpu cpu1(reset_req); //instance of the VeriRisc CPU design $display("\n
***********************************************************************");
initial //display time in nanoseconds $display(" * THE FOLLOWING DEBUG TASKS ARE AVAILABLE: *");
$timeformat(-9, 1, " ns", 12); $display(" * Enter \"test1;\" to load the 1st diagnostic program, and then
continue simulation. *");
$display(" * Enter \"test2;\" to load the 2nd diagnostic program, and then
initial //go to interactive mode at time 0
continue simulation. *");
begin
$display(" * Enter \"test3;\" to load the Fibonacci program, and then
display_debug_message; continue simulation. *");
$shm_open("lab9.shm"); $display(" * Run cwaves if you would like to see the waveforms for this lab
//$shm_probe("A"); *");
$shm_probe(cpu_test.cpu1.reset, $display("
cpu1.alu_clock, *********************************************************************\n");
cpu1.clock, end
cpu1.clk2, endtask
cpu1.fetch,
cpu1.zero,
cpu1.inc_pc,
cpu1.load_acc,
cpu1.load_pc,
cpu1.mem_wr,
cpu1.mem_rd,
cpu1.load_ir,

D-54 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-55
Appendix D Lab 9 cpu_test.v cpu_test.v Appendix D Lab 9

task test1; always @(test)


begin begin: MONITOR
test = 0; case (test)
disable MONITOR; 1: begin //display results when running test 1
$readmemb("CPUtest1.dat",cpu1.mem1.memory); //load 1st diagnostic program $display("\n*** RUNNING CPUtest1 - THE BASIC CPU DIAGNOSTIC PROGRAM ***");
#1 test = 1; $display("*** (THIS TEST SHOULD HALT WITH THE PC AT 17 hex) ***");
sys_reset; $display("\n TIME PC INSTR OP DATA ADR");
end $display( " ---------- -- ----- -- ---- ---");
endtask while (test == 1)
@(cpu1.opcode or cpu1.ir_addr)
task test2; #1 $strobe("%t %h %s %h %h %h", $time,
begin cpu1.pc_addr, mnemonic, cpu1.opcode, cpu1.data, cpu1.addr);
test = 0; end
disable MONITOR; 2: begin //display results when running test 2
$readmemb("CPUtest2.dat",cpu1.mem1.memory); //load 2nd diagnostic program $display("\n*** RUNNING CPUtest2 - THE ADVANCED CPU DIAGNOSTIC PROGRAM
#1 test = 2; ***");
sys_reset; $display("*** (THIS TEST SHOULD HALT WITH THE PC AT 10 hex) ***");
end $display("\n TIME PC INSTR OP DATA ADR");
endtask $display( " ---------- -- ----- -- ---- ---");
while (test == 2)
task test3; @(cpu1.opcode or cpu1.ir_addr)
begin #1 $strobe("%t %h %s %h %h %h", $time,
test = 0; cpu1.pc_addr, mnemonic, cpu1.opcode, cpu1.data, cpu1.addr);
disable MONITOR; end
$readmemb("CPUtest3.dat",cpu1.mem1.memory); //load Fibonacci program 3: begin //display results when running test 3
#1 test = 3; $display("\n*** RUNNING CPUtest3 - AN EXECUTABLE PROGRAM ***");
sys_reset; $display("*** This program should calculate the Fibonacci ***");
end $display("*** number sequence from 0 to 144 ***");
endtask $display("\n TIME FIBONACCI NUMBER");
$display( " ---------- ----------------");
task sys_reset; while (test == 3)
begin begin
reset_req = 0; wait (cpu1.opcode == 3'h7) //display Fib. No. at end of program loop
#10 reset_req = 1; $strobe("%t %d", $time, cpu1.mem1.memory[5'h1B]);
end wait (cpu1.opcode != 3'h7) ;
endtask end
end
endcase
end

D-56 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-57
Appendix D Lab 9 cpu_test.v CPUtest1.dat* Appendix D Lab 9

always @(cpu1.opcode) //get an ASCII mnemonic for each opcode CPUtest1.dat*


case(cpu1.opcode) /*************************************************************************
3'h0 : mnemonic = "HLT"; * Test program 1 for the VeriRisc CPU system, Verilog Training Course.
3'h1 : mnemonic = "SKZ"; *
3'h2 : mnemonic = "ADD"; * This diagnostic program tests the basic instruction set of the VeriRisc
3'h3 : mnemonic = "AND"; * system. If the system executes each instruction correctly, then it should
3'h4 : mnemonic = "XOR"; * halt when the HLT instruction at address 17(hex) is executed.
3'h5 : mnemonic = "LDA"; *
3'h6 : mnemonic = "STO"; * If the system halts at any other location, then an instruction did not
3'h7 : mnemonic = "JMP"; * execute properly. Refer to the comments in this file to see which
default : mnemonic = "???"; * instruction failed.
endcase *************************************************************************/

endmodule //opcode_operand // addr assembly code


//-------------- // ---- -----------------------------------------------
@00 111_11110 // 00 BEGIN: JMP TST_JMP
000_00000 // 01 HLT //JMP did not work at all
000_00000 // 02 HLT //JMP did not load PC, it skipped
101_11010 // 03 JMP_OK: LDA DATA_1
001_00000 // 04 SKZ
000_00000 // 05 HLT //SKZ or LDA did not work
101_11011 // 06 LDA DATA_2
001_00000 // 07 SKZ
111_01010 // 08 JMP SKZ_OK
000_00000 // 09 HLT //SKZ or LDA did not work
110_11100 // 0A SKZ_OK: STO TEMP //store non-zero value in TEMP
101_11010 // 0B LDA DATA_1
110_11100 // 0C STO TEMP //store zero value in TEMP
101_11100 // 0D LDA TEMP
001_00000 // 0E SKZ //check to see if STO worked
000_00000 // 0F HLT //STO did not work
100_11011 // 10 XOR DATA_2
001_00000 // 11 SKZ //check to see if XOR worked
111_10100 // 12 JMP XOR_OK
000_00000 // 13 HLT //XOR did not work at all
100_11011 // 14 XOR_OK: XOR DATA_2
001_00000 // 15 SKZ

D-58 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-59
Appendix D Lab 9 CPUtest1.dat* CPUtest2.dat Appendix D Lab 9

000_00000 // 16 HLT //XOR did not switch all bits CPUtest2.dat


000_00000 // 17 END: HLT //CONGRATULATIONS - TEST1 PASSED!
/*************************************************************************
111_00000 // 18 JMP BEGIN //run test again
* Test program 2 for the VeriRisc CPU system, Verilog Training Course.
@1A 00000000 // 1A DATA_1: //constant 00(hex) *
11111111 // 1B DATA_2: //constant FF(hex) * This diagnostic program tests the advanced instruction set of the VeriRisc
10101010 // 1C TEMP: //variable - starts with AA(hex) * system. If the system executes each instruction correctly, then it should
* halt when the HLT instruction at address 10(hex) is executed.
@1E 111_00011 // 1E TST_JMP: JMP JMP_OK
*
000_00000 // 1F HLT //JMP is broken
* If the system halts at any other location, then an instruction did not
* execute properly. Refer to the comments in this file to see which
* instruction failed.
*
* WARNING: The CPUtest1 diagnostic program should be completed successfully
* before this test is run.

*************************************************************************/

//opcode_operand // addr assembly code


//-------------- // ---- -----------------------------------------------
@00 101_11011 // 00 BEGIN: LDA DATA_2
011_11100 // 01 AND DATA_3
100_11011 // 02 XOR DATA_2
001_00000 // 03 SKZ
000_00000 // 04 HLT //AND doesn't work
010_11010 // 05 ADD DATA_1
001_00000 // 06 SKZ
111_01001 // 07 JMP ADD_OK
000_00000 // 08 HLT //ADD doesn't work
100_11100 // 09 XOR DATA_3
010_11010 // 0A ADD DATA_1 //FF plus 1 makes -1
110_11101 // 0B STO TEMP
101_11010 // 0C LDA DATA_1
010_11101 // 0D ADD TEMP //-1 plus 1 should make zero
001_00000 // 0E SKZ
000_00000 // 0F HLT //ADD Doesn't work
000_00000 // 10 END: HLT //CONGRATULATIONS - TEST2 PASSED!
111_00000 // 11 JMP BEGIN //run test again

@1A 00000001 // 1A DATA_1: //constant 1(hex)


10101010 // 1B DATA_2: //constant AA(hex)
11111111 // 1C DATA_3: //constant FF(hex)
00000000 // 1D TEMP:

D-60 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-61
Appendix D Lab 9 CPUtest3.dat run.f Appendix D Lab 9

CPUtest3.dat run.f
/************************************************************************* // This file contains the Verilog invocation commands to run
* Test program 3 for the VeriRisc CPU system, Verilog Training Course. // the VeriRisc CPU design. This run file assumes that the
* // file names referenced in other lab directories are the
* This is an actual program that calculates the Fibonacci number sequence // same name as was specified in the lab specifications.
* from 0 to 144. The Fibonacci number sequence is a series of numbers in
* which each number in the sequence is the sum of the preceding two numbers cpu_test.v
* (i.e.: 0, 1, 1, 2, 3, 5, 8, 13 ...). This number sequence is often used cpu.v
* in financial analysis, and can also be found in the patterns of pineapple clkgen.v
* shells and some flower petals.
* ../lab2-register/register.v
* WARNING: Do not run this program before the CPUtest1 and CPUtest2 ../lab4-counter/counter.v
* diagnostic programs have completed successfully. Those who do are ../lab5-alu/alu.v
* asking for endless heartache. ../lab7-mem/mem.v
*************************************************************************/
../lab8-control/control.v

//opcode_operand // addr assembly code


//-------------- // ---- -y ../lab2-register/cells_lib
---------------------------------------------------- +libext+.v
111_00011 // 00 JMP LOOP //jump to the address of LOOP
@03 101_11011 // 03 LOOP: LDA FN2 //load value in FN2 into accum +delay_mode_zero //ignore delays on all primitives & paths
110_11100 // 04 STO TEMP //store accumulator in TEMP +caxl //use the CAXL alogrithm where applicable
010_11010 // 05 ADD FN1 //add value in FN1 to accumulator
110_11011 // 06 STO FN2 //store result in FN2
101_11100 // 07 LDA TEMP //load TEMP into the accumulator
110_11010 // 08 STO FN1 //store accumulator in FN1
100_11101 // 09 XOR LIMIT //compare accumulator to LIMIT
001_00000 // 0A SKZ //if accum = 0, skip to DONE
111_00011 // 0B JMP LOOP //jump to address of LOOP
000_00000 // 0C DONE: HLT //end of program
101_11111 // 0D AGAIN: LDA ONE
110_11010 // 0E STO FN1
101_11110 // 0F LDA ZERO
110_11011 // 10 STO FN2
111_00011 // 11 JMP LOOP //jump to address of LOOP

@1A 00000001 // 1A FN1: //data storage for 1st Fib. No.


00000000 // 1B FN2: //data storage for 2nd Fib. No.
00000000 // 1C TEMP: //temproray data storage
10010000 // 1D LIMIT: //max value to calculate 144(dec)
00000000 // 1E ZERO: //constant 0(decimal)
00000001 // 1F ONE: //constant 1(decimal)

D-62 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-63
Appendix D Lab 10 dff.v dff_udp.v Appendix D Lab 10

Lab 10 dff_udp.v
/*************************************************************************
dff.v * UDP definition for the basic fucntionality of a D Flip-Flop - Verilog
/************************************************************************* * Training Course, Lab 10.
*************************************************************************/
* D Flip-Flop model using a UDP - Verilog Training Course, Lab 10.
*************************************************************************/
primitive dflop(q, d, clk, rst);
output q;
module dff(q, qb, clk, d, rst);
input d, clk, rst;
output q, qb;
input clk, d, rst;
reg q;
dflop (qt, d, clk, rst);
table
buf (q, qt);
// d clk rst : q_old : q_new
not (qb, qt);
? ? 0 : ? : 0;
? ? x : 0 : 0;
specify
0 (01) 1 : ? : 0;
1 (01) 1 : ? : 1;
$setuphold(posedge clk &&& rst, d &&& rst, 3:5:6, 2:3:6);
? (10) 1 : ? : -;
(??) ? ? : ? : -;
(rst *> q, qb) = 3;
? ? (??) : ? : -;
(clk *> q) = (2:3:5, 4:5:6);
endtable
(clk *> qb) = (2:4:5, 3:5:6);
endprimitive
endspecify
endmodule

D-64 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-65
Appendix D Lab 10 test.v test.v Appendix D Lab 10

test.v initial
/************************************************************************* begin
* Stimulus to test the D Flip-Flop model with timing checks - Verilog $shm_open("lab10.shm");
* Training Course, Lab 10. $shm_probe("A");
* #1 $stop;
* This stimulus should cause timing violations under the following end
* conditions:
* endmodule
* with Minimum Delays: No violations
* with Typical Delays: A setup violation
* with maximum Delays: A setup and a hold violation
*************************************************************************/
module test;

reg data, rst, start;

dff d1 (out, outb, clk, data, rst);

nand #10 (clk, clk, start); //a 20ns clock oscillator

initial //initialize the clock oscillator


begin
start = 0;
#20 start = 1;
end

initial
begin

rst = 0; //check that the flip-flop resets


#15 rst = 1;
@(negedge clk) //sync to negedge of clock to avoid timing violation
data = 1; //check to see if can clock in a 1
@(negedge clk) //sync to negedge of clock to avoid timing violation
data = 0; //check to see if can clock in a 0
@(negedge clk) //sync to negedge of clock
#6 data = 1; //check to see if get setup violation
@(posedge clk) //sync to posedge of clock
#5 data = 0; //check to see if get hold violation
#20 $stop;

end

D-66 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-67
Appendix D Lab 11 register.v register.v_fixed Appendix D Lab 11

Lab 11 register.v_fixed
/*************************************************************************
register.v * 8-bit register with hierarchy, Verilog Training Course, lab 11
/*************************************************************************
*************************************************************************/
* 8-bit register with hierarchy, Verilog Training Course, lab 11
module register(r, clk, data, ena, rst);
*************************************************************************/ output [7:0] r;
module register(r, clk, data, ena, rst); input [7:0] data;
output [7:0] r; input clk, ena, rst;
input [7:0] data;
input clk, ena, rst; wire [7:0] data, r;

wire [7:0] data, r; and a1(load, clk, ena);

and a1(load, clk, ena); dff d0 (r[0], , data[0], load, rst),


d1 (r[1], , data[1], load, rst),
dff d0 (r[0], , data[0], load, rst), d2 (r[2], , data[2], load, rst),
d1 (r[1], , data[1], load, rst), d3 (r[3], , data[3], load, rst),
d2 (r[2], , data[2], load, rst), d4 (r[4], , data[4], load, rst),
d3 (r[2], , data[3], load, rst), d5 (r[5], , data[5], load, rst),
d4 (r[4], , data[4], load, rst), d6 (r[6], , data[6], load, rst),
d5 (r[5], , data[5], load, rst), d7 (r[7], , data[7], load, rst);
d6 (r[6], , data[6], load, rst),
d7 (r[7], , data[7], load, rts); endmodule

endmodule

D-68 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-69
Appendix D Lab 11 register_test.v register_test.v Appendix D Lab 11

register_test.v initial
/************************************************************************* begin
* Stimulus for testing the 8-bit Register - Verilog Training Course, lab 11 error=0;
#20 if(reg_out !== 8'b00000000) begin $display($stime,,"out should be
*************************************************************************/ 8'b00000000 but is 8'b%b",reg_out); error=1; end
module test; #20 if(reg_out !== 8'b11111111) begin $display($stime,,"out should be
8'b11111111 but is 8'b%b",reg_out); error=1; end
wire [7:0] reg_out; //declare vector for register output
#20 if(reg_out !== 8'b01010101) begin $display($stime,,"out should be
reg [7:0] data;
8'b01010101 but is 8'b%b",reg_out); error=1; end
reg ena, rst, start, error;
if (error==0) $display("********** TEST PASSED **********");
else $display("********** TEST FAILED **********");
register r1(reg_out, clk, data, ena, rst);
end

nand #10 (clk, clk, start); //clock oscilator


endmodule
initial //start the clock oscillator
begin
start = 0;
#10 start = 1;
end

initial //apply stimulus to register inputs


begin
rst = 0; //should reset register to hex 00
ena = 1; data = 8'hff; //assert ena to enable loading the register
@(posedge clk) ; //should NOT load data with reset asserted
#2 rst = 1; //de-assert reset
@(posedge clk) ; //should load data (hex FF)
@(negedge clk) data = 8'h55; //sync to negedge clock to meet setup spec.
@(posedge clk) ; //should load data (hex 55)
#10 ena = 0; data = 8'hff; //de-assert enable
@(posedge clk) ; //should NOT load data with ena de-asserted
#20 $stop; $finish;
end

D-70 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-71
Appendix D Lab A buffer.v computer.v Appendix D Lab A

Lab A computer.v
// define QUEUE_ID 0
buffer.v
module computer;
module buffer;
integer SEED , MEAN;
/* A number of 20 overflows, over a period of 40.000 time unit, integer job_id;
is acceptable */ integer delay;
integer status;
integer MAX_LENGTH; integer NUMBER_OF_OVERFLOWS;
integer status;
reg queue_value;
initial
begin
initial SEED = 1; MEAN = 60;
begin job_id = 1;
NUMBER_OF_OVERFLOWS = 0;
MAX_LENGTH = 27; end
// Initialize the queue and check for errors always
$q_initialize (QUEUE_ID, 1, MAX_LENGTH, status); /* Print Warning Messages if the queue is full
if(status !==0) else put a new job in the queue */
begin begin
// $display("status = %d", status); delay= $dist_poisson(SEED, MEAN);
$display("ERROR INITIALIZING THE QUEUE IN THE BUFFER"); #delay;
$finish; if($q_full(QUEUE_ID, status))
end begin
end $display("WARNING - OVERFLOW at time%d for job_id#%d",
$time,job_id);
endmodule NUMBER_OF_OVERFLOWS = NUMBER_OF_OVERFLOWS + 1;
end
else
begin
$q_add(QUEUE_ID, job_id, 0,status);
job_id = job_id + 1;
end
end

endmodule

D-72 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-73
Appendix D Lab A disk.v system.v Appendix D Lab A

disk.v system.v
// define QUEUE_ID 0 define QUEUE_ID 1

module disk; module system;

integer SEED, START, END; integer status;


integer job_id; integer queue_length, max_queue_length, lwt, awt;
integer delay;
integer status; buffer I1();
integer inform_id; computer I2();
disk I3();
initial
begin initial
job_id = 0; forever #10000 $stop;
SEED=23; START=1; END=130;
end
// Display Statistic Values
always always
begin begin
delay = $dist_uniform(SEED,START, END); #1000
#delay; $display("\n\n********************************************************");
$q_remove(QUEUE_ID, job_id, inform_id, status); $display("* TIME=%d",$stime);
end $q_exam(QUEUE_ID, 1, queue_length, status);
$display("* CURRENT QUEUE LENGTH= %d", queue_length);
endmodule
$q_exam(QUEUE_ID, 3, max_queue_length, status);
$display("* MAX QUEUE LENGTH=%d",max_queue_length );

$q_exam(QUEUE_ID, 5, lwt, status);


$display("* LONGEST WAIT TIME=%d", lwt);

$q_exam(QUEUE_ID, 6, awt, status);


$display("* AVERAGE WAIT TIME=%d", awt);
$display("* NUMBER OF OVERFLOWS=%d", I2.NUMBER_OF_OVERFLOWS);
$display("********************************************************");
end

endmodule

D-74 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-75
Appendix D Lab B pull_ud.v test.v Appendix D Lab B

Lab B test.v
// switch resistive cmos_1
pull_ud.v switch resistive default
timescale 1ns/1ps
module pull_ud( cnt,a, b, c, y );
input a, b, c,cnt; module test;
output y; reg a, b, c,cnt;
trireg (* const real capacitance = 1.1; *) y; trireg y;
trireg a, b, c;
supply1 vdd; pull_ud ud(cnt,a,b,c,y);
supply0 gnd;
// initial
// switch resistive cmos_1 begin
switch resistive default $timeformat(-9,2,"ns",5);
tranif0 (* const real width=10, length=1; *) p1( vdd ,y ,cnt ); cnt=0;
tranif1 (* const real width=10, length=1; *) n1(y , gnd , a ); a = 0;
tranif1 (* const real width=10, length=1; *) n2(y , gnd , b ); b = 0;
tranif1 (* const real width=2, length=1; *) n3(y , gnd , c ); c = 0;
// #40 cnt=1'b1;
endmodule a = 1;
b = 0;
c = 0;
#20 a = 1'b0;
cnt=0;
#40 a = 0;
b = 1;
c = 0;
cnt=1;
#20 b = 1'b0;
cnt=0;
#40 a = 0;
b = 0;
c = 1;
cnt=1;
#20 c = 1'b0;
cnt=0;
#10 a=0; b=0; c=0;
cnt=1;
#10 $stop;
end

// Display results
initial
$monitor("%t a=%b b=%b c=%b y=%b",$realtime,a,b,c,y);

endmodule

D-76 Cadence Design Systems, Inc. 6/29/95 6/29/95 Cadence Design Systems, Inc. D-77

Das könnte Ihnen auch gefallen