A
HDL
VERILOGf
Primer
Second Edition
J. Bhasker
A
HDL
Verilog\302\256
Second
Edition
Primer
Other booksby the
author:
same
Verilog HDL Synthesis, A ISBN 0-9650391-5-3.
Practical
A VHDL Primer, Third Edition, ISBN 0-13-096575-8.
Prentice Hall, Englewood Cliffs,
VHDL Primer, Synthesis ISBN 0-9650391-9-6.
Second Edition, Star
VHDL Primer, Synthesis ISBN 0-9650391-0-2.
Star Galaxy
A
A
HDL Primer, Verilog ISBN 0-9656277-4-8.
A
Primer: Revised Edition, VHDL ISBN 0-13-181447-8. Guide to VHDL Syntax, ISBN 0-13-324351-6.
A
VHDL Featuresand Applications: A
VHDL
Primer,
In Japanese:
In German: Verlag
GmbH,
Prentice
Galaxy Press,AUentown,
Prentice HaU, EnglewoodCliffs, Study
IEEE,
Guide,
HaU, Englewood
PA,
A Guide
ISBN
1998,
1997,
1995,
1995,
Cliffs, NJ, 1992,ISBN
Die VHDL-Syntax(Translation of ISBN 3-8272-9528-9.
NJ,
1995, Order
A VHDL Primer, CQ Publishing, Japan, 1996,
NJ,
PA,
1996,
PA,
Prentice Hall, EnglewoodCliffs,
1998,
1999,
NJ,
Galaxy Publishing,AUentown,
Publishing, AUentown,
First Edition, Star
A
Publishing, AUentown, PA
Star Galaxy
Primer,
No. HL5712. 0-13-952987-X.
4-7898-3286-4.
to VHDL
Syntax), Prentice Hall
A
HDL
Verilog
Second Edition
Primer
J. Bhasker Bell
Star
Lucent
Laboratories,
Galaxy
Technologies
Publishing
1058TreelineDrive,
Allentown,
PA
18103
Copyright
1999
\302\251 1997,
Lucent
Technologies.
All rights reserved.
Published by:
Star
Treeline
of this
writing from
Drive, Allentawn,
PA
18103
610-391-7296
Phone:
No part
Publishing
Galaxy
1058
book
the
may
be reproduced,
in
any
form
or by any
means,
without
permission
in
publisher.
WARNING
- DISCLAIMER
The author and examples contained
error-freeor
publisher have used their best efforts in preparing this book and the in it. They make no representation, however, that the examplesare are suitable for every application to which a reader may attempt to apply
of any kind, expressedor the publisher make no warranty or theory contained in this book, these examples,documentation all of which is provided \"as is\". The author and the publisher shall not be liable for any direct or indirect damages arising from any use, direct or indirect, of the examples
them. The
author
and
regard to
implied,
with
provided
in this
book.
trademark of Cadence Design Systems, Inc. Inc. registered trademark of VeriBest, Material in Appendix A is reprinted from IEEE Std 1364-1995 \"IEEE Standard Hardware Based on Hardware the 1995 Description Description Language Verilog Language\", Copyright \302\251 from the placement by the IEEE, Inc.The IEEE disclaims any responsibility or liability resulting is reprinted with the permission and use in the described manner. Information of the IEEE.
Verilog is a registered VeriBest\302\256
Printed
is a
in
the
United
States
of America
10987654
Library of CongressCatalogCardNumber: ISBN
0-9650391-7-X
98-61678
To my
wife, Geetha
Contents
deface JHAPTER
xv
1
Introduction
1.1.
What
is
1
HDL?,
Verilog
2
1.2.
History,
1.3.
Major Capabilities, 2
1.4.
Exercises, 5
Zhafter 2 A
Tutorial
2.1.
A
6
Module,
2.2.
Delays,
2.3.
Describing in Dataflow
2.4.
Describing
2.5.
Describing
2.6.
Describing
2.7.
8
in
Simulating
Style,
in Structural in
Style, 9
Behavioral
Style, 14 Style,
Mixed-design
a Design,
2.8. Exercises,22
11
17
16
Contents
Chapter 3
Language
24
Elements
24
3.1.
Identifiers,
3.2.
Comments, 25
3.3.
Format,
26
Functions, 26
Tasks and
3.4.
System
3.5.
Compiler
27
Directives,
define and yifdef, *else
3.5.7. 3.5.2.
27
yundef,
and
3.5.3.
*default_nettype,
3.5.4.
^include, 28
28
yendif,
28
3.5.5. >esetall,29
3.6.
3.5.6.
^timescale,
3.5.7.
yunconnected_drive
3.5.8.
ycelldefine
Value Set,
29
and
andynounconnected_drive, 31
yendcelldefine,
32
3.6.1. Integers,32 Decimal
Simple
3.7.
3.6.2.
Base Format 34 Reals,
3.6.3.
Strings, 35
Data
3.7.1.
Form,
33 33
Notation,
36
Types,
Net Types,
37
Tri Nets,
and
Wire
36
Wor and Trior Nets, 38 Triand
and
Wand
Nets,
39
TriregNet, 39 Nets, 40 SupplyO and Supply 1 Nets, Tril
and
TriO
3.7.2. UndeclaredNets, 3.7.3.
Vectored
and Scalared
3.7.4. Register
Types,
Reg
Register,
40
40
Nets, 41
41
41
Memories, 42 Integer
Register,
Time Register,
3.8.
viii
Real and Parameters, 47
Realtime
45
46 Register,
46
31
3.9.
Exercises,48
Zhafter 4
Expressions
4.1.
50
Operands,
51
4.1.1.
Constant,
4.1.2.
Parameter, 52
4.1.3.
Net,
4.1.4.
Register,
4.1.5.
Bit-select, 53
52
52
4.1.6. Part-select,53 A2.
4.1.7.
Memory
4.1.8.
Function
54
Element,
Call, 54
Operators, 55
4.2.1.
Arithmetic
57
Operators,
Result Size,
57
Unsignedand 4.2.2.
Relational
4.2.3.
Equality
4.2.4.
Logical
4.2.5.
Bit-wise
4.2.6.
Reduction
58
Signed,
60
Operators, 61
Operators,
Operators,
62 63
Operators,
Operators,
4.2.7.
Shift
4.2.8.
Conditional
65
66
Operators,
Operator,
67
and Replication, 4.2.9. Concatenation of Expressions,
4.3.
Kinds
4.4.
Exercises,69
68
Zhapter 5
Gate-levelModeling
5.1. 5.2.
5.3.
The
Built-in
Primitive
Gates,
Multiple-input Gates, 71 Gates,
Multiple-output
Gates, 75
5.4.
Tristate
5.5.
Pull Gates,77
5.6.
MOS
Switches,
77
74
70
67
Contents
5.7.
Bidirectional
5.8.
Gate
80
Switches,
80
Delays,
5.8.1. Min.typ.maxDelay
5.9.
Array
5.10.
Implicit Nets, 83
5.11.
A
5.12. A 2-to-4
5.13.
A
84
Example,
Simple
82
Form,
83
of Instances,
Decoder Example, 85
Master-slave
5.14. A Parity Circuit, 5.15.Exercises, 88
86
Example,
Flip-flop
87
Chapter 6
User-Defined
90
Primitives
a UDP,
6.1.
Defining
6.2.
Combinational
6.3.
Sequential
90 91
UDP,
UDP, 93
6.3.1. Initializingthe 6.3.2.
6.3.3. 6.3.4.
UDP, 93 UDP,
Sequential
Edge-triggered
93
Register,
94
Mixing Edge-triggered and Level-sensitiveBehavior,
95
96
6.4.
Another
6.5.
Summary of Table Entries, 96
6.6. Chapter
State
Level-sensitive Sequential
Example, 97
Exercises,
7
Dataflow
98
Modeling
7.1.
Continuous
7.2.
An Example,
7.3.
Net
7.4.
Delays, 101
7.5.
Net
Delays,
104
7.6.
Examples,
105
98
Assignment,
100
Declaration
Assignment,
101
7.6.7. Master-slaveFlip-flop, 105
7.6.2. 1.1.
Magnitude
Exercises,
106
Comparator,
106
Contents
:hapter
8
107
Behavioral Modeling
8.1.
8.2.
8.3.
8.4.
Procedural
107
Constructs,
8.1.1.
Initial Statement,
8.1.2.
Always
108 110
Statement,
One Module, 112
8.1.3.
In
Timing
Controls,
8.2.1.
Delay Control,
114
8.2.2.
Event
116
114
Control,
Edge-triggered
Event Control,
116
Level-sensitive
Event
118
8.3.1.
Sequential
8.3.2.
Parallel
119
Block,
Block, 121
Procedural
123
Assignments,
Intra-statement
8.4.1.
Control,
119
Block Statement,
125
Delay,
8.4.2. BlockingProceduralAssignment, 8.4.3.
Non-blocking
8.5.
8.6.
Case
Assignment,
130
in Case,
Don't-cares
136
Loop Statement, 136
8.7.1.
Repeat-loop
8.7.3.
While-loop
Statement, 137 138
Statement,
Statement, 139
For-loop
Procedural
Continuous
8.8.1.
137
Statement,
Forever-loop
8.7.2.
8.7.4.
8.8.
vs Procedural
133
Statement,
8.6.1.
8.7.
Assignment, 128
Procedural
8.4.4. Continuous Assignment ConditionalStatement, 131
126
Assignment,
Assign - deassign,
8.8.2. Force-
release,
8.9.
A Handshake
8.10.
Exercises,145
Example,
139
140
141
143
:hapter9
Structural Modeling 9.1.
Module,
147
147
xi
Contents
9.2.
Ports,
9.3.
Module
Instantiation,
9.3.1.
Unconnected Ports, 151
9.3.2.
Different
9.3.3.
Module Parameter
148
148
Port
151
Lengths,
152
Statement,
Defparam
9.4.
Module InstanceParameter External Ports, 155
9.5.
Examples, 158
9.6.
152
Values,
Value
Assignment,
Exercises,160
Chapter 10
161
Other Topics 10.1.
Tasks,
161
10.1.1.
Task Definition,
10.1.2. Task 10.2.
10.2.2.
Calling,
Function
167
Call,
Display Tasks, 168 Displayand Write Tasks, Strobe Tasks, 170 File I/O
Tasks, 172 and
Readingfrom
174
a File,
175
Control
Simulation
Time
Simulation
Conversion Functions, Distribution
10.4.
Disable
10.5.
Named Events,
10.6.
Mixing
Statement, Structure
180
Functions,
10.3.8.Probabilistic
xii
176
Tasks,
Timing Check Tasks, 177
10.3.6. 10.3.7.
File, 173
Timescale Tasks,
10.3.4.
172
Files,
Closing to a
out
Writing
10.3.3.
168
171
Tasks,
Opening
10.3.5.
168
Functions,
Monitor
10.3.2.
166
Definition,
SystemTasks and 10.3.1.
161
163
165
Functions,
10.2.1. Function 10.3.
153
181 Functions,
183
184 with
Behavior,
187
181
Contents
10.8.
Hierarchical Path Name, 188 Sharing Tasks and Functions, 191
10.9.
Value
10.7.
10.10. 10.11.
File,
(VCD)
Dump
Change
70.9.7.
An
10.9.2.
Format
of VCD File, 196
Specify
Block,
198
193
195
Example,
201
Strengths,
10.11.1.Drive Strength, 201
10.11.2.Charge
202
Strength,
10.12.
Race
203
Condition,
10.13. Exercises, 205 IHAFTER
11
207
Verification
11.1. 11.2.
Writing
a Test
207
Bench,
Waveform Generation, 208
11.2.1. A
11.2.2. Repetitive Patterns,
11.3.
Testbench
77.3.7.
11.4.
11.5. 11.6.
Examples,
11.7.
Zhafter
216 217
Flip-flop,
Vectors from a Text File, 219 to a Text File, 222
Reading Writing
210
216
A Decoder,
11.3.2. A
208
of Values,
Sequence
Vectors
223 SomeMoreExamples, 77.6.7.
A
Clock
11.6.2.
A
Factorial
Design,
11.6.3.
A
Sequence
Detector,
Divider,
223 225 229
Exercises, 231
12
233
Modeling Examples
12.1.
12.2.
12.3.
Modeling
Simple
Modeling
Delays,
Transport
12.4.
Elements,
233
Different Styles of Modeling, 238 240
Delays, 243
ModelingConditionalOperations, 244
xiii
Contents
12.5.
245
Shift Register, 249
12.6.
A Generic
12.7.
State
12.8.
Interacting State Machines, 253
12.9.
Modeling
12.10.
A
12.12.
Machine
250
Modeling,
a Moore
257
FSM,
Modeling a MealyFSM, 259
12.11. Appendix
Logic,
Synchronous
Modeling
Simplified
Blackjack
Program,
261
Exercises, 264
A
Syntax
A.l.
A.2. A.3.
266
Reference
Keywords, 266 Syntax
Conventions,
The Syntax,
268
268
Bibliography
285
Index
287
\342\226\241
xiv
Preface
Here is a neat and
book that explains the basics of the Verilog The description language. Verilog hardware descriptionlanguage, and referred to as Verilog HDL, can be used henceforth to model at levels the switch-level of from abstraction,ranging multiple designs
hardware commonly
digital to the
concise
algorithmic-level. The logic
including
gates
languageoffers
and user-defined
a powerful set of primitives, primitives, and a widerangeof constructs
but of hardware only the concurrentbehavior is nature and its structural The also composition. language interface (PLI). Verilog HDLis a extensible via a programming language levels to use but strong enough to model multiple of abstraction. simple language The Verilog HDL languagewas standardized IEEE in called the the 1995, by IEEE Std 1364-1995; this bookis basedon this standard. that
can
be
used
to model not
also its sequential
hardware of this book is to introducethe Verilog and basic constructs its by explaining important It a Each is primer. is described aspectof the language examples. so that it is easy to understand and not intimidating concise English
The purpose descriptionlanguage
through using
clear,
to
the reader
xv
Preface
for a
beginner. My hope is that
learning
The book provides of examplesfor
A number
model described
The
hardware.
detail.
in
described
the
using
each
provide
the very
first
step
in
sometimes
of
although
in an
is provided
Thebookis of
semantics
of the formal entire
interface,
this book.
and
construct
language
basics of the in modeling.
its usage
is provided;
in
addition,
not
styles supported by
modeling
help explain the construct.The language
of the
understanding
point of view
Verilog HDL are The book explains how stimulus and control can also be same Verilog language, including response monitoring various
The syntax
verification.
read manner,
the
can
to illustrate how collectivelyconstructscan be used to
are provided
examples
and
a thorough
the features
from
both
language,
Verilog
book
this
Verilog HDL.
of
many
the
are shown in an easy to This is done purposely to of constructs of the Verilog
constructs
not
complete.
complete
syntax
appendix for reference. in nature
theoretical
and introduces
the syntax and
than the technical jargon using common terms, rather No address has beenmadeto attempt language. for example, features such as the programming language, language in switch-level modeling, and stochastic modelingare not described
the
language
of the
definition
The book restrictsitselfto the most useful and
the language
are
that
enough
to model
features
common
of
simple as well as complexdevices.
designers as well as others, and system includingcircuit designers and software tool developers,interestedin be used as to model hardware using Verilog HDL.The bookcan also learning an introductory text in a first university course on computer-aided design, as hardware or synthesis. It is well suited for working modeling, professionals well as for undergraduate and graduate study.Designerscan use this book as a HDL and as a reference for work with way to get to know Verilog Verilog HDL. Students and professorswill find this book useful as a teaching tool for and for hardware description languages. hardware design This
is intended
book
Thebook
assumes
as familiarity
with
language
and
by
reading
simulating
and thorough
xvi
a basic
a high-level
I would
Finally,
alone.
them on
for hardware
knowledge
programming
hardware designas well language such as C.
of digital
to comment that it is impractical to learn a Typing out examples from this book and compiling
like
a Verilog simulator is the best way
understandingof the language.Onceyou
to have
gain
a complete this
mastered
Preface
book, look
at
IEEE
the
complete
Standard
on the
information
Reference Manual
Language
(LRM) for
Verilog HDL standard.
Book Organization Chapter
1 provides
a brief history
2 provides
a quick overview
of the
language,describingits
major
capabilities.
Chapter
the three main
styles
of
a design:
of describing
the
by demonstrating
language,
dataflow, behavioral,and
structural style.
It describes
language. and
the basic elements,that is, the nuts and bolts, of the comments, system tasks, compilerdirectives others. amongst
3 describes
Chapter data
types,
identifiers,
Chapter 4 is devoted also
places in the various
different
many
describes
form
an
using
built-in
time
and
An expression can be usedin to expressions. solely a Verilog description,includingdelays. The chapter that can be used to kinds of operatorsand operands
expression.
5 describes
Chapter
a design gate-level modeling,that is, modeling T he Gate are also delays explained. conceptof gates. is also introduced.
primitive delay
scaling
Verilog HDL provides that
is,
Chapter6. Combinational with
of creating user-defined primitives, capability to the built-in primitives. This is the topic of user-defined primitives are described sequential
the
in addition
primitives
and
examples.
The assignments
in
execution
modeling style is modeled using the continuous Chapter 7 describes this assignmentand
dataflow Verilog
HDL.
semantics.
Two kinds of delay, assignmentdelay
and
explains
net
delay,
its
are
described.
Chapter 8 describesthe behavioral main procedural
constructs:the
modeling statement
initial
The chapter also describes procedural blocksare parallel explainedin detail
assignments
with
examples.
It describes
style.
the two
always statement. Sequential and High-level programming
and
in
the
detail.
xvii
Preface constructssuch as conditionalstatement
and
loop
are described in
statement
this chapter. is elaborated in of modeling The structural style of hierarchy and matching of ports is examinedin this in this chapter is how modulesconnectwith each other
9. The
Chapter
concept included
chapter.
Also
via port
associations.
Advanced topics are presented in Chapter 10.Topicssuch are value change dump file, signal strengths blocks, presented. also includes tasks and functions.
as
This
specify
chapter
talk about 11 and 12 are the most practicalchapterssincethey a number of test bench examples and modeling. Chapter 11 shows a and response monitoring. Chapter 12 shows waveform generation
Chapter
verification that
show
of modeling
number Verilog
language
collective
the
demonstrate
A contains a complete syntax reference is described in Backus-Naur Form grammar
The
language.
are all
constructs
In all
arranged alphabetically for
the Verilog
words, system tasks boldface. In syntax part
that
Appendix
Finally, Verilog
examples
usage
of
constructs.
HDL descriptionsthat
and
system
functions, operators
descriptions,
syntax are in boldface.Optional
of the
easier
of
the
(BNF)and
the
search.
appear
in
this book,
reserved
and compiler directives are in and items
marks punctuation in a grammar rule
that
are
are
braces ({...}) square brackets ([...]). Non-boldcurly more times. Occasionallyellipsis(.. items that are repeated zero or identify to that used in Verilog HDL source to indicate code that is not relevant words are written in Courier font to identify its Verilog discussion. Certain its such as in rather than and meaning meaning English gate. indicated
non-bold
using
by
is
All
examples
Version
Verilog simulator,
book have
in this
been
verified
using
the
.)
VeriBest\302\256
14.0.
Acknowledgments It is individuals
who
manuscript
xviii
my
to
pleasure
offered
their
despite their
very
the assistance of the following drafts time and energy to review of
acknowledge
valuable busy
schedule.
this
Preface
1. Brett Graves,GabeMoretti
2. StephanieAlter, Takla,
and
Sriram
at VeriBest,
Smith
Doug
Johnson,
Danny
Tiao
Jenjen
and
Sanjana
Nair, Carlos
Tyagarajan at Bell
Inc. Roman, Mourad
Labs, Lucent
Inc. Technologies,
3.
Mannan
Maqsoodul
at National
This bookowesa lotto their am gratefully
I would
like
to thank
support and for providing a
Last,
sons who
but
not
me
gave
least,
lots
Thank you very
Jean Dussault stimulating
I would like of emotional
much!
and Hao Nham
work
criticism. I
and constructive
comments
detailed
to them.
indebted
Semiconductor Corp.
atmosphere
to thank wife, my without support,
for
their
and my two never
Geetha, which
continuous
Labs.
at Bell
I would
have succeeded.
J. Bhasker PA
Allentown,
February
Preface
to Second
1997
Edition
This improved
for each and every edition includes exercises chapter; course. New makes the more useful in an book hopefully university sections on tasks and functions, MOS switches,bidirectionalswitches, sharing have been and named have been added. The page format and fonts events, to to read. make the book more easier redesigned this
you have any questions, feel free to contact me through
If
please
comments or suggestionsabout my
the
book,
publisher.
J. Bhasker
January, 1999
\342\226\241
xix
1
Chapter
Introduction
This
of the Verilog HDL languageand
it's
capabilities.
major
1.1
the history
describes
chapter
is Verilog HDL?
What
is a
HDL
Verilog
a digital system at to the
level
hardware levels
many
gate-level to the
being modeledcouldvary or
system,
digital
and
hierarchically
The
switch-level. from
that
of a
in between.
anything can
timing
description language that can be of abstraction ranging from the
be explicitly
complexity
used
to model
algorithmic-
of the digital
system
simple gate to a completeelectronic
The digital system modeled
within
can the
be
described
same
description.
The
Verilog of
behavioral nature
composition,
HDL
of response
monitoring
language.
In
includes capabilities to describethe dataflow nature of a design, a design'sstructural waveform generation mechanismincludingaspects and all modeled using one single verification, language provides a programming languageinterface
language
a design, the and a delays
addition,
the
1
CHAPTER
1
Introduction
which the internals of a design can be accessed during control of a simulation run.
through
simulation
the
including
The languagenot only each
for
semantics
simulation
the
defines
language
defines very clear construct. Therefore, models written syntax
but also
in
inherits verified using a Verilogsimulator.Thelanguage language the from C constructs and of its programming operator symbols many HDL an extensive range of modeling capabilities, Verilog provides language. someof which are quite difficult to comprehend initially. However,a core to is quite easy to learn and use. This is sufficient subset of the language has sufficient The modelmost however, complete language, applications. from the most complexchipsto a complete to capture the descriptions capabilities
can be
this
electronic
1.2
system.
History
The Verilog HDL languagewas first developed by Gateway Design simulator Automation1 in 1983 as a hardware modeling languagefor their product.
of their language. Becauseof the popularity a a s usable and HDL practical gained acceptance product, Verilog the popularity of to increase language by a number of designers.In an effort in the public domain in 1990. Open the language, the languagewas placed to promote Verilog. In 1992,OVI was formed (OVI) VerilogInternational This of Verilog HDL as an IEEEstandard. decided to pursue standardization The in 1995. effort was successful and the language became an IEEE standard the Hardware Verilog Description Language complete standard is describedin Reference Manual. The standard is calledIEEEStd 1364-1995.
At
that
time
it was
a proprietary
simulator
1.3
Capabilities
Major
Listed below are the majorcapabilitiesof the Veriloghardware description
language:
1. Gateway
2
Design Automation
has
since been
acquired by
Cadence
Design
Systems.
Major Capabilities \342\200\242 Primitive
and, or
such as
gates,
logic
and
are
nand,
SECTION
1.3
built-in
into
the language. \342\200\242
of
Flexibility primitive
combinational logic
a
or
primitive
primitive.
\342\200\242 Switch-level
primitive
modeling
also built-in
are
be a
either
logic
sequential
primitive (UDP). Such a
a user-defined
creating
could
into the
gates, such
as pmos and
nmos,
language.
are provided for specifyingpin-toand delays, pin path delays timing checks of a design. \342\200\242 A design can be modeled in three different styles or in a mixed - modeled are: These behavioral style. styles style using - modeled procedural dataflow constructs; style using continuous - modeled and structural and module assignments; style \342\200\242
constructs
language
Explicit
using gate
instantiations. \342\200\242 There
data types in Verilog HDL; the net data data type. The net type representsa physical structural while a register type elements
two
are
the register connectionbetween
an abstract
data
\342\200\242 Hierarchical
can be
described, up to
level,
any
can be
design
of
size;
arbitrary
the
language
does not
limit. \342\200\242
is human
and machine
language
exchange
readable. Thus tools
between
impose a
and is an IEEE standard.
is non-proprietary
HDL
Verilog
\342\200\242 It
the
using
instantiation construct.
module \342\200\242 A
represents
element.
storage
designs
and
type
it
can
be
used
as an
and designers.
Verilog HDL languagecan be further by using language interface (PLI) mechanism. PLI is a collection of routines that allow foreign functions to access information within and allows for a Verilog module
\342\200\242 The
capabilities
designer \342\200\242 A
of the
the programming
extended
interaction
design
switch-level,
can be
with
the simulator.
described in a wide range of levels,ranging gate-level,
register-transfer-level
algorithmic-level,includingprocessand can be modeled entirely design built-in switch-level primitives.
\342\200\242 A
at
from
(RTL)
to
using
the
queuing-level. the
switch-level
3
Chapter1
Introduction
\342\200\242 The
same
can be usedto generatestimulus
language
single
specifying test constraints, design values of inputs. and for
\342\200\242
design
under test,
monitored
and
expected
values,
be \342\200\242 At
used to perform
can be
HDL
Verilog
such
that
is,
the
and in
the
for
the
specifying
responsemonitoring
the
of
of a design under test can be with values can also be compared
values
These
displayed.
as
case of a mismatch, a report messagecan
printed. the
behavioral-level,
Verilog
only at the
HDL can
RTL-level, and its algorithmic-level behavior. not
design
\342\200\242 At
the
but
gate and
structural-level,
also
be usedto describea
at the
module
architectural-level
can
instantiations
be
used. \342\200\242
Figure
shows
1-1
HDL, that
in
is,
the mixed-level one
design,
modeling capabilityof Verilog
each module
be
may
modeled
at a
different level.
switch
algorithm
switch gate \\ \\ '
\\ > \342\226\240V
RTL
Figure \342\200\242
Verilog
HDL
and) and \342\200\242
High-level case conditionals,
\342\200\242
Notion
I
also
1-1
gate
Mixed-level modeling.
has built-in
logic functions
such
as &
(bitwise-
(bitwise-or).
programming statements, of concurrency
constructs such as available in the language. and time can be explicitly modeled.
language and loops are
SECTION 1.4
Exercises
\342\200\242 Powerful \342\200\242 The
is
language
a model
example,
write capabilities are provided. non-deterministic under certain situations,that
read and
file
may produce different resultson different the ordering of events on an event queue
is not
is,
for
simulators;
defined
by the standard.
1.4
Exercises
1.
In
2.
What
3.
Can timing
4.
What
which
year
are the
was Verilog
three basic descriptionstyles be described
a design
of
feature
HDL first standardized by the
in the
by Verilog
supported
using Verilog
IEEE?
HDL?
HDL?
parameterized language can be usedto describe
designs?
a test
bench be written
5.
Can
6.
Verilog HDL was first
7.
What
are
8.
What
does
9.
Name two switch-levelmodelingprimitive
10.
Name
the
two main
UDP
stand
using
developed
Verilog by
which
HDL?
company?
data types in Verilog HDL? for?
two logic primitive
gates.
gates.
\342\226\241
5
2
Chapter
Tutorial
A
This
2.1
of the
a quick tutorial
provides
chapter
language.
A Module The
in Verilog
of description
unit
basic
the functionality or which it communicates
is the module.A
structure of a design and externally switch-level
with
also
describes
modules.
other
The
module
describes
the ports
through
structure
of a
and userprimitives, gate-level primitives of a is described dataflow behavior primitives; design using continuousassignments; is described using procedural behavior sequential constructs. A module can also be instantiated insideanother module. design
is
described
using
defined
Hereis
the
module
basic
syntax
module_name
of a
module.
( port_list
Declarations:
reg, wire, parameter,
input, output,inout,
6
)
;
A
. . .
task,
function,
2.1
Section
Module
Statements:
Initial
statement
Always
statement
Module
instantiation
Gate instantiation UDP
instantiation
Continuous
assignment
endmodule
Declarations are usedto define of the
or structure
the various items, such as registers and the Statements are used to define functionality
the module.
within
parameters, used
design. Declarationsand
can
statements
be interspersed
appear before its use. and readability it is best to put all declarations before any statements, convention is followed in all examplesin this book. within
a module;
a declaration must
however,
Here is a simple example of a shown in Figure 2-1.
module HalfAdder input
A,
B,
(A,
modulethat
Sum,
models
the
For
clarity this
and
half-adder
circuit
;
Carry)
B;
Carry;
output
Sum,
assign
#2
assign
#5 Carry
Sum
= A A B;
=
A
& B;
endmodule
A c*
B
B, and
of the
two
output
\" Sum
Al
ti Cany
(\302\273
Figure 2-1 A The name
XI
moduleis HalfAdder. ports
Sum
and
half-adder
It has
circuit.
four
ports; two
Carry. All ports
input
ports
A and
are of size 1-bitsinceno
7
Chapter
2
A Tutorial Also, range has beenspecified.
nodeclaration
been
has
sense
specified.
contains two continuous assignmentstatements are behavior of the half-adder.The statements
i.
Dataflow style
ii.
Behavioral
Hi.
Structural
iv.
mix
in
the
in the
important.
following
and
B.
styles:
style
style of above
sections describethesedesignstyles little explanationabout delays in Verilog HDL.
The following
with
But first,
examples.
a
Delays All
in
delays
Here is
#2
Sum
declaration.
An
example
of such
'timescale Ins / is to
of
time
units.
a delay.
= A A B;
The associationof a time
says
with
assignment
unit
timescale compilerdirective.Such
which
specifiedin terms
HDL model are
to 2 time units.
#2 refers
The
a Verilog
an exampleof a continuous assign
that one
time
unit
with
is
a directive
a directive
using the specified before a module time
physical
is made
is:
lOOps
is to
be treated
be lOOps(the time precisionsays
as Ins and that
the
time
precision
rounded to in the module present containing the above that
directive is 0.1ns). If this compiler continuousassignment,the#2 refersto 2ns.
8
is not
module
describe
that
concurrent
on events occurringon nets A
a designcanbedescribed
a module,
Any
the
within
occurs based
statement
each
of
of appearance
order
their
that
Within
2.2
the net data type since
are of
ports
module
The
the dataflow
Execution
four
these
all
delays
must be
If no such compilerdirective
is
certain time unit; this
to a
default
Dataflow
in
Describing
a Verilog
specified,
default time unit
SECTION 2.3
Style
HDL simulator may by the IEEE
is unspecified
Verilog HDL standard.
Dataflow
in
Describing
Style
The basic mechanism usedto modela design continuousassignment.In a continuous assignment,
net.The
assign Anytime the the
changes,
to the
the
= RHS_expression;
used in the right-hand side operand side expression is evaluated, and the value
right-hand
between to
the
after
delay.
specified
of operand on side. If no delay value
a change
left-hand
style is the is assignedto a
dataflow
a value
an
of
value
the
is:
assignment
] LHS_net
delay
f
left-hand side net
duration assignment
a continuous
of
syntax
in
the is
The delay
and
the default
specified,
assigned
specifies the time
side
right-hand
expression is
the
is zero
delay.
Here modeled
using
is an the
example
of a 2-to-4decodercircuit,shown
dataflow
style.
in
NO
An
-El
>
Abar
2-2,
Z[0]
VO
Nl
>
Bbar
B
Figure
Z[l]
Z[2]
Vt>o-
>
EN
Figure 2-2
A
2-to-4
decoder
Z[3]
circuit.
9
A
Tutorial
/ Ins
Ins
timescale
module Decoder2x4 (A, A, B,
input
[0:3]
output
B,
EN,
Z) ;
EN;
Z;
Abar, Bbar;
wire
assign #1 Abar
= ~A;
assign
#1 Bbar =
assign
#2
assign assign assign
Z[0]
= -
#2 Z[l] = #2 Z[2] = #2 Z[3] =
//
(Abar
Stmt 1
// Stmt 2
~B; &
Bbar
~ (Abar & B & - (A & Bbar & - (A & B & EW)
& EN) ;
EN) ; EN)
;
//
Stmt
//
Stmt 4
// Stmt //
;
Stmt
3
5
6
endmodule
with a backquote, is an example of The first statement, the one that begins timescale sets the time unit in a compilerdirective.The compiler directive to be Ins. For the module for all delays to be Ins and the time precision to values #1 and #2 in the continuous assignmentscorrespond example, the delay values of Ins and 2ns respectively. delay A has three The moduleDecoder2x4 port. input ports and one 4-bit output Bbar wire is one of the net net declaration declares the two wiresAbar and (a six continuous assignment the module contains types). In addition, statements.
at 5ns, statements 3, EN 2-3. When changes because EN is an operand on the right-hand 4, 5, and 6 are to its new side of each of these continuous assignments.Z[0]gets assigned value, which is 0, at time 7ns. When A changes at 15ns, statements 1, 5 and 6 of statements 5 and 6 do not affect the value of Z[0] and execute. Execution to 0 at 5 causes 17ns. Execution Z[2] Z[l]. Executionof statement change to of statement 1 causes Abar to get its new value at time 16ns. Since Abar changes,this in turn causes Z[0] to change value to 1 at time 18ns. Notice that the continuous model dataflow behavior of the assignments See
the
in Figure this is executed;
waveforms
circuit; the structureis implicit, not assignments
execute
concurrently,
explicit.
that is, they
In
addition,
continuous
are order-independent.
Describingin
Behavioral
SECTION 2.4
Style
EN
A
25
15
B
35
20 Z[0]
18
7
Z[l]
38
28
Z[2]
17
23
Z[3]
Figure 2-3 Example of
Behavioral
in
Describing
27
22
0
continuous
assignments.
Style
The behavior of a design is describedusing
constructs.
procedural
These
are:
i. ii.
This statement Always statement: This statement Initial statement:
executes always
only
once.
executes
in a
loop,
that
is executed
statement
repeatedly. Only a registerdata type can be assigned a value in either of these statements. Such a data type retains its value until a new value is assigned. All initial statements and always statements begin executionat time 0 concurrently. Here is an exampleof an always statement used to model the behavior of a is, the
1-bitfull-adder module input output
{A,
FA_Seq A,
in Figure
shown
circuit
B,
B,
Cin,
2-4. Sum, Cout)
Cin;
Sum, Cout;
11
A
Tutorial
Sum
Cout
2-4
Figure
A
1-bit
full-adder.
Sum, Cout;
reg
reg Tl,
T3;
T2,
always @
=
(A
Tl
= A
&
T2 = B T3 = A Cout
Cin) begin
B or
or
(A Sum
A
A
B)
Cin;
Cin;
&
Cin;
&
B;
= {Tl
| T3;
| T2)
end
endmodule
The
has three inputs and two outputs.Sum,Cout, Tl, T2 and to be of type reg (reg is oneof the register data types) because these are assigned values statement. The always statement within the always module
T3 are
FA_Seq
declared
block (begin-end
a sequential
has
expression following on A, B or Cin, the the
occurs
block
sequential
in
statement
A,
B,
pair) associatedwith This
character).
means
that
an
event
whenever
control
for
an
(the
an event
Statements within sequentialblockis executed. execute and the execution suspends after sequentially the sequential block has executed.After the sequential
execution, the always statement again waits
completes
on
@
event
a the
last
block
to occur
or Cin.
The statements
blocking
procedural
appear
within
assignments.
A
that
sequential block are examples of blocking procedural assignment comthe
Describingin pletes execution beforethe next statement may optionally have a delay.
forms: specified in two different Inter-statement delay: Thisis the delay
i.
Intra-statement delay: value of the right-hand
ii.
example of an
is an
example
The
delay is
expression value
to
second
= #3
Sum
by
which
a statement's
side
expression
between
and
the
computing
its assignment
to the
(A
A
delay.
Cin;
of the that the execution specifies time units. That is, after the first statement Hereis and then execute the second assignment.
statement
be delayed by 4 for 4 time units, of intra-statement
to
wait
executes, an
in the
delay
This is the delay
inter-statement
Sum = (A A B) A #4 Tl = A & Cin;
is
assignment
side.
left-hand
The
A procedural
is delayed.
execution
assignment
executes.
SECTION 2.4
Style
can be
Delays
Here
Behavioral
A
B)
delay. Cin;
in this assignment means to be computed wait first,
that
for
value of the right-hand side time 3 units, and then assign the the
Sum.
zero is the assignment, delays are specifiedin a procedural delay More on this and other forms occurs default, is, assignment instantaneously. of statementsthat can be specified in an always statement are discussed in
If no that
Chapter
Here
8.
is an
example of an initial Ins
timescale
statement.
/ Ins
module Test {Pop,Pid);
output reg
Pop,
Pid;
Pop,
Pid;
initial
begin Pop = 0; Pid
=0;
//
Stmt
//
stmt 2
1
13
Chapter 2
A
Tutorial
Pop
= #5
1;
// Stmt
Pid
= #3
1;
// Stmt 4
//
Pop =#6 0;
5
Stmt
// Stmt 6
#2 0;
Pid=
3
end
endmodule This modulegeneratesthe
in Figure 2-5. The initial waveforms shown block which starts executionat time 0ns and after it all statements within the the initial block, executing sequential completes block contains examples of This statement suspends forever. sequential with intra-statement assignments delays specified. Statements blockingprocedural 1 and 2 execute at time 0ns. The executionof the third statement, also at time a value at time 5ns. Statement 4 executesat 5ns, 0, causes Pop to get assigned contains
a sequential
Pid gets
assigned the
statement
and
and Pid statement
gets the
suspends
0
value
forever.
Chapter
the value 0 at 14ns 6 executes,the initial 8 describes initial statement in more detail. at
value
at 16ns.
8ns.
Similarly,
Pop gets
After statement
Pop
14ns
5ns
Pid
16ns
8ns
Figure 2-5
2.5
Describing
in Structural can
Structure
i.
Built-in
gate
Hi. User-defined
14
Module
Test.
Style
in Verilog HDL using: (at the gate-level) primitives
be described
ii. Switch-levelprimitives iv.
of module
Output
(at
the
transistor-level)
primitives (at the gate-level)
instances
(to create
hierarchy)
Describingin Structural are specified by
Interconnections
described in a and based on the logicdiagfam adder circuit
using nets. Hereis an in
shown
module FA_Str (A, B, input A, B, Cin; Sum, Cout; output
example
using built-in Figure 2-4.
fashion
structural
Sum,
Cin,
SECTION
Style
of
2.5
a full-
gate primitives
Cout) ;
wire SI, Tl, T2, T3;
xor A,
XI
{SI,
X2
(Sum,
SI,
and Al (T3,
B) , Cin);
B) ,
A,
A2
(T2,
B, Cin),
A3
(Tl,
A,
Cin);
or
01 (Cout,
Tl, T2, T3);
endmodule
In
this
the module
example,
xor, and, and
built-in gates
SI, Tl, T2,
T3.
and
The
is implied;
sequentially
contains gate The
or.
gate
is,
instances
of
are interconnected by nets can appear in any order since no shown; xor, and and or are being
instances
gate
instantiations
pure structure
that
instantiations,
is
XI, X2, A1, etc. are the instance names.The list of gate primitives; is the output each one signals following gate are its interconnections; the first of the gate and the rest are its inputs. For example,SI is connectedto the xor output of the gate instance XI whileA and B are connected to its inputs. A 4-bit full-adder can be described by instantiating four 1-bit full-adder the logic diagram of which is shown in Figure 2-6. The model of this modules, built-in
4-bit full-adderis shown module parameter
FourBitFA SIZE [SIZE-.l]
input
output
(FA, FB, =
FCin,
FSum,
FCout);
4 ;
FA, FB;
[SIZE-.l] FSum;
input
FCin;
input
FCout;
wire
next.
[l-.SIZE-l]
FTemp;
15
Chapter
A Tutorial
2
FA_Str FAl
FA2
.Cin(FCin),
(.A(FA[1]),
B(FB[1]),
.Sum(FSum[l
), .Cout(FTemp[l])),
(.A(FA[2]),
, .Cin(FTemp[l], .B(FB[2])
.Sum(FSum[2
) ,
)
.Cout(FTemp[2])),
FSum[3], FTemp[3]),
FTemp[2],
FA3
(FA[3]
FS[3],
FA4
(FA[4]
FCout); FS[4], FTemp[3],FSum[4],
endmodule
FB[3]
FA[3]
FB[4]
FA[4]
FB[1]
FA[1]
FB[2]
FAl
FA2r
FA3
FA4
FA[2]
FCin
FCout
FSum[4]
2-6
Figure
example, module
In this
a
module
instantiation,
first two
The
of the
name described
instantiations the form FA3
instances
and
\".
used to model a 4-bit full-adder.In associated by name or by position.
can be and
portjiame
full-adder.
4-bit
use named
FAl
port and the net to which is of
(each
instantiations,
ports FAl
A
are
instantiations
the
FSum[l]
FSum[2]
FSum[3]
is
it
connected
( netjiame)\.")
FA4, associate
ports
associations, that is, to are explicitly The last two
with
The order of the associationsis important instance FA4, the first one FA[4] is connected to port A one FB[4] is connectedto port B of FA_Str, and so on. association.
2.6
is, a
instantiations,
16
using
positional
here,
for
in example, the second
of
FAJStr,
and behavioral constructs can bemixedfreely, structural can contain a mixture of gate instantiations, module and and initial statements, amongst always assignments,
a module,
Within
nets
in Mixed-design Style
Describing that
the
module
continuous
others. Values from
assigneda value
gates or switches, while values drive
only
can
in turn
example
of a
nets)
statements (remember only can drive these statements)
and initial
statements
always
can be
data type
a register
from
within
assignments (can
or continuous
gates
be used to
SECTION 2.7
a Design
Simulating
trigger always
and
statements
initial
statements.
Here is an module
(A, B,
FA_Mix
input
A, B,
Cin;
Sum,
Cout;
output
1-bit full-adder in
reg
Cout;
reg
Tl, T2, T3;
Cin,
a mixed-designstyle.
Cout)
Sum,
;
wire SI;
xoi
XI
instantiation.
II Gate
B) ;
A,
(SI,
always @
//
B or Cin) begin - A & Cin; T2 = B & Cin; T3 = A & S; = (Tl | T2) | T3; Cout (A or
statement.
Always
Tl
end
assign
A
= SI
Sum
II Continuous
Cin;
endmodule
Executionof or
B.
The
always
the
gate
instantiation
occurs
whenever
statement executes whenever there
Cin, and the continuousassignmentexecuteswhenever
assignment.
an event
is an there
event
is an
occurs on A on A, B or event on SI
or Cin.
1.1
Simulating a Design HDL
Verilog
model
provides
control, storing
stimulus,
language. Stimulusand Responses
from
capabilities
the
design
control
under
not only
responses
and
can
be generated
test can
be saved
to describea designbut verification,
all using
also
to
the same
using initial statements. as \"save on change\" or as
17
A
Tutorial
strobed
can be performedby
Finally, verification responses by expected
data.
with comparing
automatically
in an initial
statements
appropriate
writing
statement.
Here is an described
test module 2.3.
of a
example
in Section
earlier
wire
the
tests
module
FA_Seq
Ins/Ins
timescale
module Top;
reg
Top that
list.
an empty port
PCi;
PB,
PA,
may have
module
//A
PCo, PSum;
module under test:
II Instantiate Fl
FA_Seq
PB,
(PA,
II Positional.
PSum, PCo);
PCi,
initial
begin:
ONLY_ONCE
[3:0]
reg
Pal;
II Need 4
bits so that
(Pal = 0; Pal < begin
for
{PA,
PB,
Pal
have
can
Pal
= Pal
PB,
PCi=%b%b%b\",
8;
value
the
8.
+ 1)
= Pal;
PCi)
#5 $display
(\"PA, \"
:::
PCo,
PA, PB,
PSum=%b%b\", PCo,
PCi,
PSum);
end end endmodule The signals in the module instantiation are linked to the ports of the module under test using positional association,that is, PA is connected to port A of module and so on. FA_Seq, PB is connected to port B of moduleFAJSeq, Notice that a for-loop statement has been used in the initial statement to generate a waveform on PA, the for-loop
The target of the first assignment statement a The concatenated bits on represents target. appropriate the right-hand side are assignedto the left-hand side from right to argument left. The initial statement also contains an example of a predefinedsystem task. The in the values Sdisplay system task prints the specified argument to the format specified output. PB
and
PCi.
within
The
delay
control
in the
Sdisplay system task
after play taskis to be executed
5 time
units.
call
This 5
specifies
that the
$dis-
time units basicallyrepre-
SECTION 2.7
a Design
Simulating
sents the settling time for the logic, that is, the delay time between the of a vector and observing the module-under-test'sresponse. application
Thereis the
yet
statement has to block label is not the
be labeled.ONLYjONCE if there
necessary
Figure 2-7 shows the test module.
block.
produced
nuance to this model. Pal is declaredlocally in To do this, the sequentialblock(begin-end)
another
statement.
initial
by
PA, PA,
PB,
PCi
PB,
PCi
the
:
=000 =001
:
PB,
PA,
=100:
Here
produced.
PCo,
PSum
=00
PCo,
PSum
=01
PA PB, PCi =010: PCo, PSum :; PCo, PSum PB, PCi =011 PA PCi
PSum
PCo,
in
case.
this
variables declared locally
are no
waveforms
label
block
the
is
within
the
is the
initial The within
output
=01 =10
=01
PA PB, PCi =101 : PCo, PSum =10 PB,
PA,
PCi
=110::
PA, PB, PCi =111:
PCo,
PSum
=10
PCo,
PSum
=11
PCi
0
5ns
10ns
15ns
20ns
30ns
25ns
35ns
PB
PA
PSum
PCo
Figure 2-7 nand
Waveforms
produced
by executing
Hereis anotherexampleof a testmodulethat in Figure 2-8. gate module RS_FF shown
test bench
exercises
the
Top. cross-coupled
19
Chapter 2
A
Tutorial
Q
Qbar
2-8 Cross-couplednand
Figure
gates.
\"timescale10ns/Ins module
R, S) ;
Qbar,
(Q,
RS_FF
output Q, Qbar;
input
R,
#1
nand
5;
(Q, R, Qbar)-,
nand #1 (Qbar, S, Instance
II
Q)
;
names are
optional
module
under test:
in gate instantiations.
endmodule
module
Test;
reg
TS, TR;
wire TQ, TQb; II
Instantiate
RSJFF NSTA (.Q(TQ) II Using named //
Apply
stimulus:
initial
begin TR
= 0 ;
TS = 0 ;
#5 TS = #5
TS
TR = #5
TS
1;
= 0;
1; = 1;
TR = 0 ;
#5 TS= 0; #5
end
20
TR
= 1;
,
.S(TS)
association.
,
.R(TR)
, .Qbar(TQb));
Simulating a Design
//
Section2.7
output:
Display
initial
$monitor \"
$time,
TQ=%b,
TS=%b,
TR=%b,
\"
%t,
time
(\"At
TQ, TQb)
TS,
TR,
TQb=%b\",
endmodule
Module RS_FF
describesthe structure
in gate instantiations;
for
time unit. This gate delayimpliesthat T+l. Q gets the computed value at time The
the waveform on procedural
task
the test module. The design under test RS_FF is are connected using named association. Therearetwo in this module. The first initial statement simply generates TS and TR. This initial statement contains blocking
its ports
statements
initial
inter-statement
with
assignments
The second initial statement when called causes the
occurs in the specifiedvariables waveforms
the effect
if R
Test is
module and
instantiated
the design. Gate delays are used is 1 delay for the first instantiation or Qbar changes at say time T, then of
the gate
example,
Here
produced.
by the
produced
delays.
specifiedstring the
in
the systemtask
to call
is used
be
to
argument
is the output produced timescale directive
This
Smonitor.
a change
whenever list. Figure 2-9 shows the by the test module. Notice
printed
on the delays.
TR
250 TS
TQ
200
J
\302\261
10ns TQb
150
100
50
x
120
J
0ns Figure
60
2-9
At time At
260ns
W 0
time
At time
Waveforms
210
170
HO
produced
by module
Test.
0, TR=0, TS=0,TQ=x, TQb=x
10,TR=0, TS=0,TQ=l,TQb=l
50,
TR=Q
15=1.
TQ=1.
TQb=l
21
Chapter 2
A
Tutorial
At time
60, TR=0,
At time
100, TR=1. TS=0,TQ=l,TQb=0
110,
time
At
TQ=0, TQb=l
TR=1, TS=0,
120,
At time
150,TR=0,
TQb=l
TQ=0,
TS=l,
160, TR=0, TS=l. TQ=l, TQb=l
time
At
TQ=l,TQb=l
TR=1,TS=0,
At time
TQb=0
TQ=l,
TS=l,
At time
170,
At time
200, TR=0, TS=0,TQ=l.TQb=0
TR=0,
210,
time
At
TR=0,
TQb=0
TQ=l,
TS=l,
TQb=l
TQ=l.
TS=0,
At time
250, TR=1, TS=0,TQ=l,TQb=l
At time
260,
TR=1,
chapters elaborateon thesetopicsand
The following
TQb=l
TQ=0,
TS=0,
more
in greater
detail.
2.8
Exercises
1.
What
statement
2.
What
is the
is used
a design in the dataflow
to describe
style?
purpose of the \"timescalecompilerdirective?
an
Give
example.
3.
What
are the
two kinds of delays that
statement?
assignment
Elaborate
4. Describethe 1-bitfull-adder 5.
What
is the
using shown
can
be
specified
in a
procedural
an example. in Figure
key differencebetween an
2-4 using
the dataflow
statement
initial
and
style.
an always
statement?
6. Generatethe
waveform
following
on a
variable BullsEye using an initial
statement.
0
Figure
22
12
2 3
2-10
A
waveform
22 on variable
24
27
BullsEye.
32
Exercises 7.
a model, in
Write
structural style, for
the
shown
decoder
2-to-4
2.8
SECTION
in
Figure
2-2.
8.
described bench to test the moduleDecoder2x4
a test
Write
in
Section
2.3.
9.
Name two kinds of assignmentstatements
that
you
can have
in
a Verilog
model.
HDL
in 10. When is a label requiredto be specified
the
11. Using following
dataflow
style,
description
logic. Use
exclusive-or
write
block?
a sequential
a Verilog
HDL model for
the
the specifieddelays.
5ns
4ns
ft Ins
5ns
B
Figure 2-11 12.
What
is wrong
assign
with
the
Reset =
#2
following A
Exclusive-or
continuous
logic.
assignment?
WriteBus;
23
3
Chapter
Elements
Language
This
comments,
identifiers,
In
functions.
3.1
elements of Verilog HDL. It introduces numbers, directives, system tasks and system compiler it introduces the two data types in the language. the basic
describes
chapter
addition,
Identifiers An
in Verilog
identifier
the
character,
and
character
must
sensitive.
be
Here
_ (underscore) a letter or
HDL is any
sequence of letters, digits, the $
character, with an underscore.
the
restriction
Count
COUNT
_R2_D2 R56_68
FIVE$
24
that the
In addition, identifiers are some examplesof identifiers.
II
Distinct
from Count.
first
are
case-
Section
Comments
An
ASCII characters
identifier.
an
in
and
character
(backslash)
provides
identifier
escaped
ends
with a
newline).Hereare some
a way of including An escaped identifier
white space (a white of
examples
any
starts
space
the
of
is a
with
3.2
printable a \\
space, tab
or a
identifiers.
escaped
\\7400
\\~Q
The last exampleexplainsthe the
and
escaped identifier, the backslash of the identifier. Thus, identifier space part to identifier OutGate.
is identical
Verilog HDL defines can in
be used
only the language.
in
Note identifier
ALWAYS
3.2
Note
identifiers, called keywords,that A lists all the reservedwords Appendix
of reserved
that
only
lower
the (which
always
is a
are reservedwords. is distinct from the keyword)
case keywords
a keyword).
is not treated the same as the keyword. keyword is a is distinct from the identifier initial (which this convention is different from those of escaped identifiers. escaped
\\initial
identifier
keyword).
in an
that,
contexts.
is not
(which
In addition, an Thus,
list
a
certain
Forexample, identifier
fact
are not
terminating
\\OutGate
OutGate
as
same
is
\\OutGate
that
Comments
There aretwo
forms
in Verilog
of comments
HDL.
/* First form:Can extend
across
many
lines
*/
// Second form: Ends
at
the
end of
this line.
25
Chapter3
3.3
Elements
Language
Format That is, Verilog HDL is case-sensitive. case are distinct.In addition, HDL Verilog
may be tab, and that
across
written
lines,
multiple
space characters)
no
have
differing is free-format, that
or on
special
only in their
identifiers
one line. White
is,
constructs (newline,
space
Here is an
significance.
example
this.
illustrates
initial
Top = 3'bOOl;
begin
#2
Top
= 3'bOll;
end
is same as:
initial
begin Top
= 3'bOOl;
#2 Top
= 3'bOll;
end
3.4
System Tasks and An
or as a
identifier
Functions with
beginning
systemfunction.A
task
a $
character is interpreted a mechanism
provides
as
a system
task
to encapsulate a
from different parts of a design. A task can return zero is like a task except that it can or more values.A function return only one a function executes in zero time, that is, no delays are allowed, value. In addition, behaviorthat
can
whilea task
be invoked
can
have
delays.
(\"Hi, you have reached LT today\") $display /* The $display system task displays the to with a newline character. */ output
;
specified
message
$time
// This
system
Tasksand functions
26
function
are
described
returns
the
in Chapter
current
10.
simulation
time.
CompilerDirectives
\\.5
3.5
SECTION
Directives
Compiler
Certain identifiers that
directives. A
(backquote) character when compiled, remains in effect
directive,
compiler
*
the
with
start
process (which couldspan
entire compilation
compiler directive specifiesotherwise.
Here
is
a different
list of
a complete
the
through
until
files)
multiple
are compiler
standard
compilerdirectives. \342\200\242
\"undef
\"define,
\342\200\242
\"endif
\"else,
\"ifdef,
\342\200\242
\"default_nettype
\342\200\242 \"include \342\200\242 \"resetall \342\200\242 \"timescale \342\200\242
\"nounconnected_drive
\"unconnected_drive,
\342\200\242
\"endcelldefine
\"celldefine,
$.5.1
vdefine
and \"undef
The \"define
C programminglanguage.Hereis an
\"define
Once the the
compilation. many different
the definition
For example the
files with
the
\"define
WORD
wire
\"undef
[
\"WORD
16
:
//
Creates
stays in
effect
usage of MAX_BUS_SIZE
in another
directive
The \"undef directiveremovesthe definition macro. Hereis an example.
\"define
example
much
of this
the
like
directive.
AddReg;
1:0]
is compiled,
directive
\"define
entire
across
-
MAX_BUS_SIZE
[
and is very
32
MAX_BUS_SIZE
\"
reg
for text substitution
is used
directive
#define in the
a macro
of
a previously
through could
be
file. defined
text
for text substitution.
1 ] Bus;
WORD
27
Chapter
3
Language Elements
// The definition // after this 3.5.2
is
WORD
no longer
available
directive.
\"endif
\"else and
\"ifdef,
of \"undef
Thesecompiler
for conditional
used
are
directives
compilation. Here
is an
example.
WINDOWS
\"ifdef
parameter
WORD_SIZE
=16;
WORD_SIZE
= 32;
\"else
parameter \"endif
if the text macroname WINDOWS
During compilation, parameter
is selected,
declaration
otherwise
the second
selected. The
3.5.3
is optional
directive
\"else
the
with
Mfdef
is defined,
the first
parameter declarationis
directive.
\"default_nettype
This directive that is, for nets that
is
to specify not declared.
used are
\"default_nettype
the net
type
for
net
implicit
declarations,
wand
This example specifiesthe default if a net to be a wand net. Therefore, type net is not declared in any module following this directive,the net is assumed
to be a wand
3.5.4
net.
\"include
The \"include compiler directivecan beusedto include file in-line. The file can be specified either with a relative full path name. x
include
28
\"../..
/primitives.v\"
the
path
contents
of any
name or
with
a
Compiler Directives
is replacedwith
this line
compilation,
Upon
of the
contents
the
3.5
SECTION
file \"../../prim-
itives.v\".
\"resetall This compilerdirective
to their default
directives
all compiler
resets
value.
'resetall
For example, this
directive causesthe default
net
type
to be
wire.
'timescale In a Verilog
HDL
model,
The association of time units
compilerdirective.This precision.
actual
with
is used
directive
is of
directive
The
are expressed
all delays
time
is done
to specify
units.
of time
terms
in
using the 'timescale
the time
time
and
unit
the form:
'timescale time_un.it/ time__precision where
the
100 and units
from s, ms,us,ns, ps and
directive
unit of
a time
outside
appears
that follow
it. Hereis an Ins
'timescale
module AndFunc
and
//
and
Ins and a time precisionof lOOps. of a module declaration and affects
\"timescale
The all
delay
values
example.
/ 10Ops (Z,
A,
B) ;
Z;
output
input
1,10,
Ins / 10Ops
'timescale indicates
is made up of values from fs. Here is an example.
and time_precision
timejunit
A,
#(5.22,
Rise
B;
6.17)
and fall
Al (Z,
A,
B)
;
delay specified.
endmodule
29
Elements
Language
specifies all delays to be in ns and delays are rounded to one5.2ns and the 5.22 becomes (lOOps). Therefore, the delay value 6.17 becomes 6.2ns. If instead the following timescale directive the above module,
The directive of
tenth
a ns
delay
value
is used
in
\"timescale 10ns / Ins becomes
5.22
then
52ns,
The \"timescale directive in
directive directive
is
having
place appropriately
What
its
if there
happens
\"timescale
own
all
affects
until another
a compilation
found.
becomes 62ns.
and 6.17
in modules
delays
is morethan
scaled
to this
'timescale
Ins
module AndFunc input
/ lOOps (Z,
B) ;
A,
B;
A,
Al (Z,
6.17)
and #(5.22, endmodule
10ns /
'timescale
A,
B)
Ins
module TB; PutB;
Put A,
reg
wire GetO;
initial
begin PutA
= 0;
PutB
= 0;
#5.21 PutB =
#10.4
PutA
#15 PutB
1;
= 1;
= 0;
end AndFunc
endmodule
AF1
in a
module
In such a case, simulation of precision all the modulesand smallest time precision. Hereis an
Z;
output
one
directive?
smallest time
in the
follow
that
(GetO,
PutA,
this
\"timescale directive or \"resetall
PutB);
;
design each
always all
delays
example.
takes
are
CompilerDirectives
SECTION
3.5
directive. The \"timescale example, each modulehas its own timescale to the delays. Therefore in the first module, directive is first applied 5.22 is in 6.17is a nd is the second 5.21 10.4is 6.2ns, 5.2ns, module, 104ns,and 52ns, If module TB were simulated,the smallesttimeprecision 15 is 150ns. of all in this design is lOOps.Therefore,all delays modules in the delays (especially module TB) will be scaledto a precisionof lOOps. 52ns now becomes Delay and 150ns becomes 520*100ps, 104ns becomes 1040*100ps, 1500*100ps. More importantly, simulation occursusing a time precisionof lOOps. If were simulated, module AndFunc the \"timescale directive of moduleTB has no TB is not a child moduleof moduleAndFunc. effect since module In this
3.5.7
and
\"unconnected_drive
Any
these
unconnected
ports
input
two directives
\"nounconnected_drive in module
instantiations
are either pulledup or pulled
that
appear
between
down.
\"
pulll
uncoxmected_drive
/* All unconnected input are pulled up (connected
ports betweenthese two to 1) . */
directives
*nouncoxmected_drive
\"
pullO
unconnected_drive
unconnected
/* All are
pulled
input ports betweenthese two to 0) . */
directives
down (connected
*nouncoxmected_drive
3.5.8
and
'celldefine
'endcelldefine
These two directivesare used to mark typically encompassa moduledefinition,
a module as
shown
as a in the
cell module. They
following example.
x
celldefine
module
FD1S3AX
{D, CK,
Z)
;
endmodule
*endcelldef
ine
31
Language Elements
Chapter 3
Cellmodulesare
used
3.6
some
by
PLI routines.
Set
Value
the following
has
HDL
Verilog
four basic values,
i. 0 : logic-0orfalse 1:
ii.
logic-1
Hi. x: z:
iv.
or true
unknown
high-impedance
of these four values are built-in Note that the interpretations a 0 always A z in a value always means a high-impedance, and so on.
x.
input
of
same as 0X1Z.A
constant
the
means
language. a logic-0,
an expression is usually interpreted as z are case-insensitive,that is, the value in Verilog HDL is made up of the above
or x and
a gate
the values
Furthermore,
Oxlz is
in
values.
basic
four
at the
z value
A an
into
There are
three types of constants
i*.
Integer
ii.
Real
in
Verilog
HDL.
Hi. String An
underscore
freely;
they
readability;
are the
(_)
character
can be
used in
an
in the number itself. They ignored restriction is that the underscore only
or a real constant can be usedto improve character cannot be the
integer
character.
3.6.1
Integers
An integer
32
number can be written decimal
i*.
Simple
ii.
Base format
in
the
following
two forms,
first
Value
Decimal
Simple An
+
(unary) or a
specified as a sequenceof digits
form is
Here
operator.
(unary)
are some
examples of
an optional
integersin
the
is decimal 32
32
- 15
is
-15
decimal
An integer value in this form represents a in two's complement form. is represented
010000
with
form.
decimal
simple
Form
in this
integer
3.6
SECTION
Set
binary; -15 is 10001in
in 6-bit
signednumber.A negative Thus 32 is 10000in a 5-bit
5-bit
binary,
and is
number
binary,
110001 in a
6-bit
binary.
Notation
Format
Base
of an
The format
[ size
]
in this
integer
'base
form is:
value
in number of bits, base is one specifies the size of the constant or B d b or D (for binary), (for octal), (for decimal),h or H (for and value is a sequence of digits that from the base. The are values hexadecimal) values x and z and the hexadecimalvalues a through f are case-insensitive.
where
the size
of oorO
Here are
some examples.
5'037
5-bit octal
4'D2
4-bit
decimal
4'Blx_01
4-bit
binary
7-bit
x (x z (z
7
'Hx
4-bit
4'hZ
Not
4'd-4 8
'h
3' (2+3)
2A
bOOl
'dlO
legal: Spaces are and
between
Not
legal:
Not
legal;
extended) , that is, xxxxxxx extended) , that is, zzzz value cannot be negative
allowed between size and ' character base and value no space allowed between ' and base b size cannot be an expression
33
3
Elements
Language
(or z)
z) in a hexadecimalvalue represents three bits of x (or z), and x represents
an x (or
that
Note
octal
in
four
(or z), x represents
bits of x
(or z) in binary
one bit of x (or z). in base format notation is always an unsigned number. The size of in this form. If no is is an size specifiedin an specification optional integer of bits specified in the value. the size of the number is the number integer, Here are some examples. A
number
'o721
9-bit octal
'hAF
8-bit
If the
hex
size specifiedis largerthan
number is padded is a x or a z, in
the
to
specified
O's except for or a z respectively
left with a x
case
which
size
the
the
case
is used
for the constant, the where the leftmost bit to pad
to the left. For
example,
10'blO If
size
the
the
0 to
with
Padded
left,
Padded with x to the left,
10'bxOxl
specified
is smaller,
the
then
leftmost
0000000010 xxxxxxxOxl
bits
are appropriately
truncated. For example,
3'bl001_0011
is
5'HOFFF
is same
The ?charactercanbeused be used
to
improve
readability
value (see
don't-care
as
3'bOll
as
same
as 5'HIF for value z in a number. where the value z is interpreted
an alternate
in cases
Chapter 8).
Reals A
real
number
can be
i. Decimalnotation: 2.0
5.678
11572.12
0.1
specified
in
Examples
one
following two forms. in this form are: numbers
of the of
It may as
a
// Not legal: // on either
2.
ii.
notation:
Scientific
side of decimal.
360.0
3.6E2
of numbers
Examples
(e
this
are:
form
as E)
same
is
0.0005
5E-4
Implicit conversionto integeris defined are converted to integersby rounding to the
by
the
to integer
-26.22
gives
Real numbers
language.
nearest integer.
to integer 42.446, 42.45 when converted 92.699 93 when converted 92.5, yield -15.62 to integer gives -16
3
in
23510.0; underscores are ignored
The value
23_5.1e2
3.6
a digit
have
must
SECTION
Set
Value
yields into
42
integer
-26
Strings
a sequenceof characterswithin of split acrosslines.Here are examples
A string is
not be
double
quotes.
A string
may
strings.
ERROR\"
\"INTERNAL
\"REACHED->HERE\"
A character unsigned
is represented by
ASCII
value
which is
treated as an
To Therefore a string is a sequenceof 8-bit ASCIIvalues. \"INTERNAL ERROR\", a variable of size 8*14is needed.
integer.
the string
reg
[
1
Message The
8-bit
an
8*14
:
=
] Message;
\"INTERNAL
character
\\ (backslash)
store
ERROR\";
can be
used to escapecertain
special
characters.
\\n
newline
\\t
tab
\\\\
the
\\
character character
itself
35
Chapter 3
3.7
Language Elements \"
\\\"
the
\\206
character
character
with
octal
value 206
of data
types.
Data types two groups
has
HDL
Verilog
i. Net type: A
net
typo, represents
as a continuous to
connected
ii.
gate
of
value
output.
defaults to a value
of
value is savedfrom one has a default value of x.
and its type
register
z.
element.It is
assignment
are
the
different
kinds of
nets that
belong
to the
net data
\342\200\242
wire
\342\200\242 tri \342\200\242 wor \342\200\242
trior
\342\200\242 wand \342\200\242 triand \342\200\242
trireg
\342\200\242 tril \342\200\242
triO
\342\200\242
supplyO
\342\200\242
1
supply
A simple
syntax for
net_kind
36
driver is
or
an
to the
Net Types Here
[
a net declarationis: msb
: lsb
] net!,
net2 ,
. . .
such
drivers
its
If no
an abstract data storage represents within an always statement only
values
statement,
3.7.1
assignmentor a
the net
type
register
assigned
A
connection betweenstructural from the
type:
Register A
a net,
a physical
is determined
value
Its
elements.
, netN;
type.
initial
next.
Data
is one of the
where net_kind that
expressions
of the
the range
specify
range is specified,a net defaults
if no
wire Rdy, Start; wand [2:0] Addr; The various for a
net,
that
is,
wor
In this
Isb are constant
is optional; net; the rangespecification a size of one bit. Here are some
II
Two
1-bit
//
Addr
is
wire a 3-bit
nets. vector
wand
one exists more than driver nets behave differently when there when there are multiple assignments to a net. Forexample,
assign
i?de = Bit
&
Wyl;
assign
i?de = Kbl
\\
Kip;
Rde has two drivers,onefrom a wor net, the effective value
it is
Since
of the
each
of Rde
continuous
is determined
wor (see following section on wor nets) using the values side (the values of the right-hand expressions).
table
Wire
and
net
used to special
of
the
a
from
drivers
Tri Nets
This is the mostcommontype wire
net.
i?de;
example,
assignments.
to
msb and
3.7
declarations.
net
of
examples
above,
listed
nets
SECTION
Types
and a
tri
are
net
identical
net
of
is used to connectelements. A and semantics; the tri net may be a net, and has no other drive
which
in syntax
describe a net where multiple
drivers
significance.
Reset;
wire
[3:2] Cla,
wire
tri
[MSB-1
:
Pla, Sla;
LSB+1]
Art;
drivers drive a wire is determined by using the following
(or a
If multiple
tri) net, the
value
effective
of the
net
table.
wire (or tri)
0
1
x
z
0
0
x
x
0
37
Elements
Language
wire (or tri)
0
1
x
z
1
x
1
x
1
X
X
X
X
X
z
0
1
x
z
an example.
Here is
assign Cla
Cla =
assign In this
example,
of the determine evaluated
side
an
z index into
and
Wor
A
Sla;
is used
Since Cla is a vector,eachbit
of Cla.
if the
example,
secondright-hand
(the first bits 1 and 1 index into an
first
right-hand
side
is xlx
the tableto give
of the two drivers (the values to index in the above table to
values
The
drivers.
expressions)
of Cla
second
x, the
Pla
For
independently.
the value Olxand the value
& Sla;
value
effective
effective
Pla
Cla has two
right-hand
the
=
expression 0 and 1 index
bits the
table
to give
position
is
has side expression has the value Hz, the
into the table to give a 1, the third bits x and
x).
Trior Nets
This is a wired-ornet, is also a 1. Both
the net
is, if any
that
and
wor
trior
one of the drivers is nets are identical in
a 1,the
value
functionality.
wor
[MSB
trior
: LSB]
If multiple drivers determined
by
using
Art;
: MIN-1]
[MAX-1
drive
the following
wor (or trior) 0
this
Rdx,
Sdx, Bdx;
net,
the effective
value of the net
table.
0
1
0
1x0
x
on
their syntax and
z
is
Data
wor (or trior)
and
Wand
SECTION
Types
0
1
X
z
1
1
1
1
1
X
X
1
X
X
z
0
1
X
z
3.7
Nets
Triand
This net is a wired-and is a 0. Both wand
net,
the net
that
triand
and
the is, if any of the drivers is a nets are identical in their syntax
0,
value
of
and
functionality.
wand
Dbus;
[-7:0]
triand
Clk;
Reset,
If multiple drivers drive determine
the
effective
a wand
following table
is usedto
0
1
X
z
0
0
0
0
0
1
0
1
X
1
X
0
X
X
X
z
0
1
X
z
wand (or triand)
THreg
net, the
value.
Net
This net stores a value
(like
a register)
node.
and is
used to modela capacitive
all drivers When to a trireg net are at high-impedance, that is, have the value z, the trireg net retainsthe last value on the net. In addition, the default value for a trireg net is an x. initial
trireg
[1:8]
Dbus,
Abus;
39
Chapter 3
Elements
Language
Nets
Tril
and
TriO
These nets alsomodelwired-logic nets, characteristicof a triO particular this net, its value is 0 (1 for tril). driving driver. The
The
has
[-3:3]
tril
[0:-5] OtBus, ItBus;
than
(tril)
the effective
value for
a triO
and
(tril)
0
1
X
z
0
0
X
X
0
1
X
1
X
1
X
X
X
X
X
z
0
1
X
0(1)
than
one
no driver
is
or a tril
net
value 0,
and the
that
Nets
Supplyl
The supplyO net is used to modelground,
supplyl net is usedto modela power
3.7.2
more
with
is that if
net
one driver.
triO
SupplyO
shows
table
following
a net
is,
GndBus;
triO
more
that
net,
that is,
that
is,
the
the value
1.
ClkGnd;
supplyO
Gnd,
supplyl
[2:0]
Vcc;
Undeclared Nets In
it is
HDL,
Verilog
possible not to
declarea net.In
such
a case,
the net
defaults to a 1-bitwire net. This
net
implicit
compiler
xdefault_nettype
declaration directive.
can be changed It is of the form:
\"
net_Jcind
de\302\243ault_nettype
For example,
40
with
the
compiler
directive:
by using
the
Data Types \"
wand
default_nettype
net defaults to a
any undeclared
.3
1-bitwand
The keywords,scalared or vectored, vector net. If a net is declaredwith the
part-selectsof this has to be assigned chapter). Here
is an
net
vector
(bit-selects
Bit-select
wor
and part-select
Grb[3:2]
allowed.
[4:0]
Best;
as:
wor [4:0]
Best;
part-select
Best[3:1]
are allowed.
If no such keyword
.4
for a
Grb;
// Bit-select Best[2] and //
be specified
then bit-selects and vectored, keyword allowed; in other words, the entire net and part-selects are describedin the next
Grb[2]
scalared
11 Same //
NOT
optionally
of such a declaration.
example
// are
can
are not
wire vectored [3:1] II
net.
Nets
Scalared
and
Vectored
3.7
SECTION
is
specified,
then the
default is scalared.
Register Types There
five
are
different
kinds of
register types.
\342\200\242
reg
\342\200\242
integer
\342\200\242 time \342\200\242 real \342\200\242 realtime
Reg
Register
The reg kind of registerdata type is the one most commonly used. A which is of the form: declared by using a reg declaration,
reg
is
41
Language Elements
reg
, reg2 ,
] regl
is optional; if no range specification register. Here are someexamples.
[1:32]
reg A an
size.
in a
be of any
can
register
1-bit
A
A
value
a 4-bit
is
Sat
// Kisp, Pisp, Lisp;
The
expressions.
is specified,
range
//
reg [3:0]Sat; reg Cnt;
. . . , regN;
the range and are constant-valued
lsb specify
and
msb
where
: lsb
msb
[
to
defaults
it
a 1-bit
register.
register.
interpretedas
is always
register
number.
unsigned
Comb;
[1:4]
reg
= -2;
Comb
Comb =5;
II
Comb has
//
Comb
two's
14 (1110), the 5
has
of
complement
2.
.
(0101)
Memories A
is an
memory
array of
registers. It is declaredusing
declaration
a reg
of
the form:
reg
[
: lsb
msb
] memoryl memory2
Hereis
example
of a
reg [0:3]
MyMem
an
//
is
MyMem
and
MyMem
Bog
Bog
is
no
such A
memories.
of sixty-four of five
are memories.
Arrays
a memory
equivalent
for the
reg
declaration
single
: lower2
. .
], .
;
[0:63];
an array
an array
not allowed.Noticethat
: lowerl ],
[upper2
declaration.
memory
reg Bog[l:5];
//
[upperl
4-bit registers.
1-bit registers. with
belongs
more
two
than
to the register
dimensions
net data type. can be
used to declareboth
are
data type. Thereis
registers
and
Data
parameter ADDR_SIZE reg [ 1: WORD_SIZE]
RamPar is a memory, bit
an
, DataReg;
8-bit registers, while DataRegis a 8-
of sixteen
array
: 0]
[ADDR_SIZE-1
register.
of caution in but a assignment,
A word in
WORD_SIZE = 8;
=16, RamPar
SECTION 3.7
Types
one
for a memory when it is following assignment,
cannot be
A memory
assignments.
register can. Thereforean
reg [1:5]Dig; //
Dig
is
a 5-bit
assigned a value to be
specified
difference. In the
Let's look at this
assigned.
being
needs
index
register.
Dig = 5'bll011;
is okay,
but
the
following
assignment:
//
[1:5];
reg Bog
Bog
is
a memory
of five
1-bit registers.
Bog=5'bll011;
isnot.
One
memory
way
to assign For
individually.
reg
[0:3]
to a
memory is to assign a value
to
each
word
of a
example,
[1:4];
Xrom
= 4'hA;
Xrom[l]
Xrom[2] = 4'h8;
Xrom[3]
=
Xrom[4]
= 4'h2;
4'hF;
to assign values
An alternate way
tasks:
These
i.
$readmemb
ii.
$readmemh
system
The text
tasks
file must
(loads
read contain
hexadecimal. Hereis
an
binary
to
a memory
is by using
values)
(loads hexadecimalvalues) and load data from a specifiedtext file the
appropriate
the system
form
of numbers,
into
a memory.
either binary or
example.
43
Elements
Language
reg [1:4]
RomB is a may
may be in
RomB);
(\"ram.patt\", file
The
memory.
must contain binary values. The file of what and comments.Hereis an example
\"ram.patt\"
white spaces
contain
also
[7:1];
RomB
$readmenb
the file.
1101
1100
1000
0111 0000
1001
0011
The
system
index
7, the
from task $readmemb causesthe values to be read in starting a part of the memory is to be word index of RomB.If only can be explicitly range specified in the $readmemb task, such as:
leftmost
loaded,
the
RomB,
(\"ram.patt\",
$readmemb
5,
3);
case only RomB[5],RomB[4],and RomB[3] words at the The and values readare 1100 1101, beginning top.
in which file
file may
The
also contain explicitaddressesof the
When index
bound
@5
11001
11010
case the values are read into only
//
value is
a start
of the
$readmemb
form:
example:
@2
in which
from the
1000.
value
@hex_address
such as in this
are read
memory
specified
of the
addresses
specified, readcontinuesuntil
the
RomB,
from address
6
6); and
continues
until
memory.
right-hand
is reached. For example,
(\"rom.patt\",
Starts
the
1.
Section 3.7
Data Types
// Reads
An
an
4.
Register
Integer
for modeling
typically
of the
declaration
integer
can be usedas a general behavior. It is declaredusing high-level
integer values. It
contains
register
integer register,
purpose
4);
6 through
addresses
from
6,
RomB,
(\"rom.patt\",
$readmemb
form:
integer integerl , integer2,. msb and
lsb are constant-valued
..
,
integerNl
msb
: lsb
];
that specify the range of an no bit range is is Notice that integer array; optional. array range specification a minimum of 32 bits; however, an implementation allowed. An integer holds of integer declarations. may provide more. Here are some examples expressions
the
C;
A, B,
integer
II Three integer
integerHist[3:6]; //
An provide
An
of
signed quantities results.
registers.
four
integers.
and arithmetic
operations
arithmetic
complement integer
array
the be accessed as a bit-vector.For example, given are not allowed. One way for integer B, B[6] and B[20:10] is to assign it to a reg register and then bit-value of an integer from the reg register. Here is an example.
cannot
declaration
above
to extract a select
holds
register
integer
two's
An
the
bits
Br eg;
[31:0]
reg
Bint;
integer
// Bint[6]
Bint[20:10]
and
Breg = Bint;
/*
At
this
point,
the
give
Breg[6]
corresponding
are
not allowed.
and Breg[20:10] are from the
allowed
and
bit-values
integer Bint */ This
example
accomplished
by
shows simply
that
using
converting an integer to a bit-vector can an assignment. Type conversionis automatic.
be No
spe-
45
Language Elements
cial functions are necessary.Converting
also be accomplished by using
to an integer
a bit-vector
from
can
some examples.
Here are
an assignment.
integer J;
reg [3:0]
Beg;
= J;
Beg
has the value 32'b0000.. .00110. the value 4'bOHO.
// J
= 6;
J
//
Beg has
Bcg=4'bOlOl;
J
=
Beg;
III
J
=
-6;
// II
= J;
Beg
Note
that
leftmost
bit;
assignment
any
extra
that
value
32'bOOOO.. .00101.
.11010.
J has the value 32'bllll. . Beg has the value 4'blOlO. takes place
always
bits are
remember
can
you
the
J has
from the rightmost
bit
to the
truncated. It is easy to think of type conversion if are represented as two's complement bit-
integers
vectors.
Time
Register
register is usedto storeand
A time
using a time declarationof the time
time_idl
manipulate
It is
values.
time
declared
form:
, time_i<32
, . .
.,
time_idN
[
msb
: lsb
];
and lsb are constant-valued the range of that indicate expressions no is each identifier stores one time value which is indices.If range specified, 64 bits. A time register holds only an unsigned at least Here are quantity. where msb
examples
of
time
time
time
declarations.
Events[0:31] CurrTime;
;
// Array of time values. CurrTime holds one time value. //
Real and RealtimeRegister A
form.
real
register
(or a
realtime register) can be declaredusing
the
following
SECTION3.8
Parameters
// Real declaration:
real real_regl,
,
real_reg2
.
.
. ,
real_regN;
declaration:
II Realtime
realtime realtime_regl , realtime_reg2 ,.
. .,
realtime_regN;
A
realtime
identical to a real register.Hereare
is exactly
register
some
examples.
real
Top;
Swing,
realtime
The default
CurrTime; of a
value
is allowed for
real register register.
is 0. No range,bit
range
or word
range,
a real
declaring
When assigning values x and z to a real register,thesevalues
are
treated
as
aO.
real
RamCnt;
= 'bOlxlZ;
RamCnt
RamCnt has
i.8
the value
after
'b01010
the assignment.
Parameters A
is a
parameter
variables. declaration.
A
and widths of often used to specify delays a value only once, using a parameter can be assigned declaration is of the form:
It is
constant.
parameter
A parameter
parameter paraml \342\200\224 const_exprl a
paramN
Here
are some
, param.2
= const_exp2
, .
. .,
const_exprN;
examples.
parameter
LINELENGTH
parameter BIT
=
1,
=
BYTE
= 16
132,
ALL_X_S
=8,
PI = 3 .14;
'bx;
47
Chapter 3
Elements
Language
parameter
STROBE_DELAY = {BYTE +
parameter
TQ_FILE
value can
A parameter
using a defparam module
=
statement
instantiation
also be changedat or
statement
BIT) I
2;
\"/home/bhasker/TEST/add.tq\";
specifying
by
two mechanisms
(these
time.
compile
the parameter
This
is done by
value in
the
are describedin
Chapter
9).
3.9
Exercises
1. Identify the COunT,
legal and
identifiers:
illegal
\\**7 , Real?, \\wait, Initial
l_2Many,
2.
What
3.
Explain
the text substitution
4.
Is there
a Boolean type in Verilog
5.
What
are the bit
6.
is
What
the
reg [1
If a
example.
HDL?
the
following:
10'd2, 'hzF
stored
in
after
Qpr
the assignment?
: 8*2] Qpr;
= \"ME\";
Qpr
7.
patterns for
bit pattern
function?
compiler directiveusing an
'BxO, 5'bxllO, 'hAO,
7'o44,
task or a system
a system
identifies
character
first
net Bnq is declaredbut
no
is made
assignment
to it, what is its default
value?
8.
net
9.
HDL allows
Verilog kind
What is wrong with integer
10. Write
a system
mA.data\".
48
a net
not
to
be
explicitly
declared.
If so, how
is the
determined?
[0:3]
the
following?
Ripple;
task to
load a 32 by
64
word
memory
from a data
file
\"rae-
Exercises
11. State two
ways
by
which
you can
override a parametervalue
SECTION3.9
at
compile
time.
\342\226\241
49
4
Chapter
Expressions
This
the
describes
chapter
basics
of how
VerilogHDL. An
be used
4.1
is formed
expression
wherever a value
using operands
is
expected.
Operands An
can
operand
i.
Constant
ii.
Parameter
Hi.
Net
be one
of the following,
iv. Register
50
v.
Bit-select
vi\".
Part-select
vii.
Memory
element
expressions are formed in
and operators.An
expression
can
Operands call
viii. Function
.1.1
4.1
SECTION
Constant in the
described
were
Constants
Here are some
previous chapter.
examples.
7
256,
4'bl0_ll,
'bl,
//
Unsized
decimal numbers
//
Unsized
integer
8'hOA// Sized integerconstants
'hFBA
// Real constant
\"BOND\"
/*
An integer
value
an
in
is a
If it
number.
each character
constant;
String
as a 8-bit
unsigned
constants
90.00006
is interpreted
expression
decimal integer,for
example,
as either a signedor an 12, then it is interpreted
or as a signed number.If the integeris a basedinteger (unsized is treated as an unsigned number. Hereare someexamples.
12
in 5-bit is 01100
-12
is
vector
decimal
5'bOllOOis
5'bl0100is
4'dl2 More
is
form
(signed)
form
(signed)
sized),
then
it
12 (unsigned)
decimal 20 (unsigned) 12
decimal
is the
important
5-bit vector
10100 in
is stored
*/
value
ASCII
fact
that
(unsigned)
value of an
a negative
integer is treated value of an
with or without a base. integer an integer with a base while specifier is treatedas a signedvalue, different from as an unsigned value. Thus, -44 is treated specifieris treated next 44 is in the -6'o54 octal as shown (decimal 54) example. for
differently
with
The negative
an integer
no base
Cone;
integer
Cone=
-
44 /
4;
Cone = - 6'o54 / Note
that
both
-44
4;
and -6'o54
are evaluated
-44 is treatedas a signednumber, number. value
Thus
Cone
1073741813
in the
first
in the
assignment
while
to
-6'o54 has
the
same
is treated
the value
bit pattern; however as an unsigned
-11, while
Cone has the
second assignment.
51
CHAPTER
4.1.2
4
Expressions
Parameter
Parameters were describedin the previous a parameter constant and is declaredusing a parameterdeclaration.
parameter
= 4
LOAD
values 12 and 4.1.3
10
Here is an
a of example is like
4 ' dlO;
, STORE=
of parameters
are examples
STORE
and
LOAD
' dl2
A parameter
chapter.
declaration.
that
declared
are
to have
the
respectively.
Net
Both scalarnets (1-bit)and expression.
A
are
Here
examples
nets
vector
of net
wire [0:3] Prt;
II Prt is
a
wire Bbq;
II
a scalar
in a
value
net is
Bbq
can be
(multi-bit)
used
in
an
declarations.
is
interpreted as an
4-bit
unsigned
net.
vector
net. value.
In the
continuous
assignment,
Prt
assign
=
Prt hasthe bit-vector the following
4.1.4
assigned
which
is in effect the
decimal value
13.
=
the bit-vector
4 'HA;
1010assignedto it
which
is the
decimal
value 10.
Register
Scalar
and
declared
52
1101
continuous assignment,
assign Prt Prt has
- 3;
using
vector
a register
registers
used in an expression. A Here are some examples.
can be
declaration.
register
is
In
SECTION
Operands
4.1
TemA, TemB;
integer
reg [1:5] State;
time
A value number
while
unsigned
number.
an
in
in a
Values
as a signed two'scomplement or a time as an reg register registeris interpreted real and realtime registers are interpreted as signed
register
integer
a value
in
TemA
-
- 10;
TemA
=
'blOll;
State State
=
-
// TemA has the bit-vector 10110, which of 10. //is the two's complement // TemA has the decimal value 11. State
//
has the bit-vector
which
is
//
which
//
10;
10110,
22.
decimal
// State has the bit-vector 01011,
= 'blOll;
decimal
the
is
11.
value
Bit-select A
bit-select
extracts
a particular
Here are
bit from
a vector.It is of the
form:
[ jbit_select_expr]
net_or_reg_vector
examples of bit-selectsused in expressions.
State[l] Prt[0]
|
&&
bit-select Register bit-select
//
State[4]
Bbq
If the selectexpression evaluates value of the bit-selectis an x, for
6
is interpreted
point values.
floating
5
[1:5];
Que
II
Net
to
an x
example,
or a
z or if it
is
out
of bounds,
the
State[x] is an x.
Part-select In
of
the
a part-select,
a contiguous
sequence of
bits of a vectoris selected.It is
form:
net_or_reg_vector
[
msb_const_expr
: lsb_const_expr]
53
CHAPTER4
Expressions
wherethe rangeexpressions must
be
constant
Here are
expressions.
some
examples.
State
[1:4]
Prt [1:3] If either
Register Net
part-select
part-select
of the range indexis out is an x.
bounds
of
or evaluates
to an x or a z, the
value
part-select
4.1.7
//
//
Memory Element A
element
memory
is an
of a memory.It is of the form:
example.
reg [1:8] Ack
No
one word
word_address]
memory!
Here
selects
Ack,
= Dram[60]
Dram[0:63];
;
or bit-select
part-select
// 60th of a memory
element of is
allowed.
Dram[60]
[2]
is not allowed.
Dram[60]
[2:4]
is
also
not
memory.
For example,
allowed.
of a word in memory is to One approachto reada bit-selectora part-select a and then use a part-select or a bit-select element to the assign memory register and are of this register.Forexample, j4c&[2:4] /4c&[2] legal expressions. 4.1.8
Function Call A
function
function
call
$time
call
(starts
can be used in an expression. It can either be a with the $ character) or a user-defined function call.
+ SumOfEvents
(A, B)
function and SumOfEvents is a /* $time is a system user-defined function (defined elsewhere)*/
54
system
Operators
are described in greaterdetail
Functions
.2
in
SECTION
4.2
10.
Chapter
Operators
Operatorsin VerilogHDLareclassifiedinto i.
Arithmetic operators
ii.
Relational
Hi.
Equality
the
following
categories.
operators
operators
iv. Logical
operators
v.
Bitwise
vi.
Reduction
viii.
Conditional
ix.
Concatenation
operators
operators vii. Shift operators
The The
following
operators
precedence
(bottom
operators
table
and replication
operators
the precedence and names of all the operators. from highestprecedence(top row) to the lowest in the same row have identical Operators precedence. shows
are listed row).
+
Unary
-
plus
Unary minus
I
Unary
negation
logical
~
Unary bit-wise negation
&
Reduction and Reduction nand
~& A
A~ or
~A
Reduction
xor
Reduction
xnor
1
Reduction or
-1
Reduction nor
* Multiply
/
Divide
%
Modulus
+
Binary plus
\342\200\224 Binary
minus
55
CHAPTER 4
Expressions
\302\253
Left
\302\273
Right
A AII
Less than
shift
shift
V
Less than Greater
than
V II
Greater
than
!=
Logical
or
equal
to
or equal to
Logical equality inequality
Case equality
Case inequality & A
A~ or
All
+
A
Bit-wise
xor
Bit-wise xnor Bit-wise
or
&&
Logical
and
II
Logical or
?:
Conditional operator
to left.
right
and
1
left to
associate
operators
associates
~A
Bit-wise
right
except
for
the conditional
The expression:
C
B-
is evaluated as: + B)
(A
while
the
right
expression:
A ?
is evaluated
A
56
II Left to
- C
B : C?
D
:
F
as: ? B
:
(C ? D
: F
)
II
Right
to left.
operator
that
Operators can be
Parentheses
used to
such changethe orderof precedence,
SECTION
as
4.2
in the
expression:
.2.1
Arithmetic
?
: C)
? B
(A
D
:
F
Operators
The arithmetic
are:
operators
\342\200\242 +
\342\200\242
(unary
and binary
(unary
and binary minus)
plus)
* \342\200\242
(multiply)
\342\200\242 /
(divide)
\342\200\242 %
(modulus)
division
Integer
truncates any fractional part. Forexample,
is 1
7/4 The
%
(modulus)
gives the remainder
operator
with
the
sign
of the
first
operand.
7
4
%
is
3
is
-3
while:
-7
%
4
If any bit of
resultis an
x. For
'blOxl
Result
an operandin an
arithmetic
operation
is an
x or a z, the entire
example,
+ 'bOllll
is
'bxxxxx
Size
The size of the resultof an arithmetic is determined expression by the size of the largest operand.In caseofan assignment, it is determined by the size of as well. Consider the following the left-hand side target example.
57
Expressions
Bar, Crt;
[0:3] Arc,
reg
reg [0:5]
Frx;
= Bar
Arc
+ Crt;
Frx = Bar +
Crt;
The result sizeof the by the size
So in
first
the
size of the secondaddition
of Frx (largestof sizesFrx, assignment, any overflow from the
similarly
while in the
second assignment,any
Frx[\\]. In largerexpressions, how determined?
HDL
Verilog
this
the
are
a rule
defines
sizes
is decided
operation
Crt),
Bar,
which
operation
plus
all
result bit
results
of the intermediate
which statesthat
is six bits. is discarded
in the
is saved
bit
overflow
size of Bar, Crt and
results
intermediate
of
shall take the sizeof the largest operand (in case of an includes the left-hand side target).Consideranother example.
an expression assignment,
by the
is determined
addition
bits. The
is four
which
Arc
first
also
wire
[4:1]
Box, Drt;
wire [1:5] Cfg;
wire [1:6]Peg; Adt =
assign size of
The
the
including
performed
size 8.
Adt;
[1:8]
wire
{Box + Cfg) + (Drt
the largest
operand in
the
+
Peg)
right-hand
;
side expression
is 6,
but
are left-hand side, the largestsizeis 8. Soall additions 8 bits. Box and a result of For Cfg yields using example,adding
of the
size
Unsignedand Signed When
to note being
arithmetic
performing
which operands
treated
as signed
operations
and assignments,
are beingtreatedas unsigned
values.
An
unsigned
value
\342\200\242 a net \342\200\242 a
reg
\342\200\242 an
register
integer
in base
format notation
and
values
is stored
in:
it
is
important
which
are
Operators stored in:
value is
A signed
\342\200\242 an \342\200\242 an
4.2
SECTION
integer
register
integer
in decimal
form
Here are some examplesof assignments. Bar;
[0:5]
reg
Tab;
integer
Bar = - 4'dl2; = -
Tab
-
//
4'dl2;
/
4'dl2
is a
Bar
4
reg register,
right-hand
the decimal value
the
vector
is
it
assigned
holds
52
as an
is
only
value of
values. The
unsigned
10100 (the two's complement the assignment.
after
is the
to an integer
the decimal
cases, the same bit-vector
interpreted as a signed interpreted
stores
is 'bl
side expression
being
Tab
quantities. Thus
in both
expression
right-hand it
is 1073741821.
Result
//
Bar holds this time
value 52,
decimal
// Result is -3.
side
assignment,
the
// (bits 110100)
-12/4 Since
has
Bar
Reg
// which is the vector110100. Tab has the value -12 // Integer
stored;
12).
the
Thus
In the second
same, whosevalue
is
'bl
10100,
but
register which holds signed
value -12 (the bit-vector is
of
however,
unsigned number and in the
Note
110100).
in the
first
case,
secondcase,it
that
the
is
number.
Here are some moreexamples. Bar
=
Tab
=
Bar =
- 4 ' dl2 - 4 ' dl2 -
12 /
Tab = - 12 /
/ 4; / 4; 4; 4 ;
Bar gets the decimal value 61 (bit-vector 111101), the decimal value 1073741821 Tab (bitassignment, gets vector 0011...11101). Bar gets the same value in the third assignment as in the This is because Bar holds only unsignedvalues.In the fourth first assignment. the decimal value -3. Tab gets assignment, In
first
the
while
in
the
assignment, second
59
CHAPTER4
Expressions
Here are somemoreexamples. =
Bar
4-6;
Tab = 4 -
Bar gets
Hereis
= -2 +
gets the -6
value
4.2.2
+
while
Tab
gets
the
(-4) ; (-4);
decimal value
58
111010),
(bit-vector
while Tab
gets the decimal
111010).
(bit-vector
Relational
-2),
example.
Tab = -2 Bar
complement of
(bit-vector111110).
another
Bar
62 (two's
value
decimal
the
value -2
decimal
6;
Operators
The relationaloperatorsare: \342\200\242 >
(greater
\342\200\242 <
(less
\342\200\242 >= \342\200\242 <=
than) than) than
(greater (less
than
or equal
or equal
to)
to)
The result of a relationaloperatoris true (the value 1) or false (the value 0). Resultis an x if any bit in either of the operands is an x or a z. Forexample,
23 is false
>
45
(value 0),
while:
52 < 8'hxFF
is x.If operands the most significant
are
not bit
side
'blOOO >= 'bOlllO
is equivalent 60
to:
same size, the smaller operandis zero-filledon (the left). For example,
of the
SECTION4.2
Operators
'bOlOOO>= 'bOlllO is
which
false
0).
(value
Operators
Equality
The equality
equality)
(logical
\342\200\242 !=
inequality)
(logical
\342\200\242 ===
(case
\342\200\242 !==
equality)
(case
is 0 if
The result
are:
operators
\342\200\242 ==
the
inequality) comparison
is false,
else the resultis a
1.
In
case
z are compared strictly as values, that is, with no while in logical comparisons, can never be an unknown, values x and z have their usual meaning and the result may be unknown; that is, for logical comparisons if either operand contains an x or a z, the result is comparisons,
x and
values
interpretations,
and
result
the
the unknown
value
(x).
is an example.
Here
Data =
Given:
'bllxO;
= 'bllxO;
Addr
then:
Data == Addr
is unknown,
is, the
that
value x, and:
Data === Addr
is true, that
is,
the
value
1.
If the operandsare of unequal on the most significant that side,
2'blO
==
lengths,
is, on
the
smaller
operand
is zero-filled
the left. For example,
4'b0010
61
CHAPTER 4
Expressions
is same as: ==
4'bOOlO
which
4.2.4
is true
4'b0010
(the value
1).
Operators
Logical
The logical
operatorsare:
\342\200\242 &&
and)
(logical
\342\200\242 II (logical
or)
\342\200\242 ! (unary
negation)
logical
These operators operate on logicalvalues operation is a 0 or a 1. For example, given: = 'bO;
Crd
Dgs =
// //
'bl;
0 or
1. The
result of a logical
false. true.
0 is 1 is
then: Crd &&
Dgs
is
Crd | |
Dgs
is 1 (true)
!
is
Dgs
For vector
0
0
(false) (false)
operands, a non-zerovectoris treated
given:
A_Bus
=
B_Bus
= 'bOlOO;
'bOllO;
then: A_Bus A_Bus
and:
62
| |
B_Bus
&& B_Bus
is 1 is also
1
as
a 1.
For example,
Operators ! B_Bus
same as
is
! A_Bus
4.2
SECTION
which is 0.
If a
in
bit
operands is an
of the
any
x, the
result
is also an
x.
is x
!x
Bit-wise Operators bit-wise
The
negation)
(unary
\342\200\242 &
and)
(binary
\342\200\242 I (binary
or)
A \342\200\242
exclusive-or)
(binary
\342\200\242
~A,
A~
These operators operands
and
are:
operators
\342\200\242 ~
(binary
operate bit-by-bit, a vector
produce
exclusive-nor)
bit-by-bit operation
the
for
on
corresponding
result. The following various
bits
tables show
of the the
input
result
of the
operators.
&(and)
0
1
X
z
l(or)
0
X
z
0
0
0
0
0
0
0
X
X
1
0
1
X
X
1
1
1
1
X
0
X
X
X
X
X
X
X
z
0
X
X
X
z
X
X
X
63
4
Expressions
A
(xor)
0
1
X
z
0
0
1
X
X
1
1
0
X
X
X
X
z
X
X
~
is an
Here
A
=
A~ (xnor)
0
1
X
z
0
1
0
X
X
X
1
0
1
X
X
X
X
X
X
X
X
X
X
X
z
X
X
X
X
(negation)
0
1
x
z
1
0
x
x
example. Given,
'bOllO;
B = 'bOlOO;
then: A
|
B
is
A
&
B
is
If the operands
0110 0100
are unequal in length,the smalleroperand
most significant side. Forexample,
'bOllO A
is same
'bl0000
as: A \342\200\242bOOHO
whichis'blOllO.
'bl0000
is
zero-filled
on the
Operators
1.2.6
SECTION4.2
Reduction Operators
The
reduction
a 1-bit
produce
\342\200\242 &
x, else
is
is an x
bit
or a z, the result
nand):
or):
is a
If any bit result
any
& reductionoperator.
\342\200\242 I (reduction
\342\200\242 ~l
0, the result is 0,elseif the result is a 1.
(reduction
Invert of
single operand and
and):
(reduction
\342\200\242 ~&
bits of a
are:
The operators
If any bit is
is an
on all
operate
operators
result.
an
bit
is an
x or
a z, the
nor):
(reduction
Invert of
1, the resultis 1, elseif any result is 0.
x, else the
I
reduction
A \342\200\242
operator.
xor):
(reduction
x or a z, the result is an x, else if there are even number of l's in the operand,the result is 0, else the result is 1. If
\342\200\242 ~A
any
are some A
=
xnor):
(reduction
Invert of Here
is an
bit
A
reduction
operator.
examples. Given,
'bOllO;
B = 'bOlOO;
then: \\
B
is
1
&
B
is
0
-A A
is 1
The reductionxoroperatorcan
is
an
be
used
to determine
if any bit of a vector
x. Given,
MyReg = 4'bOlxO;
then:
65
CHAPTER
4
Expressions
\"MyReg is
an x
This can be checkedusing if
an
===
{\"MyReg
l'bx)
is an
(\"There
$display
such as:
if statement
vector
the
in
unknown
MyReg!\") ;
cannot be used for comparison; will logical equality operator comparison only yield the result x.Thecase 1 the value which is the desiredresult. operator yields equality Note
the
that
(==) operator
equality
logical
the
4.2.7
Shift Operators shift
The
are:
operators
\342\200\242
\302\253(left-shift)
\342\200\242
\302\273(right-shift)
shift
The
shifts the
operation
times.It is a logicalshift. operand
to an
evaluates
x or
left
by
operand
vacated
The
bits are
the
right operand
filled
a z, the resultof the shift
0.
with
If the is an
operation
number of
right x. Here
is an
Given:
example.
[0:7]
reg
Qreg;
Qreg = 4'bOlll;
then: Qreg
is
\302\273 2
8'b0000_0001
has no exponentiationoperator.However, the shift operator this partly. For example, if you are interestedin support this can be achieved by using the shift such as: operator,
Verilog HDL can be
used
computing
2NumBlts,
to
32 'bl In a
similar vein,
wire
66
II
\302\253 NumBits
NumBits
a 2-to-4decodercanbemodeled
[0:3] DecodeOut=
4'dl
\302\253 Address[0:1
must be
using
] ;
less than a shift
32
operator.
.
SECTION4.2
Operators
Address[0:\\]can have values the values 4'b0001,4'b0010,4'b0100,
0,
and 3.
1,2,
and
Correspondingly, DecodeOuthas thereby modeling a
4'bl000,
decoder.
.8
Conditional
Operator
operator selects an
The conditional
conditionexpressionand
it is
of the
on the
based
expression
value of the
form:
cond_expr ? exprl : expr2
If
bitwise
operation
with
on exprl
1, rest are
1 gives
Hereis an
and exprl
with
the
= Marks >
18 ? Grade_A
is another
to
The
= [Ctr
in the
expression
incrementCtr,elseif .9
Concatenation
procedural Ctr
? (Ctr +1)
!= 25)
becomes
0,
are some
Grade_C;
Grade_A
is
assigned
to
Student.
: 5;
assignment says that 25, reset it to 5.
the
operation
expressions. It is of the
{ exprl
Here
0 gives
if Ctr
is not
equal to 25,
and Replication is
Concatenation
form larger
with
example.
always Ctr
:
18 is computed;if true,
Marks >
Student, if Marksis <= 18,Grade_Cis assigned
#5
0
x
Student
[0:2]
expression
Here
logic:
following
is
example.
wire
The
if cond_expr is, has value 1), exprl is selected, is selected.If condjexpris an x or a z, the result is a
(that
0), exprl
(value
1
true
is
cond_expr
false
, expr2
, .
of joining
bits from
smaller
expressions
to
form:
. . , exprN
}
examples.
67
CHAPTER
4
Expressions
wire
Dbus;
[7:0]
wire [11:0]
Abus;
= {Dbus[0], Dbus[7:4] lower four II Assign four bits. //
assign
Dbus = [Dbus[3:0] , Dims[7:4]};
assign
//
and
lower
Swap
these
are
numbers
bits. as the
allowed
is not
numbers
size of
For example,
known.
not
four
upper
Concatenation of unsized constant
is // Unsizedconstantin concatenation
{Dbus, 5}
not
allowed.
//
is not
Dbus[3]};
Dbus[2],
D\302\243>us[l],
bits in reverse orderto upper
legal.
Replication is performedby
number.
a repetition
specifying
It is
of the
form: { repetition_number { exprl , expr2,. are some
Here
Abus
=
//
{3{4'bl011}};
A
The bit-vector
Dbus);
as
same
I*
Sign
12,bl011_1011_1011 */
extension
{Ack,
Ack,
Ack]
that
evaluates
of Expressions constant
expression
is an
expression
compile time.More specifically,
i.
constant
literals,
a constant
such
ii, parameternames,such
68
}}
exprN
is 111
{3{l'bl}}
{3{Ack}} is
Kinds
,
examples.
Abus = {{4 {D\302\243>us[7]}},
4.3
..
as 'MO as
RED
expression
to a
can be
constant
value at
made up of:
and 326 from
the parameter
declaration:
Exercises RED = 4'blllO;
parameter
A scalar
is
significant
bit of
result
1.4
expression is an
scalar
4.4
SECTION
to a 1-bit result. If a a vector the expression produces result, the least expression
that
the vector is used(the
rightmost
but
expected
evaluates
bit).
Exercises
1. Declare a parameterGATE_DELAY
2.
3.
of size 64 words, with Given a memory code to swap the contents of memory word at 0 to word at 63, word 1 to word
Given a 32-bit bus, Address_Bus, write reductionnand of bits 11 through 20.
4. Given one bus, Control_Bus[l5:0], write will split the bus into two buses, Abus[0:9] 5.
an
Write
that
expression
number contained 6.
in
performs
of 5.
a value
with
8 in 62,
an
bits
reverse and
word, write Verilog that is, transfer so on. per
order,
that computes
expression
an
that
statement
assignment
the
and Bbus[6:l].
the arithmetic
shift
of
a 8-bit
signed
Qparity.
a conditional operator, write an assignment that selects statement the value of NextState.If CurrentStateis RESET, then NextState is GO, if CurrentState is GO, NextState is BUSY, if CurrentState is BUSY,NextState Using
is RESET. 7.
the behavior
Model using
a
single
conditional
8.
How
would
of the
continuous operator you
and
generate
2-to-4 decodercircuitshown
in
Figure
assignment statement. [Hint: Use shift the concatenation operator]. a bus,
BusQ[0:3], from
scalar
four
2-2 operator,
variables,
A,
B, C, and D? How
would
you
form
a new
bus, BusR[10:l], from
two
buses,
BusA[0:3]
andflu*y[20:15]?
\342\226\241
69
5
Chapter
Modeling
Gate-level
This
chapter
the available
It describes
the gate-level
describes
built-in primitive
HDL. modeling capability of Verilog and how these can be usedto gates
describe
hardware.
5.1
The
The following i.
Gates
Primitive
Built-in
built-in
primitive
Multiple-input
gates
gates:
and, nand, or, nor,xor,xnor ii.
gates:
Multiple-output
buf, not
Hi. Tristate gates: bufifl,
buflfO, iv.
Pull
gates:
pullup,
70
notifO,
pulldown
notifl
are available
in
Verilog
HDL.
Section 5.2
Multiple-input Gates switches:
MOS
v.
in
the
that
instantiation. Here is a simple
specify
term2
,
.
.
. ,
termN);
gatejtype is one the gateslisted and registersconnectedto the terminals of the
is optional;
instance_name
terms
The
earlier.
a gate
using
[ instance_name ] ( terml ,
gate_type Note
a design
rtran, rtranifO, rtranifl
instantiation.
a gate
of
format
tranifl,
tranifO,
be used
can
gate
switches:
Bidirectional
tran, A
rcmos, rnmos, rpmos
nmos, pmos,
cmos, vi.
the nets
gate.
Multiple instances of the
The syntax for
is the
this
same gate type
specified
in one
construct.
following.
gate_type [ instance_namel
5.2
be
can
[
instance_name2
] ( term.21
, terml2 , , term22,.
. . . , termlN), . . , term2N),
[
instance_nameM
]
( termMl
, termM2 ,
. . .
]
( termll
,
terwMN);
Gates
Multiple-input
The multiple-input built-in gates are: nor
nand
and
xnor
xor
or
These logic gateshave only one output syntax of a multiple-input gate instantiation.
and one
multiple_input_gate_type I
The
instance_name
first terminal Here
are
some
is the output examples.
] ( OutputA
and
, Input
all others
The logic
or more inputs.
1 , Input2 ,...,
are the
is the
Here
);
InputN
inputs. See Figure5-1.
diagrams are shown
in
Figure
5-2.
71
Gate-level Modeling
Inputl
InpuiT
OutputA \342\200\224>
Multiple-input
gate
:
InputN
5-1
Figure
gate.
(Outl, Inl, In2);
andAl and
Multiple-input
RBX
Bro,
Rib,
(Sty,
Qit, Fix) ;
xor (Bar, Bud[0],Bud[l],Bud[2]), (Car,
Cut[0],
Cut[l]),
(Sar,
Sut[2],
Sut[l],
Sut[0], Sut[3]);
Bud[0]
Car
Bud[l]
Bud[2]
Sut[2]
Sut[l]
Sut[0] Sut[3]
Figure
The
5-2
Multiple-input
gate examples.
name Al, 2-input and gate with instance and with two inputs, Inl and Inl. The secondgate instantiation is a output Outl and gate with instance name RBX, output Sty and four inputs, Rib, 4-input instantiation is an example of an xor gate with Bro, Qit and Fix. The third gate no instance name. Its output and it has three inputs, Bud[0],Bud[\\] is Bar and has two additional instancesof the same type. Also, this instantiation Bud[2]. first
gate
instantiation
is a
The truth input
tables
for
like an
is handled
never be a z.
gates are
these
x; additionally,
SECTION5.2
Gates
Multiple-input
shown next. Noticethat the
of a
output
a value
z at an
gate can
multiple-input
nand
0
1
X
z
and
0
1
X
z
0
1
1
1
1
0
0
0
0
0
1
1
0
X
X
1
0
1
X
X
X
1
X
X
X
X
0
X
X
X
z
1
X
X
X
z
0
X
X
X
or
0
X
z
nor
0
1
X
z
0
0
X
X
0
1
0
X
X
1
1
1
1
1
0
0
0
0
X
X
X
X
X
X
0
X
X
z
X
X
X
z
X
0
X
X
xor
0
1
X
z
xnor
0
1
X
z
0
0
1
X
X
0
1
0
X
X
1
1
0
X
X
1
0
1
X
X
X
X
X
X
X
X
X
X
X
X
z
X
X
X
X
z
X
X
X
X
73
Chapter
5.3
Gate-level Modeling
5
Gates
Multiple-output
The
not
buf
These gates have basic syntax for
one
only this
gate
input and instantiation
one or more outputs.
See
[
all
input,
( Outl,
]
instance_name
terminal is the
0ut2 , .
terminals
remaining
. . , OutN,
are the
Out! InputA
not
are some
74
examples.
Bl [Fan[0], Fan[l],
not
Nl
{PhA,
instance,
Fan[2],Fan[3],
Clk);
PhB, Ready); Clk is
the
input
Fan[3].
In the
outputs,
Fan[0]
only
input to
the not gate. This instancehas table
through
for
these
gates are
the
to
four
The truth
gates.
Multiple-output
buf
gate
OutN
buf
OutN
Figure 5-3
first
outputs.
_Out2
InputA
In the
);
InputA
Outl
Outl
Here
5-3. The
Figure
is:
e_outpu t_ga te_ type
mul t ipl
The last
are:
gates
multiple-output
buf gate; this
gate instance
second gate instance,Ready two
outputs,
shown next.
buf
not
(output)
(output)
PhA
and PhB.
is
has the
Tristate Gates
SECTION
5.4
Gates
THstate
The tristate
gates are:
These gates and
input
one
notifO
bufifl
bufifO
model three-statedrivers. control input. Here is the
notifl
These
have
gates
basic
syntax
of a
one output,
one data
tristate gate
instantiation.
tristate_gate
[
The first terminal OutputA and the control input,
instance_name
is the is
input
can be
the output
output, ControlC.
]
(OutputA,
InputB,
ControlC);
terminal InputBis the data Figure 5-4. Depending on the
the second See
to the high-impedance state, that is, to z if is else data control is 1, is transferred gate, output to is a z if control is 0. Fora notifO gate, gate, output at z if at For is control is 1 else is invert of the data value. the output output input notifl gate, output is at z if control is at 0. control
input,
a bufifO output. For a bufifl
value
z. For
driven
the
bufifl
notifl
OutputA
InputB
InputB ControlC
ControlC
notifO
InputB
P\"-^
ControlC
J\\.
OutputA
^ bufif0
OutputA
InputB
\\
p-v^
OutputA
ControlC
Figure
5-4
Tristate gates.
Here are someexamples.
bufifl
BF1
notifO
NT2 {Addr,
[Dbus,
MemData,
Strobe);
Abus, Probe);
75
CHAPTER
5
Gate-level
Modeling
Dbus to high-impedance state when gate BFl drives the output to Dbus. In the second instantiation, is transferred Strobe is 0, elseMemData when Probe is 1,Addr is in high-impedance state, else Addr gets the inverted
The bufifl
of Abus.
value
The indicate
alternate
be a 0 or a z
Data
76
the
in Chapter
the
that
indicates
of the data
strengths
output
the
table
can either
and control values;
10.
Control
bufifl
0
1
X
z
0
0
z
0/z
0/z
1
1
z
1/z
1/z
X
X
z
X
z
X
z
X
notifO
shown next. Someentriesin
example,0/z
on
depending
bufifO
Data
gates are
these
entries. For
discussed
are
strengths
for
table
truth
Control
0
1
X
z
0
z
0
0/z
0/z
1
z
1
1/z
1/z
X
X
z
X
X
X
X
z
z
X
X
X
Control
Data
notifl
0
1
X
z
0
1
z
1/z
1/z
1
0
z
0/z
0/z
X
X
z
x
z
X
z
x
Control
0
1
X
z
0
z
1
1/z
1/z
1
z
0
0/z
0/z
X
X
z
X
X
X
X
z
z
X
X
X
Data
Section 5.5
Pull Gates
5.5
Pull Gates The
are:
gates
pull
pulldown
pullup
These gates have only its output. A pulldown
one
with no inputs. A pullup places a 0 on its output. A gate
output
gate
places
gate
instantiation
a 1 on is of
the form:
I instance_name ] ( Outputs );
pull_gate
The
is an
Here
pullup
This pullup
5.6
of this
list
terminal
gate instantiation
contains only one output.
example.
PUP {Pwr); has
gate
name PUP
instance
with
Pwr
output
tied to
1.
Switches
MOS
switches
MOS
The
cmos
pmos
are:
nmos
rcmos rpmos
unidirectional switches, data flow can be turned off by
model
These
gates
output
and the
rnmos
appropriately
from input to the control setting
(n-type MOS
transistor), rnmos
that
data
is,
flows
input(s).
The pmos (p-type
('r'
stands
for
MOS
resistive)
one control input.
gate_type
nmos
transistor),
and rpmos
The basic syntax
switches have for
one output,
[ instance_name ] ( Outputs
one
input
and
is:
an instantiation
,
InputB
, ControlC
);
77
CHAPTER
Gate-level
5
Modeling
and The first terminal is the output, the second terminal is the input the last and rnmos terminal is the control.If controlis 0 for nmos switches and 1 for pmos and rpmos switches, the switch is turned off, that is, output has value z; if control is 1, data at input passes to output; see Figure 5-5. The resistive switches
the
between have a higher impedance(resistance) terminals as compared to the non-resistiveswitches
and
(rnmos
rpmos)
and output
input
(nmos and
for
occurs
strength
from input to output, resistive switches; strengths are describedin when
Thus
pmos).
data passes
OutputA
InputB
a reduction
in
10.
Chapter
OutputA
InputB
O
ControlC
ControlC
nmos switch
Figure
Hereare
some
pmos
PI
rnmos
5-5 Nmos
and pmos switches.
examples.
{BigBus,
RN1
SmallBus,
GateControl);
GateControl. The tables truth
indicate
alternate
for
these
entries.
with is
switches are For example,
either 1 or z dependingon the input
78
Hold);
ReadyBit,
[ControlBit,
The first instance instantiates a pmos switch to the switch is SmallBus and the output
table
switch
pmos
and
instance
BigBus
and
name
PI. The
the control
shown next. Someentriesin 1/z indicatesthat the output
control.
input
signal is the
can be
Section 5.6
MOS Switches
Control
pmos
nmos
Control
rnmos
rpmos
Data
0
1
X
z
0
0
z
0/z
0/z
1
1
z
1/z
1/z
X
X
Z
X
z
z
z
z
z
0
1
X
0
z
0
0/z
0/z
1
z
1
1/z
1/z
X
X
z
X
X
X
z
z
z
z
z
z
Data
of cmos) MOS) and rcmos (resistiveversion (complimentary have one data one data two switches control inputs.The output, input and these two switches is of the form: syntax for instantiating
The
cmos
(r)cmos
[
]
instance_name
( OutputA
The
first
terminal
and
(rcmos) an
nmos
Figure 5-6.
output,
the
second
is the
, NControl , PControl); input,
the
third
is the
n-
fourth terminal is the p-channelcontrolinput. A switch behaves exactly like a combinationof a pmos (rpmos) switch with and common inputs; see common (rnmos) outputs
channel control input cmos
is the
, InputB
and
the
PControl
InputB
OutputA
NControl
Figure
5-6 (r)cmosswitch.
79
Chapter 5
5.7
Gate-level
Modeling
Switches
Bidirectional
The bidirectionalswitchesare:
tran rtran These switches
are bidirectional,that
data
when
delay
propagates
be turned
switches cannot The
for
syntax
flows
data
is,
both ways
through the switches. The
off by setting a control
be turned
rtranifl
tranifl
rtranifO
tranifO
and there is no
last four
signal appropriately.
can
switches
rtran
and
tran
The
off. a
instantiating
or a
tran
rtran
of tran)
version
(resistive
switch is:
(r)tran The
that
is,
The
syntax
from for
, SignalB);
( SignalA
two terminals and data flows unconditionally SignalA to SignalB and vice versa. only
[
bidirectional switches
the other
instantiating
gate__type
The
]
instance_name
has
list
terminal
ways,
[
]
instance_name
( SignalA
, SignalB
both
is: , ControlC );
bidirectional terminals, that is, data flows from The third terminal is the control signal.If and the ControlCis 1 for tranifO and rtranifO, and 0 for tranifl rtranifl, bidirectional data flow is disabled. rtranifO and For the resistive switches (rtran, when it the the of the reduces switch; rtranifl), signal passes through strength first
two
terminals
SignalA to SignalBand
are the vice
strengths are discussedin
5.8
Gate
Chapter
10.
Delays
The signalpropagation specifiedusinga gatedelay. instantiation specification.
80
versa.
itself.
Here
is the
delay The
from gate
any gate delay
input
can be
syntax of a gate instantiation
to
the
gate output
specified with
in
the
the
delay
gate
can be
Delays
SECTION5.8
] ( terminal_list
);
Gate
gate_type
The delay specifiesthe input to the output. When
[ instance_name
]
delay
[
that is,
delay,
gate no
delay
gate
of up delay can be comprised rise i. delay
A gate
A delay The
ii.
fall
iii.
turn-off
the propagation
is specified, to
delay from
the default
gate
any
delay
is zero.
values:
three
delay
delay
specification may
contain
table shows the
following
zero,
one, two,
values that
are
or all three values specified. for a delay based on the
used
numberof specifiedvalues. 1 value
No
(d)
(dl,d2)
Rise
0
d
dl
dA
Fall
0
d
d2
dB
To_x
0
d
mina(dl,d2)
Turn-off
0
d
min (dl,
a. min: that the
Notice
determined
expressed in
is done
min
dC)
dB,
(dA,
(dA,
dB, dC)
dC
d2)
minimum
transition to x delay (to_x)cannot the
from
Here are time
3 values
2 values
delay
other
some examples.Notethat terms
of
using the
time
be
specified
explicitly
but is
values.
specified
units. The
all
delays
in a
Verilog HDL model are
association of time units
timescale compilerdirective.In
the
following
the
gate
with
actual
instantiation,
not
the gate delay
Nl
(Qbar, is
nand #6
0 since
Q) ; no delay
has been specified. In
instantiation,
(Out, Inl, In2);
81
Chapter
Gate-level
5
Modeling
the rise delay and fall delay are both never a nand gate since the output is also 6. to x delay impedance. The transition
all delays are 6, that does not apply to
and #(3, In this gate 5 and
delay
is
the
following
5)
rise
to
(Out,
In2,
Inl,
high-
to be
specified of
3 and
3, the
fall
5, which is
3. In
(Dout, Dinl, Din2);
8, 6)
the fall delay is 8, the turn-off is the minimum of 2, 8 and 6, which
x delay
delay
into
goes
instance,
gate
is 2,
delay
Turn-off
In3) ;
instantiation, the rise delay has been the transition to x delay is the minimum
notifl#(2, the
6.
is,
delay
is 6
and the
transition
is 2.
such as and and or, and multiple-output (buf gates, gates can have only up to two delaysspecified(sinceoutput never goes to to three delays and the pull gates cannot have z). Tristate gates can have up Multiple-input
and not)
any
5.8.1
delays.
A
delay
for
can
also
assignments)
Form
Delay
Min:typ:max
a gate (including all other delays suchas in continuous form. The form is: be specified in a min:typ:max : maximum
: typical
minimum
typical and Here is an exampleofa delay
The minimum,
nand The
selection run.
simulation delay
of
4
this
form
used
must in
be constant a gate
expressions.
instantiation.
(Pout, Pinl, Pin2);
made as an option during a delay to use is usually if simulation is performed,a maximum delay example, of for nand and a fall delay 7 is used the gate instance.
of which
For
A specify
discussed in
82
in
5:6:7)
#(2:3:4,
values
maximum
block can alsobeused Chapter
10.
to
specify
gate delays.
rise
Specify blocks are
Section 5.9
Array of Instances
.9
Array of Instances When
be optionally
in a
specified
a module
are required,
instances
repetitive
a range specificationcan
gate instantiation (a range specification The syntax of a gate instantiation
gate_type
[ delay ( list __of_
]
[ leftbound
instance_name terminal_names
leftbound
of the boundsis not restrictedto bea wire [3:0] nand
This
InA,
Out,
Gang [3
]
: rightbound
two than
is an
constant the
right
It is
expressions. bound and
either
example.
InB;
: 0] (Out, InA,
with the
instantiation
Here
0.
in
case is:
this
);
and rightbound values are any not necessary for the left bound to be greater The
be used
also
can in
instantiation).
InB);
range specificationis sameas:
nand
Gang3
(Out[3],
Gang2 (Out{2], Gangl
(Out[l],
GangO {Out[0],
Note
that
the
instance
name
InB[3]),
InA[3],
InA[2], InB[2]), InB[l]),
InA[l],
InA[0], InB[0]); is not
optional when specifyingan
array
of
instances.
J.
10
Implicit
Nets
in If a net is not declared declared as a 1-bitwire.However be usedto override the default
HDL model, by default,
a Verilog the
implicitly
can This compiler directive is of the form:
\"default_nettype
net type.
it is
compiler
directive
'default_nettype net_type
83
CHAPTER
5
Gate-level
Modeling
Here is an
example.
\"default_nettype this
With
The definition
undeclared nets areof type
all subsequent
directive,
compiler
\"default_nettype and in effect stays
the
until
wand.
directive occurs outsideof a module next same directive is reached or a resetall
is found.
directive
5.11
wand
A Simple
Example
Hereis a
of a 4-to-l description multiplexer circuit shown instance names are Figure specifiedin the gate instantiations used in an array of instances). as these are optional (exceptwhen gate-level
that no
Note
5-7.
module MUX4xl
output and
D2, D3,
Dl,
DO,
input
D2, D3,
Dl,
DO,
(Z,
SO, Si);
Z;
Slbar)
SObar,
DO,
(TO,
SO, SI;
(Tl, Dl,
SObar, SI) ,
(T2,
D2,
SO,
(T3,
D3, SO,
Slbar)
,
,
SI);
not (SObar,SO), (Slbar,
or
(Z, TO,
SI)
;
Tl, T2, T3);
endmodule if the
What
instantiation
or gate was replacedby
for the
the
following
Verilog
HDL.
instantiation?
or
84
Z (Z,
TO, Tl,
T2,
T3)
;
II
Not
legal
in
2-to-4
A
Decoder
D3
T3
Dl
Tl
D2
T2
DO-
TO
Example
Section
5.12
SO
^
SObar
SI
K>
Slbar
Figure 5-7
the
that the gate is also
cannot
be
.12
A 2-to-4
same
Decoder
Hereis
a
4-to-l
multiplexer.
instance name is alsoZ and the Z. This is not allowedin Verilog module. as a net name within one
Notice
the
A
to the output instance name
net connected HDL.
An
of
Example description
gate-level
of a
2-to-4 decoder
circuitshown
in
Figure
5-8.
DEC2x4 {A, B, A, B, Enable;
module input
output [0:3] wire
not
#
(1,
Z) ;
Z;
Bbar;
Abar,
V0 (Abar,
Enable,
2) A)
,
85
CHAPTER 5
Gate-level Modeling
NO
\\
Z[0]
Nl
\\
Z[l]
\\>4b\302\253r V0/>\302\260
A
i\342\200\224 i
N?\\
i
^^
i\342\200\224
^
B
.
Z[2]
Bbar
Z[3] Enable
5-8
Figure VI
A
2-to-4
decoder
circuit.
{Bbar, B);
nand #(4, 3) NO
(Z[0],
Nl
(Z[l],
N2
(Z[2],
N3
(Z[3]
Abar, Bbar), Abar, B), A, Bbar), A, B) ;
Enable, Enable, Enable, ,
Enable,
endmodule
5.13
A Master-slave Here
is a
Flip-flop Example description
gate-level
of a master-slaveD-type
Figure 5-9.
module
MSDFF
input D,
output
(D,
C,
C;
Q,
Qbar;
not
NT1 (NotD,
D) ,
NT2
C),
(NotC,
NT3 (NotY,
86
Y)
;
Q, Qbar) ;
flip-flop
shown
in
Circuit
A Parity
Figure 5-9 A nand ND1 (Dl,
master-slave
SECTION5.14
flip-flop.
D, C), , Ybar) , Y, D2) , NotD)
C,
ND2
(D2,
ND3
(Y,
ND4
(Ybar,
ND5
(Yl,
Dl,
Y, NotC),
ND6 (Y2,
NotC)
NotY,
(Q,
ND8
(Qbar,
,
Yl) ,
Qbar,
ND7
Q);
Y2,
endmodule
1.14
A Parity A described
Circuit for a
model
gate-level
9-bit parity generator,
shownin Figure5-10,is
next.
module
(D, Even,
Parity_9_Bit
input [0:8]
Odd;
Even,
output
xor #(5,
4)
XEO
(E0,
D[0]
, D[l])
XE1
(El,
D[2],
D[3])
, ,
XE2
(E2,
\302\243>[4] ,
D[5])
,
XE3 (E3,
D[6], D[7]),
XFO
E0,
(F0,
Odd);
D;
El) ,
87
Chapter 5
Gate-level
Modeling
i
DO
XODD
Figure 5-10 XF1
{Fl,
E2, E3),
XHO
{HO,
FO,
XEVEN
parity
generator.
,
Fl) D[8],
{Even,
A
HO) ;
not #2 XODD
Even);
{Odd,
endmodule
5.15
Exercises
1. Modelthe
circuit
bench to test out
shown circuit.
the
in Figure 5-11 using primitive Exercise the circuit with
gates. all
possible
Write
a test
values
of
inputs.
2. Model the circuitofa priority primitive
gates.
Output
Valid
Write a test bench and
88
is 0
verify
in Figure 5-12 using encoder shown it is a 1. when all inputs are 0, otherwise that the model behaves as a priority encoder.
Exercises Section5.15
B[0]\342\200\224-j
A[l]
B[l]
T
3
A[2]
B[2]
A[3]
B[3]3 5-11
Figure
Logic
for A
not
equals
B.
Data[3] Encode[0]
Data[2] -j-\302\243>-
Encode[l] D\302\253te[l]
Valid L\342\200\236 D\302\253fa[0]
Figure
5-12
Priority
encoder.
6
Chapter
Primitives
User-Defined
In
the
HDL. This
by Verilog specifying
user-defined
syntax for
6.1
gates
capability
the
exactly
same
is identical
instantiation
way as
a primitive
to
of
that
gate,
of
that
instantiation.
a gate
using a
is defined
UDP
UDP declarationwhich
has
the
following
syntax.
primitive
UDP_name
( OutputName
Output_declaration
List_of__input_declarations
90
provided
a UDP
Defining A
HDL
Verilog
(UDP).
primitives
UDP
an
the built-in primitive
chapter describesthe
is instantiated
A UDP
we looked at
chapter,
previous
[
Reg_declaration
[
Initial_statement
]
]
, List_of_inputs
);
is, the
Combinational
UDP
SECTION
6.2
table
tries
List_of_table_en
endtable
endprimitive UDP
definition
outside
of a
A appears
text
separate
does
module
and not depend on a module definition can also be definition. A UDP definition
can have
only
one
output
port must be the output port. x (z is not allowed).If a value
1 or
z appears
The following two kindsof behavior /. Combinational.
ii.
the
can
their
is an
0,
as an x.
UDP.
level-sensitive).
In a combinationalUDP, the table specifiesthe specified
is treated
in an
be described
The
have the value
UDP
Combinational
and combinations
or moreinputs.
the output can on the input, it form of a table.
and
(edge-triggered
Sequential
have one
and may
In addition,
The behavior of a UDPis describedin
.2
a
file.
A UDP first
thus in
output values.
corresponding
x for
the output. Hereis an
primitive
(Z, Hab, Bay,
MUX2xl
Any
of a
example
various
combination
2-to-l
input that
is not
multiplexer.
Sel);
Z;
output
Hab, Bay,
input
Sel;
table
//Hab 0
Bay
?
Sel
Z
1
0
1
?
1
1
?
0
0
0
?
1
0
1
0
0
X
0
1
1
X
1
Note:
This
endtable
endprimitive
91
Primitives
User-Defined
character representsa don't-carevalue, of the input ports must match order
The ?
or x.
The
that
first column
the
is,
Olx (there for
other
in
table
the
is no
there
multiplexer,
are others as well);in
this
to the first
table
entry
example of a 4-to-l 2-to-1 using multiplexerprimitives. Here is an
A
the
module is Sel.
In
input combination
defaults to an x (as
also
I
I
I
\\MUX2xl \\muazxi/
MUX2xl
6-1
Figure
A 4-to-l
MUX4xl (Z, C,
B,
A,
A,
B,
6-1, formed
CD
B I
in Figure
shown
multiplexer,
MUX2xl/ Sel[l] _\\^iuA/xi/
input
column
entries).
unspecified
module
in
input
third
one
for
the output
case,
of entries
and the
is Bay
either be a 0, 1 in the table,
it could
is, order
corresponds
is Hab), secondcolumn
port list (which the table for the
that the
Se/[1]
Sel[2]
multiplexer
built
using
UDPs.
D, Sel);
C,
D;
[2:1] Sel;
input
output Z;
parameter MUX2xl
tFALL)
#{tRISE,
{TL, A,
B, Sel[l])
(TP, C,
D,
(Z,
tFALL = 3 ;
- 2,
tRISE
Sel[l])
, ,
Sel[2]) ;
TL, TP,
endmodule In caseofa UDPinstantiation, in value
the
above 0 or
example.
a value
up
1, or the
value
be specifiedas shown can either get a output is no turn-off delay).
to two
This is because the x (there
delays can of
an UDP
SequentialUDP
\342\226\272.3
In a
sequential UDP,the
The
this
of
value
There are
and another the next
determine
to
Initializing the State of a
state
The
initial
i.3.2
models
sequential
UDP, one
the
of the (and
register
level-
models
that
behavior.
edge-sensitive value
current
using a 1-bit register. UDP.
register and
the
input
the output).
consequently
Register UDP can
sequential
be initialized
by
using
an initial
assignment statement. This is of the = 0,
reg_name
statement
initial
This
the
of sequential
that
value of
one procedural
has
statement that
output
UDP uses the
A sequential
of
kinds
different
two
is described
state
internal
is the
register
behavior
sensitive
1.3.1
6.3
UDP
Sequential
values
SECTION
1 or x;
within the UDP
appears
form:
definition.
Level-sensitive Sequential UDP Here
D-type output,
else
is
an
the
of a
example
latch. As
level-sensitive sequential UDP that is 0, data passes from the input
long as the
clock
remains
latched.
value
Latch
primitive
output
Clk,
(Q,
models
a
to the
D);
Q;
Q;
reg
Clk,
input
D;
table
//
Clk
Q(next)
D
Q (state)
:
?
:
1 ;
0
1 0
: ?
:
0 ;
1
p
: ?
:
\342\200\224 ;
0
endtable endprimitive
93
CHAPTER
Primitives
User-Defined
6
The - characterimpliesa stored
6.3.3
in register
the state
of
the
UDP
is
of a
modeled as a D-type edge-triggeredflip-flop is used to initialize the statement sequential UDP. An initial
an
is
that
Note
change\".
Sequential UDP
Edge-triggered Here
\"no
Q.
example
edge-triggered of the flip-flop. state
D_Edge_FF (Q, Clk, Data);
primitive Q;
output
Q;
reg
Data, Clk;
input
initial
Q
=
0;
table
Clk
//
p
O(next) 0
1
?
1
1 0
1
1
0
(01) (Ox) (Ox) //
Q (s tate)
Data
(01)
0
edge of
negative
Ignore
(?0)
0
// Ignore
?
:
?
data changeson : ? :
(? ?)
?
clock:
- ;
:
steady
clock:
\342\200\224 ;
endtable
endprimitive
(01) indicates a
The table entry
a transition 1, or x) to
from 0,
transition, the
0 to
and output
x, the entry (?0)
the entry defaults
Given the UDP definition just like a primitive
a module bit
94
register.
from
transition
indicates a
(??) indicates to an of gate
the
any
1, the entry (Ox) indicates from transition any value (0,
0 to
transition.
For
any unspecified
x. it can now be instantiated D_Edge_FF, in the following example
as shown
in
of a 4-
Sequential
module Reg4
SECTION6.3
Dout);
Din,
(Clk,
UDP
Clk;
input
input [0:3] Din; Dout;
[0:3]
output
D_Edge_FF
Din[0])
,
DLABO
(Dout[0]
Clk,
DLAB1
(Dout[l]
Clk, Dinll]),
Clk, Din[2]),
DLAB2 (Dout[2] DLAB3
Clk, Din[3]);
(Dout[3]
endmodule
5.3.4
Mixing
one
It is
possible to
table.
In such
the
an
primitive
D_
.Async
is,
the
D-type flip-flop
_FF (Q,
and edge-triggered
entries
in
are processed before the levellevel-sensitive entries override the
with
an
asynchronous
clear.
Clk, Clr, Data);
Q;
output
reg
of a
example
transitions
edge
that sensitive onesare processed, edge-triggered entries.
Hereis
entries
level-sensitive
mix
a case,
Behavior
Level-sensitive
and
Edge-triggered
Q;
input
Clr,
Data,
Clk;
table
// Clk
(01)
Clr 0 0 0 0
(01) (Ox)
(Ox)
Data
Q(next)
Q(state)
0
:
?
:
0
1
:
?
:
1
:
0
1:1 0:0
:
1
// Ignore negative edgeof clock: \342\200\242 ?... \342\200\242 ? . _ /\342\200\242 (?0) 0
(??)
1
?
:
?
:
0;
\342\226\240p
1
?
:
?
:
0;
endtable
endprimitive
95
CHAPTER
6.4
Primitives
User-Defined
6
Another
Example
Hereisa UDP
of
description
input vector
a 3-bit
has two or more1's.
primitive
A, B,
Z,
ty3
Majori
.A,
input
circuit. The output
majority
is
1 if
the
C) ;
C;
B,
Z;
output
table
//A 0 0
B
C
Z
0
?
0
?
0
0
0
0
p
0
1
1
?
1
1
?
1
1
1
1
1
\342\226\240p
endtable endprimitive
6.5
Summary For that
could
sake
of Table Entries listed
of completion, be used
in a
Symbol
the
are all the
below
table
Meaning
0
logic 0
1
logic
X
1
unknown
7
any of 0,
b
any of
-
(AB)
96
in
table entry.
no
1,or
x
0 or 1
change
value change
from A
to B
possible values
Exercises
SECTION6.6
Meaning
Symbol
*
sameas (??)
r
same
f
same as (10)
as (01)
P
any
of (01),
(Ox), (xl)
n
any
of (10),
(lx),(x0)
Exercises
1. How is a combinational
2.
A
3.
Can
4.
Write a
5.
data
input
is
0,
clock
negative
6. Modela
Verify
from
a sequential
UDP?
the
to initialize priority
a combinational
encoder
UDP?
circuit shown
in
Figure
using a test bench.
for a toggle-type flip-flop. In a toggle flip-flop, if not change. If data input is a 1, then on every output does that the triggering clock edge is a Assume toggles. output edge. Verify the model using a test bench.
description
clock edge,the
K, are J is 1
be used
the model
a UDP
different
more outputs.True or False?
UDP descriptionfor
Verify
Write
one or
statement
initial
an
5-12.
have
can
UDP
UDP
triggered
rising-edge
does 0, output and K is 0, then
the model
not
JK
change.
output
is
inputs, flip-flop as a UDP. If both If J is 0 and K is a 1, then output 1. If J and K are both 1, output
J and is 0.
If
toggles.
using a test bench.
\342\226\241
97
7
Chapter
Modeling
Dataflow
This
the continuous
describes
chapter
Continuousassignmentsmodel dataflow (the
assignments Combinationallogic
7.1
topic
behavior
assignment feature of Verilog HDL. in contrast,
behavior;
procedural
chapter) model sequentialbehavior. be best modeled using continuousassignments.
of next can
Continuous Assignment A assign
continuous a value
to a
assignment assigns a value to a net (it cannot be used to register). It has the following form (a simple form):
= RHS__expression;
LHS_target
assign
Forexample, wire
[3:0]
assign 98
Z
Z,
Preset,
= Preset
&
Clear; Clear;
// Net //
declaration.
Continuous
assignment.
Continuous
of
The target continuous
is Z and the right-hand assignment Note the presence of the keyword assign
continuous
the
& Clear\".
\"Preset
expressionis
7.1
side in the
assignment.
assignment execute? Whenever
a continuous
does
When
a change of value)
event is
on
occurs
an operand used and if the result
expression, the expression is evaluated then assigned to the left-hand side target.
In
above
the
event
(an side
right-hand
value is different,
it is
Z.
net
the
a continuous
in
can be
assignment
one of the
following.
net
Scalar
i.
an the
if either Preset or Clear change,the entire rightis evaluated. If this results in a change of value, then the
resultant value is assignedto The target
in
example,
side expression
hand
SECTION
Assignment
ii. Vector net
Hi. Constantbit-selectofa vector iv. Constant of a vector part-select of any
of the above
Here are more examplesof continuous
assignments.
Concatenation
v.
BusErr
assign
Z
last continuous
The in
assign
A, B,
C, D, and
evaluated
= -
= Parity (A
\\
(C
| D)
&
;
OP)
(E
\\
F)
;
assignment executes whenever there is a changeof value the entire right-hand side expressionis which case, to the target Z. result is then assigned
the
target
is a
concatenation
+ B
+ Cin;
of a scalar net
and
a
net.
wire
Cout,
wire
[3:0]
assign
Since of
&
&
E or F, in
In the next example,the vector
B)
| (One
A
a 5-bit
and 4 bits
Cin; Sum,
{Cout,
A,
B;
Sum) = A
B are 4-bits wide, the result of addition can producea maximum result. The left-hand sideis specifiedto be five bits (one bit for
and
of
Sum).
The assignment
therefore causes
the
rightmost
four
Cout
bits of
99
CHAPTER
Dataflow
7
Modeling
the right-hand side expressionresult to (the carry bit) to Cout.
The next example shows
how
be
can be
assignments
multiple
and the
to Sum
assigned
bit
fifth
in
written
one
statement.
continuous
assign
=
Mux
(S ==
0) ? A : == 1) ? B : == 2) ? C : == 3) ? D :
Mux = (S
This is a short
Mux
=
(S
Mux
=
(S
'bz;
the following
of writing
form
'bz,
'bz, 'bz, four separatecontinuous
assignments.
assign
assign assign assign
7.2
An
== 0) (S == 1) (S == 2) (S == 3)
Mux = (S
?A
Mux = Mux = Mux =
?B ?C
:
?D
:
:
'bz;
:
'bz; '
bz ;
'bz;
Example
Hereis an exampleofa 1-bitfull-adder module input
(A,
FA_Df A,
B,
the dataflow
using
style.
Sum, Cout) ;
Cin,
B,
described
Cin;
output
Sum, Cout;
assign
Sum
assign
Cout
= A A B A Cin;
= (A
&
Cin)
|
(B
&
Cin)
|
(A
&
B)
;
endmodule
In this
example, there are two
concurrent assignments
hand evaluated,
in
the
execute
continuous
assignments.
These
side expression. If A changes, side that is, the right-hand
assigned to the left-hand
are
assignments
These
that they are order independent. based on events that occur on operands
sense
side targets
both
the continuous
expressions are evaluated concurrently.
continuous
used
in
the
right-
assignments are and
the
results
are
Net
7.3
Net Declaration continuous
A
SECTION7.3
Assignment
Assignment can appear as part of a is called a net declarationassignment.
assignment
an assignment
Such
Declaration
itself.
declaration
net
is an
Here
example.
wire
Sum = 4 ' bO ;
[3:0]
wire Clear =
wire A net assignment. continuous
'bl; > B,
= A
A_GT_B
= B
B_GT_A
> A;
declaration assignmentdeclaresthe net along It is a convenient form of declaringa net and the example
See
assignment.
with then
a continuous writing a
below.
wire Clear;
assign Clear to the net
is equivalent
wire Clear
=
=
'bl;
declaration assignment: 'bl;
net declaration
Multiple
assignments on
multiple assignmentsare necessary,continuous
7.4
the
same
net
are not must
assignments
allowed. If be used.
Delays If no delay is specifiedin examples,
the
of the
assignment
target occurs
zero
with
continuous assignment
assign
as shown
#6
Ask
delay.
a continuous
assignment,
as
in
the
previous
right-hand side expressionto the left-hand A delay can be explicitlyspecifiedin a
in the = Quiet
side
following example. \\ \\
Late;
101
Chapter
Dataflow Modeling
7
the right-hand side and the leftThe delay specified,#6,is the delay between on Late at time 5, then occurs the hand side. For example, if a change of value is evaluated at time 5 and on the right-hand side of the assignment expression is Ask will be assigneda new value at time 11 (= 5 + 6). Thedelay concept in
illustrated
7-1.
Figure
Quiet
20
10
Late 15 6
*- 6
,
Ask
11
What
propagate to applied.
if the
happens
Here
the
is an
side? that
continuous assignment.
side changes before it had a case, the latest value
right-hand
left-hand
example
>6
Delay in a
7-1
Figure
-
In such shows
this
a chance change
to
is
behavior.
#4 Cab = Drm;
assign
7-2 shows the effect. The changes on the right-hand side that occur within the delay interval are filtered For example, out. the rising edge on Drm at 5 gets scheduled to appear on Cab at 9, however since Drm goes back to 0 at 8, the scheduled value on Cab is deleted.Similarly, the pulse on Drm 18 and 20 gets filtered out.This corresponds to the inertial delay occurring between that is, a value on the right-hand side must hold steadyfor at behavior; change least the delay period before it can propagate to the left-hand side; if the value on the right-hand side changes within the delay period, the former value does Figure
not
propagate
to the
output.
For each delay specification, up
/. Rise
delay
ii.
Fall
delay
Hi. Turn-off
102
delay
to
three
delay
values can
be specified.
7.4
SECTION
Delays
Drm
5
8
18
13
Cab
26
20
4
L
4..^
Lj 1
\342\226\240\"
30
17
is the syntax
Here
Here are three
delay
for specifyingthe
#( rise
assign
, fall ,
some examplesthat
#4
Ask
interval.
delays.
turn-off how
show
= Quiet
assign #(4, 8)
Ask
assign #(4, 8,
6)
assign Bus = first
three
delay
)
= RHS_expression
LHS_target
delays
;
when zero to
are interpreted
are specified.
values
assign
In the
Values changing faster than
7-2
Figure
^
'
\\ \\
= Quick;
-
Arb
the transition to x
&
:4]
MemAddr[7
DataBus;
;
delay are
II
One delay
value.
II
Two delay
values.
II
Three
//
No
delay
values.
delay
value.
delay, the fall delay and
the rise
statement,
assignment
Late;
turn-off
the
second is 8 and the transition to x and z the same, which is the minimum of 4 and 8, which is 4. In the third delay are the rise delay is 4, the fall delay is 8 and the turn-off assignment, delay is 6; the transition to x delay is 4 (the minimum of 4, 8 and 6). In the last statement, all and
delay
statement, the rise delay
is 4,
the
same,
which
is 4. In the
the fall delay
delaysare zero. What
a rise
does
goes
from a
hand
side
delay mean
non-zero
value
value
to
goes to z, then
for a vector net target? If the
a zero
vector, then fall delay
turn-off delay is used;elserise
right-hand
side
is used. If rightdelay
is used.
103
CHAPTER
7.5
Dataflow
7
Modeling
Net Delays A
can
delay
also be
specified
a net
in
such as
declaration,
in
the
following
driver
for
declaration.
wire
#5 Arb;
This delay indicatesthe and
the net Arb itself.
a change
between
delay
Consider
the
of value of a
continuous
following
assignment
Arb
to the
net Arb.
assign An
event
on Bod, If
evaluated.
the
= Bod
Arb
#2
say
result
at
&
Cap;
10, causes
time
is different,
it
is
the right-hand side expressionto be to Arb after 2 time units, that assigned
12. However since Arb has a net delay specified, the actual net Arb occurs at time 17 (= 10+ 2 + 5). The waveforms in assignment to the the different delays. 7-3 illustrates is,
at time
Figure
Cap
20
40
Bod 10
Arb
3
0
, 7 .
.r 7 >
47
17
Figure 7-3
Net
delay
with
assignment
delay.
The effect of a net delay is best described as shown in is used then and assignment delay any net delay is added
If a delay net delay but for
104
A,
2 time
is present an
assignment
units is the
Figure
7-4. First the
on.
declaration assignment, then the delay is not a delay. In the following net declarationassignment
in a net
assignment delay,not
the
net
delay.
SECTION7.6
Examples
wire
A =
#2
B
- C;
II
delay.
Assignment
Driver 1 Net
target <\342\200\224Net
assign delay
RHS
assign delay
RHS expression
delay
Driver
K6
Examples
f.6.1
Master-slave Flip-flop Here
is
for
HDL model
a Verilog
2
Effect of net delay.
7-4
Figure
Figure
expression
master-slave
the
flip-flop
shown
in
5-9.
module
output
D,
C;
Q, Qbar;
wire NotC,
assign assign
assign assign assign assign assign assign assign
assign assign endmodule
Q, Qbar) ;
(D, C,
MSDFF_DF
input
NotD
Y, Dl,
NotY,
NotD,
= ~
D2, Ybar, Yl, Y2;
D
Note = ~ C NotY
= ~
Y
Dl = - (D & D2 = ~ (C & Y = ~ (Dl St
C)
;
NotD) Ybar)
Ybar = ~ (Y & D2) Yl = ~ (y & Note) Y2 = - (NotY & NotC) Q = ~ (Qbar & Yl) ;
Qbar =
~
(Y2
;
& Q) ;
105
DataflowModeling
Chapter 7
7.6.2
Comparator
Magnitude
Here is a dataflow
a 8-bit
for
model
(parameterized) magnitude
comparator.
module
AgtB, AeqB, AltB) ;
(A, B,
MagnitudeComparator
parameter BUS= 8;
parameter input
7.7
= 5,
EQ_DELAY
[1 : BUS]A,
LT_DELAY = 8,
GT_DELAY
= 8;
B;
AeqB, AltB;
output
AgtB,
assign
%EQ_DELAY
AeqB
= A ==
assign
$GT_DELAY
AgtB
= A
assign $LT_DELAY endmodule
AltB
=
B; > B; A < B;
Exercises
1.
an
Give
of how
example
turn-off delay
is used in
a continuous
assignment.
2.
3.
When
there
effective
value
are two for
the target model
a dataflow
Write
or more assignmentsto the
10. Use only two
same
target,
how is the
determined?
for the parity generator
circuit shown in
Specify rise and
assignment statements.
fall
Figure
5-
delays
as
well.
4.
Using continuousassignmentstatements, priority
circuit
encoder
shown
in Figure
describe
the
behavior
5-12.
5. Given: triO
Qbus;
[4:0]
assign
Qbus =
assign Qbus What is the
106
-
Sbus; Pbus;
value on Qbus if
both
Pbus
and Sbus
are all z's.
of the
8
Chapter
Modeling
Behavioral
In and
chapters,
previous UDP
assignments.
This
chapter
which is, behavioral may
5.1
describes
of all the
examined gate-level modelingusing gate modeling using continuous in Verilog HDL, of modeling style of Verilog HDL, a model use the full power
dataflow the third To
modeling.
a mix
contain
we have and
instantiations,
three styles of modeling.
Procedural Constructs The
primary
following
two
mechanisms
for modeling
the behavior
i.
Initial statement
ii.
Always
statement
number of initial These statements execute concurrently with to respect order of these statements in a module is not important. A
module
of a design are the
statements.
may contain an arbitrary
or
always
each An
other,
execution
statements. that
is,
of an
the
ini-
107
CHAPTER
8
Behavioral
tial or an statements
8.1.1
Modeling
starts always statement execute concurrently
control flow.
a separate at
starting
All
initial
and
always
0.
time
Statement
Initial
only once. It
executes
statement
initial
An
which is at time
simulation
0. The syntax
begins its executionat initial
the
for
statement
start
of
is:
initial [
] procedural_statement
timing_control
is one of:
a procedural_statement
where
procedural_assignment (blockingor non-blocking) procedural_continuous_assignment
conditional_statement
case_statement
loop_statement
wai t__statement
disable_statement even t_ trigger
sequential_block
parallel_block
statement. Here
to becometrue. The statement
to execute
time 0. It
may
controls
complete
in the
present
Here is an
example
reg Yurt;
initial Yurt
108
most
the
timingjcontrolcan be a delay
event control,
or an
time,
system)
block (begin...end) is
The sequential certain
or
(user
task_enable
= 2;
that
of
execution
once. Note execution
an that
at
control,
for an
procedural statement. of an
used
procedural
for a event to occur or a condition initial statement causes the procedural an initial statement starts execution at a later time dependingon any timing
wait
is,
commonly
initial statement.
that
is, wait
Procedural
The initial
statement
contains
The
statement
executes
initial
value 2
no
with
control.
timing
the assigned this time
control.
a timing
with
assignment
which causes Yurt to be is another example of an initial statement,
0. Here
time
at
a procedural at time 0,
SECTION8.1
Constructs
reg Curt;
initial = 1;
Curt
#2
Curt gets assignedthe at time 0 but completes
Register execution
Here is an
initial
a sequential
with
starts
statement
block.
SIZE = 1024;
parameter
reg [7:0] RAM[0: reg
execution
2. The at time 2.
time
initial statement
of an
example
1 at
value
SIZE-l];
RibReg;
initial
begin:
SEQ_BLK_A
Index;
integer
= 0;
RibReg
for (Index = 0; Index]
RAM[
Index
<
SIZE;
= Index
Index
+ 1)
= 0;
end
The sequential block, demarcatedby such as
language label
is
example,
if
by a all
integer
programming
memory
Here is another
locations example
has been locally declared block containsoneprocedural
Index
the sequential
for-loop statement.
this example, the timing
a high-level
is the label for the sequential block; this local declarations are present in the block, for for Index were outside the initial no label statement,
required. An
Furthermore,
initializes
in
C. SEQ_BLK_A
required declaration
the
followed
as
contains
begin...end,
keywords
sequentially,
if no
not
would be block.
execute
that
statements
procedural
the
This initial
with value of an
statement,
upon
within
this
assignment
execution,
0.
initial statement
with
a sequential
block.
In
sequential blockcontainsproceduralassignmentswith
controls.
109
CHAPTER 8
Behavioral Modeling
//
Waveform
generation:
APPLY_DELAY = 5 ;
parameter
reg [0:7] Port_A;
initial
begin =
Port_A
'h20;
%APPLY_DELAY Port_A
= ' hF2 ;
#APPLY__DELAY
Port_A
=
#APPLY_D\302\243L.AY
Port_A
= 'hOA;
'h41;
end
Upon execution, Port_A
will
get
as shown
values
in
8-1.
Figure
Port_A
'hF2
'h20
Figure 8-1 initial
An generation
8.1.2
shown
as
10
5
0
A
'hOA
\"h41
waveform
using
produced
statement is mainly used in the examples above.
15
an
initial
and
initialization
for
statement.
waveform
Always Statement In
to the
contrast
the initial
like
Just repeatedly.
time 0. The syntax
for
initial statement, an
always statement
statement, an always an always
statement
statement
executes also
begins
execution
is:
always [
where
timing_control
procedural
] procedural_statement
^statement and
timing^controlare as describedin
previous section.
Here
110
is an
example of an
always
statement.
the
at
Procedural
always Clk =
- Clk;
II Will
This always
SECTION8.1
Constructs
loop indefinitely.
assignment. Since the always control the is no specified, repeatedly timing will loop indefinitely in zero time. Therefore, statement procedural assignment always statement must always have some sort of timing control. statement
one procedural
has
statement
and there
executes
HeFe is the
same
always #5 Clk =
II
this time
statement,
always
with
a delay
of period
Clk
on
10.
This always statement, upon execution,producesa waveform 10 time units. an
event
reg [3:0] wire
always statement
with
with
a sequential
a period
block
of
that is
control.
InstrReg;
[0:5]
reg
of an
example
controlled by an
control.
~ Clk;
Waveform
Hereis
an
Accum;
ExecuteCycle;
always
@(ExecuteCycle)
begin
case (InstrReg[0:1]) Store
(Accum,
InstrReg[2:5]);
2'bOO
:
2'bll
: Load (Accum, InstrReg[2 : Jump (InstrReg[2 :5]) ;
2'bOl
:5])
;
2'blO : ; endcase end
//
Store,
//
tasks
Statementswithin respect
to each
Load and
defined
block
a sequential
other. This
occurs on ExecuteCycle,that
user-defined
are
Jump
elsewhere.
always is,
execute sequentially with that whenever an event implies changes, execute the sequential
(begin...end)
statement
whenever
it
111
CHAPTER
8
Behavioral
Modeling
of the
block; execution withinthe
block
block
sequential
executing
implies
all statements
sequentially.
another example.The model is that D-type flip-flop with an asynchronous preset. Here is
DFF {Clk, D, Clk, D, Set;
module input
output
Set,
Q,
Qbar)
of
a negative
edge-triggered
;
Qbar;
Q,
Q, Qbar;
reg
always
wait (Set
==
1)
begin
1; #2 Qbar = #3 Q=
0;
wait (Set
==
0)
;
end
always
@(negedge
Clk)
begin
if (Set != 1)
begin #5
Q =
D;
#1 Qbar =
~Q;
end end endmodule This module has
two
statement
8.1.3
has
first
block.
a sequential with
always
statement
The second
a sequential
has
a
always
block.
In One Module module
A
statements.
starts
contain
may Each
execution
Here is an statements.
112
with
timing control
an edge-triggered
The
statements.
always
level-sensitive event control
statement
at time example
multiple always statements and multiple initial Each starts a separate control flow. statement
0. of a
module
with
one
initial
statement
and two always
module
SECTION
Constructs
Procedural
8.1
TestXorBehavior;
reg Sa, Sb, Zeus;
initial
begin = 0 ;
Sa
Sb = 0;
#5 Sb =
1;
= 1;
Sa
#5
#5 Sb =
0;
end always @
or
(Sa
Zeus =
Si?)
Sa
A
Sb;
always
@(Zeus)
$display
time
(\"At
Sa,
$time,
Sa = %d,
%t,
Sb = %d, Zeus =
%b\",
Zeus);
Sb,
endmodule
The orderof the three statements execute concurrently. The initial
in the
module is not
since
important
they
the
causes
executed
when
statement
all first
in the sequential block to execute, that is, Sa gets assigned 0; the after next statement executesimmediately line zero delay. The #5 in the third a \"wait for a 1 of the initial statement indicates 5 time units\". Thus Sb gets another 5 time units and finally a 0 after 5 time Sb gets units, Sa gets a 1 after block is after another 5 time units. After the last statement in the sequential the initial statement forever. executed, suspends statement
statement waits for
The first always Whenever
such and
executed
event
an
the
event
an
the statement
within
to occur the
always
on Sa or Sb. is
statement
always
statement again waits for an on the values assigned to Sa and based statement will be executed at times
the always
then
Sb. Noticethat statement,
occurs,
on Sa or
to occur
event Sb
in the
0,
5, 10
initial
and 15 time
units. Similarly
the
second
always
on Zeus. In
such a case, the
statement
waits
always
the when
again
statement
Sdisplay
system
for an event
waveforms produced on Sa, the module is simulated.
Sb and
executes whenever an event task is executed and then
to occur on Zeus.Figure Zeus.
Here
is the
output
occurs the
8-2
shows
produced
113
CHAPTER
8
Behavioral
Modeling
At time
5, Sa
= 0, Sb=
l,Zeus= 1
10,Sa=l.Sb=l.Zeus =
time
At
At time
= 0,
15, Sa=l,Sb
0
Zeus= 1
Sa Sb
Zeus
15
10
8-2
Figure
8.2
timing
control
may
be associated
control is of two forms:
8.2.1
i.
Delay
control.
ii.
Event
control.
Delay Control A
delay
control
is of the
form:
tidelay procedural_statement
as in
the
example:
#2
114
Sa,
Sb and
Zeus.
Controls
Timing A
Waveforms producedon
Tx =
Rx- 5;
with
a procedural
statement.
Timing
control specifiesthe
A delay
before executing the
reached;
it
is
to wait
equivalent
8.2
statement is \"wait
means
above example, the
two time units for 2 time units and
is executed
statement
procedural assignment
In the
statement.
the time the
executes. Basicallyit
time the statement
to the
encountered
initially
for delay\"
from
duration
time
SECTION
Controls
Timing
after then
statement
the
is
the
execute
assignment.
is another
Here
example.
initial
begin Wave
#3
=
#6 Wave = Wave
#7
'bOlll;
'bllOO;
= 'bOOOO;
end
The initial statement executesat time 0. First, wait for 3 time units, execute the first assignment, wait for another 6 time units, execute the second statement and then suspend for 7 more time units, execute the third statement, wait
indefinitely. A
delay
can also
control
be specified in
form:
the
#del ay ;
This statement is executed.
causesa wait
Here
for
is an example
the
specified
of such an
ON_DELAY = 3,
parameter
delay before the
next statement
usage.
= 5;
OFF_DELAY
always
begin #
II
ON_DELAY;
RefClk
wait
for
ON__DELAY.
for
OFF_DELAY.
= 0;
# OFF_DELAY; = 1;
II wait
RefClk
end
The delay not be
in
a delay
control
can be an arbitrary
restricted to a constant.Seethe
following
expression, that
is,
it need
examples.
115
BehavioralModeling
CHAPTER8
^Strobe
= Tx
Compare
Clock = ~
Clock;
of the
value
delay expression
An
explicit at
If the If
the
zero
delay
the
current
time does
simulation
value
delay
all causes a wait until time are simulation
other
an explicit
zero
that are waiting
to be
is called
events
completed, before it
the
resumes;
not advance.
of a
value is used as the
is the
same
the
two's
as zero
delay.
complement
delay.
Control
Event
With an event
two kinds of event i.
control, a
event
Edge-triggered
An
edge-triggered
@
as in the
event
control control
event
control
procedural_statement
example: @
(posedge
Curr^State
based
Control
Event
Edge-triggered
executes
statement
control.
ii. Level-sensitive event
116
it
delay expression is an x or a z, it evaluates to a negative value, expression
signed integer
8.2.2
is 0, then
// Explicitzerodelay.
#0; executed
Mask;
I 2)
#(PERIOD
If the delay.
A
Clock)
= Next_State;
is of the
form:
on events.
There are
Timing Controls An
control
event
statement
until
delays the execution
statement
a procedural
with
of the specified
occurrence
the
SECTION
event. In
the
above
of the if a
example,
statement executes, positive edge occurs on Clockthe assignment execution is suspendeduntil a positive edge occurs on Clock.
8.2
otherwise
Hereare somemoreexamples. @
Count
i?eset)
(negedge
= 0;
GCla
Zoo = Foo;
In the
first
the assignment
statement,
edge occurs on Reset.In the event occurs on Cla, that is, occur, assign Foo to Zoo.
@
event
exampleof
causes a wait
an usage
such
for
wait
also be
statement executes only when a negative an Foo is assigned to Zoo when an event to occur on Cla, when it does
statement,
of the form:
;
statement
This
can
control
Event
second
in
until
the
specified
statement
initial
an
clock.
event occurs. Here is an that determines the on-period
of a
time RiseEdge,
OnDelay,
initial
begin
// Wait @
until positive edge on = $time;
RiseEdge
// @
Wait
until
negative
edge on
clock occurs:
ClockA);
(negedge
OnDelay
occurs:
clock
ClockA);
(posedge
= $time
$display
(\"The
- RiseEdge;
on-period
of
clock
is %t.\",
end can
Events shown
in
the
also
following
be or'ed
to indicate
\"if
any
of the
OnDelay);
events occur\".
This is
examples.
117
CHAPTER
8
Behavioral
Modeling
@
Clear
(posedge
or negedge
Reset)
Q = 0; @
or
(Ctr1_A
Dbus = ' bz;
Note that
the
and
edge
following
or does not
keyword
posedge positive
Ctr1_B)
imply a logical-orsuchas in
and negedge are keywordsin Verilog a negative edge respectively. A negative
expression.
a of the
indicate
that
HDL
an
is one
edge
transitions:
x
1 ->
1 -> z
1 -> 0 x -> 0
z
A positive
->
0
edge is one of the following
0 ->
x
0 ->
z
->
1
x ->
1
0
transitions:
z -> 1
Level-sensitive
Control
Event
In a
level-sensitive becomes
a condition
wait
event control, true. This
the
is delayed
statement
procedural
event control is written
in
until
form:
the
(condition)
procedural_statement The procedural statement executes only until the condition becomes true. If the statement is reached,then the procedural The proceduralstatement is optional. Here
118
are some
examples.
if the
condition is
condition
statement
true,
is already
is executed
else
it waits
true when the
immediately.
Block
8.3
SECTION
Statement
(Sum > 22)
wait
= 0;
Sum
wait
{DataReady)
Data = Bus;
wait (Preset); first
the
In
assignment
DataReady execution is
5.3
simply delayeduntil
true.
becomes
Preset
Statement
Block
a provides like a single
statement
block
A
act
to
only when Sum becomes greater than 22 will the Sum occur. In the second example,Bus is assignedto Data only if the is true, that is, DataReady has the value 1. In the last example,
statement,
0 to
of
syntactically
Verilog HDL.
i.
mechanism to group two or more statements
statement. There are two
in
of blocks
kinds
These are: block
Sequential sequentially
the
in
ii. Parallel
are executed
Statements
(begin...end):
order.
given
block (fork.,join):Statements
in
this
execute
block
concurrently.
can be
block
A
labeled optionally. If so labeled,registerscan be declared for a block. Blocks can also be referenced; example,
can be
disabled using a disablestatement.
a
to
way
All local
registers are static,
Sequential
previous
syntax
of a
a
sequential
is relative
statement
with
is,
block
label,
However, there their
values
in addition,
is one word
remain
valid
sequence.
A
of
block
provides caution. the
throughout
Block
Once
statement.
continues
that
A
run.
Statements in each
registers.
identify
uniquely
simulation
entire
8.3.1
the
within
locally
the
next
sequential
block
execute
in
delay
value
in
to the simulation time of the executionof the block completes execution,execution
a sequential
statement
following the
sequential block.Hereis the
block.
119
CHAPTER
8
Behavioral
Modeling
begin [ : block_id
{ declarations
)
]
(s)
procedural_statement
end
Here is an
//
example of a sequentialblock.
Waveform
generation:
begin
= 1;
#2 Stream
= 0;
Stream
#5
#3 Stream = #2 Stream = -
Stream
#5
1;
= 0;
Stream
#4
1; 0;
end gets executed at 10 time units. The first executes after 2 time units, that is at 12 time units. After this statement execution has the next statement is executedat 17 time units (because of completed, so on. is executed at 20 time units and the delay). Then the next statement the waveform due to the Figure 8-3 shows produced sequential execution
Assume
behavior
the
that
of
this
block
sequential
example.
Stream
10 12 8-3
Figure
17
Delays are cumulative
Here is another exampleof a sequential begin
Pat @
= Mask
FF = end
120
&
| Mat; Clk)
(negedge Pat;
20
24
in
block.
26
a sequential
31
block.
SECTION8.3
Block Statement
In this example, the Of
executes.
statement
when a negative
first and then the
executes
statement
first
the assignment in on Clk. Here appears
the
course,
edge
second
statement
second occurs only
is another exampleof a sequential
block.
SEQ_BLK
begin:
[0:3]
reg
Sat
=
FF =
Mask A
Sat; & Data;
Sat;
end
blockhas a label SEQ_BLK declared. is register Upon execution,the first statement example, the sequential
In this
second
2
and
executed,
a local then the
it has
is executed.
statement
Block
Parallel A
block
parallel
concurrently.
has the
delimiters fork and join
begin and end). Statements
the delimiters
values
Delay
specified
in each
in
a parallel
statement
within
(a
sequential
block
has
block execute a parallel
block
are
in the the time the block starts its execution.When the last activity block has execution need not be the last statement), (this completed parallel executioncontinuesafter the block statement. Stated another way, all within the parallel block must complete executionbeforecontrol statements passes of a parallel block. out of the block. Here is the syntax relative
to
fork { declarations
: block__id
[
procedural_statement
} ]
(s)
join
Hereis an //
example.
Waveform
generation:
fork #2
Stream
= 1;
#7 Stream = 0 ;
#10 Stream = #14
Stream
1;
= 0;
121
CHAPTER
8
Behavioral
Modeling
#16 Stream =
1;
#21 Stream=
0;
join
parallel block gets executedat 10 time and all delay values are relative to concurrently If the
assignment
and so on.Figure
all statements
10.Forexample, the
time units, the fifth assignment executes shows the waveform produced.
at 20
executes
units,
8-4
execute third
at 26
time units,
Stream
Figure Here is an emphasize
8-4
Delays
that
example
uses
24 26
20
17
12
10
relative
are
always #4
SEQ_A
= 5;
Dry
fork:
begin:
= 7;
// PI
SEQ_B
//
P2
Box;
//
S6
= Exe;
//
S7
3;
Exe = #5
SI
// S2
PAR_A
Cun
#6
//
Jap
end #2 Dop = Gos
#4
#8 Pas
//
P3
= 2 ;
//
P4
= 4;
//
P5
join #8
Bax
= 1;
#2 Zoom = #6
end
122
$Stop;
52;
parallel block.
of sequentialand
a mix
their differences.
begin:
in a
// S3
//
S4
//
S5
31
parallel
blocks
to
SECTION8.4
Procedural Assignments
Gos
= 2
Dop = 3 Cun =
7
= 5
Dry
8 9
10
28
22
2D
Pas = 4
= Box
Exe
12
$stop
= l
Bax
Zoom
= 52
Jap = Exe
Figure 8-5 Delaysdue
The always the
within
the
always
a mix
of sequential
block
statement
executes at time 0,
the
within
block PAR_A parallel
and parallel blocks.
a sequential block SEQ_A and all (SI, S2, S3, S4, S5) execute sequentially.
sequential
and the parallel statements
contains
statement
to
begins
block (PI,
its
Dry gets assigned execution
5 at
at 4 time
statements Since
4 time units,
units.
All
P2, P3, P4, P5)execute
concurrently,
that
units. Thus Cun gets assigneda value at 10 time units, Dop gets at 12. The Gos gets assigned at 8, and Pas getsassigned 4 sequential block starts at time execution units, SEQJi causing statements S6 and at 9. Since all statements within the then S7 to execute. Jap gets its new value block PAR_A complete execution at time S3 is executed 12, statement parallel at 12 time to Box occurs at 20, then statement S4 executes, units, assignment the assignment to Zoom occurs at 22, then the next statement executes. Finally the task at 8-5 shows events that occur executes time 28. system $stop Figure statement. upon the execution of the always is, at
4 time
assignedat
6,
Procedural A
procedural
Assignments assignment
is an
assignment
always statement. It is usedto assign hand side of the assignment can be any
to
only
expression.
within
an
a register Here
initial
statement
or an
data type. The rightis an example.
123
Chapter 8
Behavioral
Modeling
reg
[1:4]
#5
Enable
is then
side expression A statements
& -
B;
is initially
executes
it. Here
around
appear
its value
and
The
encountered.
right-hand
is assigned to Enable.
sequentially
is an
statement
the assignment
control,
delay
evaluated
assignment
procedural that
A
after the statement
units
5 time
executes
-
=
B;
A,
register.Due to the
is a
Enable
Enable,
with
example
to other
respect
always statement.
of an
always @
C or
B or
or
(A
Temp2;
Tempi,
reg
Tempi = A
& B;
Temp2 = C & D; = Tempi Tempi Z = ~ Tempi;
end
/* It is Z
= -
the
second
within
block
on A, B,
the always
occurs.
There are two
value
of Tempi
the
124
illustrate
the
to
such
sequential
takes
Tempi
of Tempi and
third
computed
assignment in
the
third
Temp2
place first.
an
Then
computed
statement.
in
The last
statement.
kinds of proceduralassignments.
i.
Blocking.
ii.
Non-blocking.
before we discuss these, let us intra-statement delays.
But
as
to
The values
assignment are used in
assignmentusesthe
with
statement starts execution when
C or D.Theassignment
assignment
the previous
statements
nature of the statements in a
block*/ occurs
four
above
such as:
((A & B) | (C Sc D)) ; it has been used here
sequential
sequential
Temp2;
the
However,
event
\\
possibleto replace
one statement,
The
D)
AOI
begin:
first
briefly
discuss
the
notion
of
Procedural
Intra-statement A
is an
Delay on the
appearing
delay
intra-statement is
it
The important
statement
assignment
delay by which the right-hand the left-hand side target. Hereis an
about this delay is that the delay, then the wait
delays and
inter-statement
in an
expression
to note
before
to the left-hand
assigned
an
side
is
value
example.
'bl;
thing
evaluated
to
applied
= #5
Done
left of
It is the
delay.
delayed before
expression is
8.4
SECTION
Assignments
the
right-hand
occurs and
then
side is
value
the
side target. To understand the difference intra-statement delays,hereare someexamples
between that
this.
illustrate
Done -
// Intra-statement
#5 'bl;
delay
control.
the same as:
//is
begin =
Temp
'bl;
// Inter-statement delay control.
= Temp;
#5 Done
end Clk)
@(posedge
Q=
//is
the
D;
II Intra-statement
event control.
// Inter-statement
event control.
as:
same
begin
Temp = D; @
Clk)
(posedge
Q = Temp;
end In
form
to the
addition
control)
that
called
can
the repeat
delay.It is of the repeat
two forms of timing controls for intra-statement specified
event control that
can
be
(delay
control
and event
delay, there is yet another used to specify intra-statement
form:
( expression
)
@
)
( event_expression
form of control is usedto specify a delay of or more occurrences one events.Hereis an This
of
be
that is
based on the
number
example.
125
CHAPTER 8
Behavioral Modeling
Done = repeat (2) @
This statement when executedevaluates + BJieg, waits for two negative is, A_Reg the
assigns
event
repeat
A__Reg + B_Reg;
ClkA)
(negedge
value
the
of the
right-hand side, ClkA and then
edges
right-hand side to Done. Theequivalent is shown next. example
of the
value control
that
on clock
of this
form
begin + B_Reg;
= A__Reg
Temp @
{negedge
ClkA);
@
(negedge
ClkA);
= Temp;
Done
end
This form or with a count 8.4.2
Blocking A
is useful
delay
Procedural
executed.
in which
edges
operator is an
\"=\"
is a
=52;
before
assignment.A
any
statements
of the is
statement
executed
is another
Here
that
@
(A
or
B or
begin.reg
example.
Tl =
Cin)
CARRY__OUT
Tl,
A
T2,
end
T3;
& B;
T2 = B & Cin; T3 = A & Cin; = Tl Cout |
blocking follow
completely
always
126
the assignment
procedural assignment. For example,
blocking procedural
assignment
to certain
assignments
synchronizing
Assignment
assignment
RegA
executed
in
of edges.
procedural
blocking
is a
of
T2 | T3;
procedural it are
assignment
executed,
that
before the next
is,
statement
is the is
Procedural
The 77
assignment occursfirst,
executes,
72
assigned,
and
then the second
is computed,
is executed
statement
third
8.4
statement and T3 is
so on.
is another
Here
77
and then the
is assigned
SECTION
Assignments
intra-statement
example of a blockingprocedural
assignment
using
delays.
initial
begin
Clr=
#5
Clr=
#4 1;
0;
Clr = #10
0;
end executes at time 0 and Clr gets assigned 0 after 5 time statement the then second statement executes Clr to a units, get assigned 1 after causing 4 time units (9 time units from time 0), and then the third statement executes 10 time units (19 time units from time 0). The causing Clr to get a 0 after is on Clr in waveform shown 8-6. Figure produced first
The
Clr
19
Figure 8-6 Blockingprocedural assignmentswith is another
Here
intra-statement
delays.
example.
begin Art
= 0;
Art
= 1;
end In this case, assigned
0,
then
Art
gets
assigned
the next
delay.Thereforethe
the value
1. This
statement executes
assignment
of 0
to
Art
that
is
is because,first
causes
Art
Art
to get 1
gets
after zero
lost.
127
BehavioralModeling
CHAPTER8
8.4.3
Non-blocking Procedural Assignment In
a non-blocking
used.Here
are
begin Load <= RegA
assignment,
procedural
some
of non-blocking
examples
symbol \"<=\"is procedural assignments.
the assignment
32;
<= Load;
RegB <= Store;
end In a non-blocking procedural not
blocked
(due
to delays)
the assignment to occur in the
assignment, but
are
scheduled
to the target future
(based
is on
the delays; if zero delay,then at the end of the current time step).When a nonis is the side executed, right-hand blocking procedural assignment expression evaluated and its value is scheduled to be assigned to the left-hand side target, and executioncontinueswith the next statement. The earliest an output would if be scheduled is at the end of the current time this case would occur step; there were no delay in the assignment At the end of the current statement. time are the assignment to the leftscheduled, step or whenever the outputs hand
side
target
occurs.
In the above example, let us assume that the sequential block executes at time 10. The first statement causes the value 32 to be assignedto Loadat the end of time 10, then the second statement the old value of Load is executes, used (notethat time has not advanced and Load in the first assignment has not the assignment to RegA is scheduled at the yet been assigned a new value); end of time step 10, the next statement and RegB is scheduledto be executes assigneda value at the end of time 10. After all events at time 10 have all scheduled to the left-hand side target are made. occurred, assignments Here
is another
example that
initial
begin
Clr <= #5 Clr
<= #4
1;
0;
Clr <= #10 0;
end
128
explains
this
further.
Procedural
Assignments
SECTION
8.4
be scheduledto appear on Clr at 5 time units, the execution of the second statement causes Clr to get a the execution of value 0 at 4 time units units from time 0), and finally (4 time a 0 to be scheduled on Clr at 10 time units (10 time the third statement causes from 0. In addition, units 0). Note that all the three statements executeat time notice that the order of execution of non-blocking assignmentsbecome on Clr. irrelevant in this case. Figure 8-7 shows the waveform produced of
The execution
a 1 to
causes
statement
first
the
Clr
10
0
Figure
8-7
Here is another
this time
but
example,
with intra-statement
assignments
Non-blocking
with
zero
delays.
delays.
initial
begin
Cbn <= 0; <=
Cbn
1;
end
The value HDL
occur in value
of Cbn after
standard
0
the first
the
all
order and
then
[0:2]
statement
non-blocking
is 1 since the Verilog to a variable shall assignments
executes
statements are executed.Thus, Cbn
gets
the
1.
Here is an example that and highlights their differences. reg
initial
specifies the assignment that
uses
both
blocking
and non-blocking
assignments
CLState;
initial
begin
Q_State = Q_State
3'b011;
<= 3'bl00;
129
CHAPTER
Behavioral
8
Modeling
Q_State is
(\"Current value of $display Wait for some time. #5; //
$display
is
of Q_State
value
delayed
(\"The
CLState)
%b\",
;
%b\",
Q_State);
end
of the
The execution
statement
initial
Current value of The
The blocking executionof
the
time step (which
QJState
has
still
the #5
delay is executed,this
occur,
QJState
and
the
then
value of
8.4.4
causes
assignment
value
the
is
011
of Q_State is 100
to get the value of 3'b011.The which is a non-blockingone, second statement, assignment 3'bl00 to be scheduled for QJState at the end of the current is 0). Therefore when the first $display task is executed, the value from the first is 3'b011. When which assignment,
first
causes
QJState
value
delayed
the result:
produces
gets updated next $display
QJState
the
causes
new
its
with
task is
assignment of Q_State to a delay of 5 time units occurs time the updated displaying
scheduled value,
executed,this
QJState.
Continuous Assignmentvs ProceduralAssignment between
differences
the
are
What
Table8-1 assignments? 8-1
Table
Difference between
Procedural
Occurs inside initial
continuous assignments and procedural
this.
illustrates
procedural and continuous
Continuous assignment
assignment
an always
assignment.
statement or
an
Occurswithin
a module.
statement.
Execution
is
with
to other
respect
statements
it.
surrounding
Executes concurrently
with
executes
whenever
change
of value
in
an
right-hand side. Drives
registers.
Uses \"=\"
or \"<=\" assignment
No assign keyword continuous assignment;
130
Drives
(except see
symbol. in a procedural Sec. 8.8).
Uses
nets. \"=\"
assignment
Uses assign
keyword.
other
there is a on its operand
statements;
symbol.
Conditional
Here is an
explaining
example
this difference
Statement
SECTION8.5
further.
module Procedural;
reg
B,
A,
Z;
always
@(B) begin = A;
Z
A = B;
end
endmodule
module Continuous;
wire
Z;
B,
A,
assign assign
= A;
Z
A = B;
endmodule time 10ns. In moduleProcedural,the two sequentially and A gets the new value of B at 10ns. Z does not get the value of B since the assignment to Z occursbeforethe to A, In module Continuous, the second continuous assignmentis assignment triggeredsincethere is an event on B. This in turn causes an event on A, which which in turn causes the first continuous assignment to be executed, causes Z to get the value of A which is really B. However, if an event occurred on A, the statement in module Procedural does not execute since A is not in the always control event list for that However the first statement. timing always in the module Continuous executes and Z gets the continuous new value assignment
Say that
B has
an event at executed
are
procedural statements
of A.
8.5
Conditional
The
syntax
Statement of
an
if
statement
is:
if ( conditional )
procedural_statement__l { else if condition^ ) (
131
BehavioralModeling
CHAPTER8
}
procedural_statement_2 [ else
}
procedural_statement_3
known then the evaluates to a non-zero value, conditional or evaluates to a value x is executed.If conditional 0, procedural_statement_l and an if it is not else the executed, branch, z, procedural_statement_l
If
if
is an example.
Here
is executed.
exists,
<
(Sum
60)
begin
Grade =
C;
Total_C =
+ 1;
Total_C
end
else if
< 75)
[Sum
begin
Grade =
B;
Total_B =
+ 1
Total_B
;
end
else
begin Grade =
A;
= Total_A
Total__A
+ 1;
end
Note that Also
as shown
in
if
condition
the
is a
there
possibility
this
expression for
an
ambiguity
must always be within if an if-if-else
parenthesis. form
is used,
example.
(Clk)
if
(Reset)
2=0;
else Q
= D;
is to which if doesthe last condition (Clk) or to the second
The question
first if resolved
in
Verilog
not have an statement.
132
else.
else if
by associating the else In this example, the else
HDL
to the belong? Does it belong condition (Reset)! This is with the closest if that does
is associatedwith
the
inner
if
Case Statement more examples of
are some
Here
if
8.6
statements.
< 100) + 10;
(Sum
= Sum
Sum
if
if
SECTION
(Nickel_In)
Deposit if
else
=
5;
{Dime_In)
=10;
Deposit
else if
(Quarter_In)
= 25;
Deposit
else
Deposit if
=
ERROR;
(Ctrl)
begin
if
(~Ctrl2) Mux
= 4 '
d2 ;
= 4 '
dl ;
else Mux
end
else
begin
if
(~Ctr22)
Mux
= 4 '
d8 ;
= 4 '
d4 ;
else Mux
end
.6
Case Statement A
statement
case
is a
multi-way conditional
branch.It has the
following
syntax:
case
( case_expr
case_item_expr
)
{,
case__item__expr
}
: procedural_statement
133
CHAPTER
Behavioral
8
Modeling
[ default:
procedural_statement
]
endcase
The caseexpression isevaluated evaluated
and
compared
Next
first.
order given.
in the
the case
item expressions are
The set of statements
that
match
the
can be is executed.Multiple case item expressions The default specified in one these values need not be mutually-exclusive. branch; case covers all values that are not covered by the case item expressions. nor the case item expressionsneedbeconstant Neitherthe case expression In a case statement, the x and z values are comparedas their expressions. literalvalues. Here is an example of a case statement. first true condition
parameter
MON =
WED =
2,
: Pocket_Money =
6;
0,
=
TUE
1,
THU= 3, FRI = 4, SUN = 6;
= 5,
SAT
reg [0:2] Day;
integer case
Pocket_Money;
(Day)
TUE
// Branch 1
MON,
WED
:
= 2;
Pocket_Money
II Branch
2
FRI,
SAT,
: Pocket_Money =
SUN default
:
Pocket_Money
7;
// Branch 3
= 0;
// Branch 4
endcase Branch2 is chosenif values FRI, the
SAT,
while
SUN,
111. Here
bit-vector
module
ALU
the value
[3:0]
input
[1:2] OpCode;
reg
[7:0]
Z;
Z;
WED.
Branch
Z)
3 covers
the
remaining values, THUand
exampleof a casestatement.
[A, B, OpCode, A, B;
input
MON or
4 covers the
branch
is another
output [7:0]
134
has
Day
Case Statement
8.6
SECTION
parameter
= 2'blO,
ADD_INSTR
SUB_INSTR= 2'bll, = 2'b01,
MULT_INSTR
= 2'b00;
DIV_INSTR
always @
or
[A
B or
OpCode)
case (OpCode) + B
ADD_INSTR:
Z
A
SUB_INSTR:
Z
A-
MULT_INSTR:
Z
A
DIV_INSTR:
Z
A I
B; * B
B
endcase
endmodule
case expressionand the case item expressions are of aremadeequal to a situation, all case expressions of any of these expressions beforeany comparisons are made.
What happens if the different
the
lengths?
largest
Here is an
such
In
size
example that
case
(3'blOl
illustrates
this.
\302\253 2)
branch
taken!
3 'blOO
\342\200\242. $display
(\"First
4'bOlOO
:
$display
5'bl0100
:
$display
branch (\"Second branch (\"Third
default
: $display (\"Defaultbranch taken!\;
endcase
taken! taken!\;
\")
; \")
;
produces:
Third
branch
taken!
Since the third case item expression is of size 5 bits, all caseitem expressions and the case expression are made equal to size 5. So when 3'blOl \302\2532 the result is 5'bl0100, and the third branch is taken. computed,
is
135
CHAPTER
8.6.1
Behavioral
8
Modeling
in Case
Don't-cares
the values x and z In case statement described in the previous the section, other of forms are interpretedliterally, that is, as x and z values.Thereare two z x for and case statements', casex and casez, that use a different interpretation identical to that of a case statement except for values.The syntax is exactly the
In a any ignored
casex
keywords
casez statement, the item
case
In a
expression
appears
in
the
case
is considered as a don't-care,that
casex statement, both an
z that
value
expression is,
that
and
in
bit is
compared).
(not
Hereis
and casez.
example
of a
values
the
x and
z are
considered as don't-cares.
casez statement.
casez {Mask)
4'bl??? : Dbus[i] =
4'bOl??
:
4'bOOl? : 4'bOOOl
:
Dbus[3]
Dbus[2] = Dbusll]
0;
= 0; 0;
= 0;
endcase z to imply The ? charactercan be used instead of the character a don't-care. if the first bit of Mask is 1 (other The casez statement example implies that of Mask bits are ignored), then 0 is assignedto Dbus[4],if first bit of Mask is 0 and the second bit is 1 (other bits are ignored),then Dbus[ 3] gets assigned the value 0, and so on.
8.7
Loop
Statement
Thereare four kinds of loop i. Forever-loop
136
ii.
Repeat-loop
Hi.
While-loop
/v.
For-loop
statements.
These are:
LoopStatement 1
SECTION
8.7
Statement
Forever-loop
The syntax for this
of
form
is:
statement
loop
forever
procedural_statement
This loop statement
the procedural statement. Thus to be used with the procedural may
executes
continuously
out of such a loop, a disable statement statement. Also, someform of timing controls must be used in in zero otherwise the forever-loop will loop forever statement, Here is an example of this form of loop statement.
get
the
procedural
delay.
initial
begin
Clock = 0; #5
forever
# 10
=~
Clock
Clock;
end This examplegeneratesa clockwaveform; stays
2
at
0 until
5 time
units. After
Clock Clock
that
toggles
first
gets every
initialized to 0 10 time units.
and
Repeat-loop Statement of loop
form
This
has the form:
statement
repeat ( loop_count) procedural_statement
statement
the procedural
It executes
count expressionis an
x or
a z,
then
some
the
the
specified
loop
count
number
is treated
If loop as a 0. Hereare
of times.
examples.
repeat
(Count)
Sum = Sum +
repeat P_Reg
10;
(ShiftBy) =
P_Reg
\302\2531
;
137
CHAPTER 8
Behavioral Modeling
The repeat-loopstatement
from
differs
which meansfor
Count
Sum.
increment
occurs,
Sum =
to
(Count) @ (posedge event control
repeat
then
Sum
compute
to left-hand
assign
the
does
What
repeat
for positive
wait
times,
1;
edge of Clk and
Sum + 1;
Clk)
+ 1 first, then wait for
Count positiveedgeson
Clk,
side. mean?
following
;
ClockZ)
@(negedge
(NUM_OF_TIMES)
to wait for NUM_OF_TIMES negative the statement following the repeat statement. It means
8.7.3
this
when
Whereas,
// Repeat means
Sum = Sum +
Clk)
(posedge
Consider,
// Repeat-loopstatement.
repeat (Count) @
event control.
repeat
clock
edges
before
executing
While-loop Statement The
of this
syntax
form of
( condition
while
loop statement
is:
)
procedural_statement
This loop executesthe statement
If the
false.
becomes
is
procedural
expression If the
executed.
never
Hereare someexamples. while
(By>
0)
begin
Ace By
end
138
- Ace << 1; = By
- 1;
statement
until
the specified
is false to begin with,
condition is an
x or
a z,
then
the
it
is treated
condition
procedural as a 0
(false).
Continuous
Procedural
7.4
SECTION 8.8
Assignment
Statement
For-loop
This loop statement
is of
the form: ) ; condition ; step_assignment
for ( initial_assignment procedural_statement
A for-loop certain
repeats the execution of the procedural The initial_assignment specifies the
statement of times.
number
loop index. The condition
specifiesthe
when
condition
statement initial
loop
value
execution
a of the
must
is true, the statements in the loop are executed. stop. As long as the condition The step_assignment specifiesthe assignment to modify, typically to increment
or
the step
decrement,
integer
K;
(K =
for
count.
0;
K
K = K +
< MAX_RANGE;
1)
begin
if
{Abus[K]
==
Abus[K)
= 1;
else
if
0) ==
(Abus[K]
1)
= 0;
Abus[K]
else
$display
an x
is
(\"Abus[K]
or a z\") ;
end
S.8
Continuous Assignment
Procedural A
continuous
procedural
can appear
within
an
always
is a procedural assignment,that is, it assignment or an initial statement statement. This assignment
all other assignmentsto a net or a register. It allows the to be driven continuously into a register or a net. Note, assignment a continuous a continuous assignment occurs outside assignment;
can override expressionin
the
this is not
of an
initial
or an
always statement.
There are two kinds i. assign and
of procedural deassign
continuous
procedural
assignments.
statements:
these assign to
registers.
139
Chapter
8
Behavioral Modeling
ii. force and nets, though
The
of operand in the
while
redone
the
side
right-hand
used for registers.
are \"continuous\"
statements
or force
assign
also be
can
expression
is in
these assign primarily to
statements:
procedural
they
force
and
assign
release
in
the
sense
8.8.1
to
change be
effect.
target of a procedural continuousassignmentcannot bit-select of a register.
The
or a
that any
causes the assignment be
a part-select
Assign - deassign An
register.
The
module
statement
procedural
deassign
The value
a register.
DFF
overrides all procedural assignmentsto a ends the continuous assignment to is retained until assigned again.
statement
procedural
assign
the
in
(D,
register
Q) ;
Clk,
Clr,
D, Clr, Clk;
input
Q;
output
Q;
reg
always
%(Clr) begin
if (! Clr)
//
assign 0=0;
D
has
no
effect
on Q.
else
deassign
Q;
end
always @
Q = D;
Clk)
(negedge
endmodule
If Clr is 0, the of irrespective
1, the
deassign
so that
If an
in
the
assign
edges, statement
future
140
that
is,
causes Q to be stuck at 0 have no effect on Q. If Clr becomes this causes the override to be removed,
statement Clk
and D
is executed;
Clk can
is applied
before making the example.
procedural
assign
clock
any
effect Q.
to an already
assigned register,it
is deassigned
new proceduralcontinuousassignment. Hereis another
first
Continuous
Procedural
SECTION8.8
Assignment
reg [3:0] Pest;
Pest
=
0;
assign
Pest
= Hty
assign
Pest
= 2;
A
// Will deassign
Pest[2] assign cannot be
Pest
continues to
// Pest
Pest;
deassign
Mtu;
then
and
assign. 2.
value
have
= 1; /* Error: Bit-select of a register a target of a procedural continuous
assignment*/ second
The
the
2
value An
another
until
first
assign
to be
to the in
assign
to
keep
register occurs. the
sense
that after the
second assign getsexecuted, any to be
statement
before
deassigned
Pest continues
is executed,
deassign
is \"continuous\"
and before the
Mtu will cause the
the
assignment
statement
assign
is executed
the first
will cause
statement
assign
making the next assign.After
first
assign
on Hty
change
or
reevaluated.
Force - release
Theforce
release
and
except
deassign,
that
statements
procedural
release
and
force
can be
are very
applied to
similar to nets
and
assign
as to
as well
registers.
The
of the release unless
force
register to be overridden by the on the register is executed,the continuous
a procedural
force statement the
establishes
A until
when applied to
statement,
force
new
value
procedural
a release
wire
or #1
assignment
was executed)in
procedural
of the
which
a register,causesthe
current
value
force expression. When a is held in the register was already in effect (at the time the the continuous case, assignment
value
current
of the value
register. on a
statement
statement
net overridesall the
is executed on that
drivers
for
the net
net.
Prt;
(Prt, Std,
Dzx)
;
141
CHAPTER
Behavioral Modeling
8
initial
begin
force Prt
=
& Std;
Dzx
// Wait
#5; release
for
time
5
units.
Prt;
end
The executionof the forcestatement value
from
which
the
the force
gate primitive from the or
assignmentis in
Hereis
another
to be
statement takes
primitive
5 time
(first
of Prt to override the is executed, upon back its effect. While
value
units), any changes on
Dzx and
executed again.
example.
Colt;
[2:0]
reg
effect
release
the
gate
of Prt
driver
the
causes until
the assignment
cause
Std
the or
Colt = 2;
force Colt = release
1;
retains
II Colt
Colt;
value 1.
assign Colt- 5; = 3;
Colt
force
release
Colt
force
II Colt gets
Colt; [1:0]
continuous
=3;
assignment
register first
The
release
at
the
time
force
no
again.
142
/* Error: target of a procedural be a part-select cannot of a
causes the value of
procedural
continuous
was applied. In the
value 5 becausethe
5.
value
*/
of Colt
becausethere was
the
procedural
Colt to
be
assignment
latter releasestatement,
continuous
assignment
This is to the applied register
retained
Colt
on Colt
(as 1). gets
back
becomes active
the
A Handshake
.9
A
Handshake
Always statements can for
within
a module
registers that are visible to use registers declared
using
recommended
of hierarchical
use
the
through
of interacting
behavior
information between always
to pass
statement
other
each
with
always statements. It is not always
the
capture
path names,
statements
described
in
10).
Chapter
the following example of two a microprocessor. The RX
Consider and
receiver,
and
communicate
is possible
(this
be used to
interacting finite-state machines.Thesestatements
that of
example,
an
within
8.9
SECTION
Example
processes,
to all the
Example
sends
a signal MP
The
process.
MP,
block
The
after
it
back
to the
Ack,
signal,
acknowledge
data.
Ready indicating
process,
that
assigns
the
data
the
data
RX
process
the serial
reads
data
input
read into the MP to the output, sends an to begin reading new input
can be
for the two processes is shown
diagram
RX, a
processes:
interacting process
in
Figure
8-8.
Ready
Serial_In
>
Out
Process
^^ *
MP,
Ack
Clk
Figure
The behavior following
Parallel
Data
RX
Process
design
for
these
8-8
Two interacting
two
interacting
processes.
processes
is expressed
in
the
description.
Ins
\"timescale
/ lOOps
module Interacting {Serial_In,Clk, Parallel__Out); Clk;
Serial_In,
input
[0:7]
output
Para 11el_Out;
reg [0:7] Parallel_Out;
reg wire
Ready,
[0:7]
\"include
Ack;
Data; \"Read_Word.v\"
//
Task
Read_Word
// this file.
is defined
in
143
Chapter
8
BehavioralModeling always
RX
begin:
Clk, Data);
{Serial_In,
Read_Word
data on every task reads the serial II Read_Word converts data in to a parallel // clockcycle // signal Data. It takes 10nsto this. The
and
do
1;
Ready=
wait
{Ack); Ready = 0;
#40;
end always
MP
begin:
#25;
-
Parallel_Out Ack
Data-,
= 1;
#25 Ack wait
=
0;
;
{Ready)
end
endmodule The shown
two
these
of
interaction
in the
waveforms
in
processes
via registers Ready and
RX reading new
serial data i
1
V
Ack
8-9.
Figure
Ready
10
6'5
75
1 50ns
140
Ack
25
0
50
100
Data
Figure
144
8-9 Handshaking protocol
125
output between
175 by MP the
two processes.
200ns
is
Exercises
L10
8.10
SECTION
Exercises
1. Which statement executesrepeatedly, 2.
a sequential
between
difference
the
is
What
using an example. Can a sequential
Explain
statement?
or always
initial
block and
block
appear
block?
a parallel
a parallel
within
block?
3.
4. Is it 5.
a label
is
When
delay?
an
in
an
between
difference
the
statement
a delay
to specify
necessary
What is
for a block?
required
statement?
always
delay and
intra-statement
an
inter-
Explain using an example.
6.
How
are
blocking
7.
How
does
the
8.
Can
a net
9.
Generate a clock waveform
different
assignments
statement
casex
from non-blocking assignments?
differ from the case statement?
type (for e.g. a wire) be assigned
in
an always
of 5ns
an off-period
with
statement?
and an
on-period
of
10ns.
10. Express the forever
following always
statement
an
using
initial
statement
and a
statement.
loop
always @
or
{Expected
if
{Expected
$display
Observed)
!== Observed) begin Expected
(\"MISMATCH:
= %b,
Observed
=
%b\",
Observed);
Expected,
$StOP;
end
11.
the
What
are
always
statements
edge
at time
two and NextStateBin the following conditions: ClockP has a positive of 5 prior to the clock edge and 5ns; CurrentState has a value
of NextStateA
values
changes3ns after
the following
under
the
clock
edge
to 7?
always @
(posedge
ClockP)
#7 NextStateA
= CurrentState;
145
Chapter8
Behavioral
Modeling
always @
ClockP)
(posedge
= #7
NextStateB
12. Write
a model
state
followingfinite
using the machine.
Inp (Gak)
0 1
0 1 0 1 0 1
13. Describethe 14. Describe
NO_ONE
NO_ONE
0
NO_ONE
ONE_ONE
0
ONE_ONE
NO_ONE
0
ONE_ONE
TWO_ONE
0
TWOJDNE
0 1 0 NO_ONE THREE_ONE 1
the
of a
input
Usg. The
(Zuk)
NO_ONE THREE_ONE
JK flip-flop
of a circuit that
the
describe
Output
behavior
on
style to
NextState
TWOJDNE THREE_ONE THREEJDNE
falling clock edge.
15.
behavioral modeling
PresentState
the behavior
1011is found
CurrentState-,
using an sets
the
data on the
always
output input
statement.
Asm to 1 if a pattern on every is checked
the behavior of a majority circuit. The input is a 12-bit vector. If the number of 1's exceedsthe number of 0's, the output is set to 1. The is checked only when Data_Ready is a 1. input data Describe
146
9
Chapter
Modeling
Structural
This
Structural
is described
modeling \342\200\242 Gate
instantiation
\342\200\242 UDP
instantiation
\342\200\242 Module
Chapters
5 and
structural
modeling style of
Verilog
HDL.
using:
instantiation
6 have
chapterdescribesmodule
).l
the
describes
chapter
discussed
gate-level
modeling
and UDP
modeling. This
instantiations.
Module A module module
defines a basic unit module_name
in
Verilog
( port_list
HDL.
It is
of the
form:
);
Declarations_and_Statements endmodule
147
CHAPTER
Structural
9
Modeling
The port list
9.2
communicates
module
the
which
modules.
external
the
with
gives the list of ports through
Ports A
port
However,
as
be declared
can
be explicitly
it can
A port by
or inout.
output
input,
declared as a net. An
output
default is a net. inout port can
or an
optionally be redeclaredas a regregister.In either the net declaration or the register declaration, the net or register must have the same size as the one in the port declaration. Hereare someexamples ofport declarations. specified module II
NextAddr) \342\226\240,
Micro {PC, Instr, declarations: Port
input
[3:1] PC;
output [1:8] Instr;
inout [16:1]
NextAddr;
II
Redeclarations:
wire
reg
[16:1]
[1:8]
I* Instr
must NextAddr; II Optional; but if specified // have same range as in its port declaration. Instr;
has been redeclared
assigned a value within statement. */
an
as
a
always
reg
so
statement
that
it can be or an initial
endmodule
9.3
Instantiation
Module
A module A
module
module_name
148
can be instantiated
instantiation
statement
instance_name
in
another
is of the
module,
thus creating
form:
( port_associations
);
hierarchy.
ModuleInstantiation can be by positionor by name; is of the form: association
associations
Port
be mixed. A
port
port_expr . PortName
where
can be any
port_expr
i.
an
)
( port_expr
identifier
however,
//
By
position.
II
By
name.
SECTION
9.3
cannot
associations
of the following: or a
(a register
net)
ii. a bit-select Hi.
a part-select
iv.
a concatenation
v.
an
In positional module
the
in
two
ports)
input
association, the port expressions connectto the ports order. In association by name, the connection specified
port and the port is not associations port
using
for
(only
expression
module of
of the above
half-adder
module
important.
modules;
HA
is explicitly Here is an
expression
of the between
the
specified and thus the order example of a full-adderbuilt
the logic diagramis shown
in
Figure
9-1.
B, S, C);
{A,
A, B;
input
S, C;
output
parameter
AND_DELAY
assign
#XOR_ .DELAY
assign
#AMD_
.DELAY
= 1,
XOR_DELAY
S =A
A
C= A
&
B;
B;
endmodule
module
FA
output
Q, Cin, Q, Cin-,
(P,
P,
input
Sum,
wire SI,
II
Two
-,
Cout;
OR_DELAY = 1;
parameter
HA hi HA h2
Sum, Cout)
CI, C2;
module
instantiations:
{P, Q, SI, CI); (.A(Cin), .S{Sum),
// Associating by
position.
.B(S1), .C(C2)); //Associating
11
by
name.
149
CHAPTER 9
Structural Modeling
// Gate instantiation:
or
01
#OR_DELAY
CI,
(Cout,
C2) ;
endmodule
Q
-A\342\200\224
hi
C
CI Cin
S
I
SI
CI
Sum
01 Cout
Figure 9-1 In the
module
first
A
full-adder
using
half-adder
HA is the
instantiation,
modules.
name of
the
module,
hi
is the
that is, P is connected to ports are associatedby position, is connected to module SI to 5 and CI to B, A, Q port port module port association is by name, that C. In the second instantiation, the port is, the connections the and the are module between (HA) ports port expressions
instance name and module
(HA)
specified
explicitly.
Here is another exampleof a
instantiation
module
that
uses
different
forms of port expression.
Micro
Ml
This
instantiation
bit-select to an
150
input
expression
port.
UdOut[0:7],
shows
(Status[Q]),
RdN}), or an
{WrN,
(Udln[2:0], &
Status[0],
Status[l]
,
can be an identifier (TxData),a a concatenation ({WrN, (Udln[3:0]), part-select an expression can only be connected (& UdOut[Q:7]); that
a
RdN),
TxData);
a port
expression
\302\273.3.1
Ports
Unconnected
Unconnected
ports
dl
DFF
the
//Byname.
;
// the
is
Preset
Input
instantiations, module
Unconnected
outputs are
By position.
//
Output Qbar is not connected.
//
port
example.
;
CK)
specified by leaving the
.Data(D),
(), . Clock(CK))
(QS, , D, ,
DFF d2
following
.QbarO,
(.Q(QS),
. Preset
both
in
can be
instantiation
an
in
such as
blank,
expression
In
SECTION9.3
Instantiation
Module
and hence
open
set to value z.
ports Qbar
and Presetare not
inputs are
driven
value
to
connected.
module
z. Unconnected
simplyunused.
>.3.2 DifferentPort Lengths When
matching
a port and the local port expressionare of different lengths, port or truncation. Here is is performed by (unsigned) right justification
an example of port matching.
module Child (Pba, Ppy)
;
Pba;
[5:0]
input
[2:0] Ppy;
output
endmodule module Top; wire
[1:2]
Bdl;
wire
[2:6]
Mpr-,
CI
Child
{Bdl,
Mpr) ;
endmodule In the module
are
not
connected to
connected
Ppy[0],
for
instantiation
Bdl[\\]is connectedto and
Mpr[5]
Pba[\\].
therefore
Child,
Bdl[2]
Remaining
input
have the value
is connected
Ppy[2]. See Figure 9-2.
is connected
to Pba[0] and
ports, Pba[5],
Pba[4], Pba[3]
z. Similarly,Mpr[6]
to Ppy[l]
and
Mpr[4]
is
is
connected
to
151
CHAPTER
9
Structural
Pba
Modeling
4
5
3
1 0
2
A
/\\
1
2
1 0
2
Ppy
V
Bdl
Mpr
Figure 9-2 9.3.3
When a moduleis instantiated
can changethe
done
in
of the
value
in
V
V
5
6
4
matching.
another
parameters
two
ways.
i.
Defparam
u.
Module instanceparameter
module, a lower
in
the higher level module.
level module This can be
statement value
assignment
Statement
Defparam A
Port
3
Values
Parameter
Module
2
is of the
statement
defparam
form:
defparam hier_path_namel = valuel , = value2,.
hier_path_name2
.
. ;
in a lower level path names of the parameters such a statement (hierarchicalpath names in the next chapter). Here is an example. Modules FA and HA in this declared section. previously
The hierarchical explicitly
set
by using
module TOP {NewA, NewB; input NewA, output
NewS,
NewB,
NewS,
NewC) ;
= 5,
Parameter XOR_DELAY Hal.AND_DELAY= 2;
HA
Hal
152
are have
NewC;
defparam Hal. XOR_DELAY
endmodule
module can be
//
in
instance
Hal.
II Parameter AND_DELAY
in
instance
Hal.
{NewA,
NewB,
NewS, NewC) ;
described been
TOP2 (NewP, input NewP, NewQ,
module
NewSum,
NewCin,
9.3
NewCout) ;
NewCin;
NewCout;
NewSum,
output
NewQ,
SECTION
Instantiation
Module
II ParameterXOR_DELAY defparam Fal.hi.XOR_DELAY=2, instance hi of instance Fal. 11 in = 3, Fal. hi. AND__DELAY / / Parameter AND_DELAY hi of instance Fal. instance 11 in = 3;
Fal.OR_DELAY
Fal
FA
NewQ,
{NewP,
Parameter
//
OR_DELAY
Fal.
instance
in
11
NewCin,
NewCout)
NewSum,
;
endmodule
In this instantiation section,
but
Value Assignment
Parameter
Instance
Module
parameter values are Here itself. are the same examples as this time, module instance parameter value
T0P3
module
input
NewB,
{NewA,
NewS,
shown
in
the
the
assignment
module
previous is used.
NewC) ;
NewB;
NewA,
NewC;
NewS,
output
specifiedin
new
the
method,
HA* (5, 2) Hal {NewA, NewB, NewC); NewS, II First value, 5, is that for parameter AND_DELAY, first II the parameter declared in module HA. II Second value, 2, is that for parameterXOR_DELAY, the second II parameter declared in module HA. endmodule
T0P4
module
(NewP,
NewP,
input
def param
Fal. hi. XOR_DELAY 11
instance
in
Fal. hi. II
FA
#(3)
II
Fal
Value
NewSum,
NewCin,
NewCout);
NewCin;
NewCout;
NewSum,
output
NewQ,
NewQ,
in
AND_DELAY
= 3 ;
instance
hi of
{NewP,
3 is
= 2,
hi of
the
II
value
for
XOR_DELAY
/ /
Parameter
AND_DELAY
instance Fal.
NewQ, NewCin, new
Parameter
instance Fal.
NewSum,
parameter
NewCout);
OR_DELAY.
endmodule
153
Chapter 9
Structural
Modeling
values in
of the parameter
order
The
parameters declared
The two modules, TOP3 and instance
value
parameter
assignment
has
TOP4,
illustrate
the
can be
used only
to
down one level of hierarchy (e.g. OR_DELAY), statement can be used to override parameter values at
Note that
the
delay specified module instantiation since delays way as that for a gate instantiation. in
any
M-by-N
generic
values
the
defparam of the hierarchy.
level
values appearsidenticalto is no case for concern in a in the
a module
is an
example
same
that
multiplier.
{Opd_l, Opd_2,
module Multiplier EM =
parameter
module
that
parameter
pass
cannot be specifiedfor
Parameter values could alsorepresentsizes.Here models a
fact
whereas
for specifying parameter This a gate instantiation.
notation
of a
that
In
module.
5 and XOR_DELAY
set as
been
has
AND_DELAY
match the order of the module TOP3, been set as 2.
must
instantiation
the
lower-level
the
in
4,
= 2;
EN
//
Result);
Default
values.
input [EM-.l]Opd_l; 0pd_2;
[EN-.l]
input
output
[EM+EN
assign
Result
:
Result;
1]
= Opd_l
*
0pd_2;
endmodule
parameterized multiplier can now be instantiated is an instantiation of an 8-by-6 multiplier.
This
wire
[1:8]
wire [1:6] wire
[1:14]
The
first
value
6 specifiesa new
154
design.
Here
Pipe_Reg; Addr_Counter; Ml
a new
8 specifies value
another
Dbus;
#(8, 6)
Multiplier
in
for
{Pipe_Reg,
value for
parameter
EN.
Dbus,
parameter
Addr_Counter); EM
and the
second value
External Ports
.4
SECTION
9.4
Ports
External
In the module definition we have visible outside the module.
of ports
module
input
Ctrl;
input
[8:0]
Ctrl,
{Arb,
Scram_A
input [0:3]
so far,
seen
the port list
describes the
list
For example,
Mem_Blk, Byte);
Arb;
Mem_Blk;
output [0:3] Byte;
endmodule
The
module
external ports, specifythe
of an
are
ports
that
Ctrl, Mem_Blk and Byte.Theseare alsothe are used to instantiation, the externalport names when associating name. Here is an example ports by
Arb,
is, in an
interconnections
of module Scram_A.
instantiation
SX
Scram_A
,
{.Byte(Bl)
.Mem_Blk{Ml),
.Ctrl(CI)
, .Arb(Al));
In module Scram_A, the external are implicitly specified. Verport names HDL an explicit way to specify external port names. This is provides ilog a port of the form: doneby specifying
. external_port_name ( internal_port_name) Here
is the
same example,
but
this
time
the external
ports are explicitly
specified.
module
Scram_B
(.Data(Arb),
.Mem_Word{Mem_Blk), input
[0:3]
input
Ctrl;
.Control{Ctrl), .Addr{Byte));
Arb;
input [8:0] Mem_Blk; output
[0:3]
Byte;
endmodule
155
Structural Modeling
Chapter 9
Scram_B
Control, Mem_Word the
between
need not
has external
ports specifiedin this case which are Data, list explicitly shows the connections external ports and the internal Note that the external ports ports. declared whereas the internal ports of the module must be
module
The
be
Addr.
and
The port
are not visible within the module but are used the module instantiation whereas internal ports must be declared within are visible within In a the module since the module. module instantiation, they are used as shown in external the following ports example. external
The
declared.
ports
SI
Scram_B
two
) ;
of notation cannot all ports in a
types
definition, that
is,
either
names specifiedor none Externalport
not used
a module
list for
a port
definition
must have
have explicit
port names.
module
in
module
explicit port
if module
instantiations
ports
position.
port name
internal
be mixed in
must
them
are
names
are being connectedby An
of
a
.Data(Dl), .Control{CD,
(.Addr(Al), .Mem_Nord{Ml)
The
in
can
not
only
be
an identifier,
it
can
also
be one
of
the following. \342\200\242 a bit-select \342\200\242 a
part-select
\342\200\242 a concatenation
Here
is an
of bit-select,
part-select and
identifier
example.
module Scram_C (Arb[0:2],
Ctrl, Mem_Blk[l]},
[Mem_Blk[0],
[0:3]
input
Syte[3]);
Arb;
input Ctrl;
input [8:0] [0:3]
output
Mem_Blk;
Byte;
endmodule
definition
a part-select (Ctrl), (Arb[0:2]), ({Mem_Blk[0], Mem_Blk[\\]}) and a bit-select (Byte[3]).In the case where the internal port is a bit-select, no external part-selector a concatenation, port name is implicitly specified. in such a module instantiation, module be must connectConsequently, ports In the module an
156
identifier
for
ScramjC,
the
a concatenation
port
list contains
External Ports ed
associations. Here
positional
through
is an
of
example
9.4
SECTION
an
such
instantiation.
SYA
Scram_C
In
this
L/[4:6] connected to
instantiation, is connected
Mem_Blk[0],
CL, MMy[l:0], BT)
[4:6],
(LI
;
thus, ports are connected by positional associations; to Arb[0:2], CL is connected is to Ctrl, MMY[\\] to Byte[3]. MMY[0] to Mem_Blk[\\], and BTis connected
Touseassociation
in this situation (where an internal port is not names must be explicitlyspecifiedfor the ports in identifier), port the module. This is shown in the following module definition for Scram_D. by
name
external
an
module Scram_D
,
(.Data(Arb[0:2])
.Control(Ctrl),
Mem_Blk[1]}),
.Mem_Nord([Mem_Blk[0],
.Addr{Byte[2]));
input [0:3] input
Ctrl;
input
[8:0]
Arb;
Mem_Blk;
output [0:3] Byte;
endmodule In the or by
for
instantiation
name,
but
not
are connected by
module
mixed.
Here
Scram_D, ports can is an example of an
be connectedby
position
where
instantiation
ports
name. SZ
Scram_D
(.Data{Ll[4:6]),
,
.Control(CL)
.Mem_Word(MMY[l:Q]), .Addr(BT));
It is possiblefor a module to have an external port Here is an example of sucha module. module
Scram_E
(.Data(
)
,
with
no
internal
port.
.Control{Ctrl),
.Mem__Word({Mem_Blk[0]
, Mem_Blk[ 1 ]})
,
.Addr{ )); input
input
Ctrl;
[8:0]
Mem_Blk;
endmodule
157
CHAPTER
9
Structural
Modeling
ScramJE has two externalports, Data and internal to the module. anything
Module connected to
Can
internal
an
FanOut
module
to more
be connected
port
Verilog HDL allowsthis. Hereis an
that
Addr,
( .A(CtrlIn),
CondOut;
assign
CondOut
Yes,
port?
example.
.B(CondOut),
. C(CondOut));
to two external
ports, B and
input Ctrlln; output
external
one
than
are not
= Ctrlln;
endmodule
The internal
9.5
is connected
CondOut
port
CondOut appearson both
value on
and
B
C.
the
Examples
Hereis an
of a
example
logic diagram is shown
in
decade counter
Figure
in
written
the
style. The
structural
9-3.
Clock JK1
J
JK2
k
*-
Qh
'-qck
i
NQ
Z[0]
C Jk
/
r-
JK3
Q
A2
Q
/
JK4 q
CK
'\342\226\272-C
Nd
S2
SI / \342\226\240-i
CK
CK
NQ
K
Z[l]
Figure 9-3
158
So
C.
Z[3]
Z[2]
A
decade
counter.
SECTION9.5
Examples
module Decade_Ctr{Clock,Z)
;
Clock;
input
Al
and
//
Z;
[0:3]
output
S2;
wire SI,
instantiations:
module
Four
.Q{Z[0]), JK2
.WOO),
.CK{Z[0]),
.K(l'bl),
(.J(S2),
.WOO),
.Q(Z[1]),
.WOO),
.Q(Z[2]),
JK4(.J(S1),
,
.CK{Z[1])
.K(l'bl),
(.Jd'bl),
JK3
.CK{Clock),
.K(l'bl),
JK1 (.Jd'bl),
JK_FF
gate instantiation.
Primitive
Z[l]);//
Z[2],
{SI,
.K(l'bl), .CK(Z[0]),
.Q(Z[3]),.NQ(S2));
endmodule
Notice
the
unconnected
ports.
of constants
usage
9-4.
Figure
^n
1
S2\\_
CK
A3 J
CK
<**
:b K
QN
JK3
Q
)\302\260* \\
Q
CK K
QN
QN
A4
A2
S7 Cnt_Down
counter
QP]
JK2
Q
Clk
K
up-down
n
Al
JK1
1
the
notice
Q[l]
Q[0]
Cnt_Up
also
ports;
input
example, this one is that of a three-bit The structural model follows.
is another
Here
shown in
as values to
<;
J
~
J
(J,K inputs
of all
Figure 9-4
A
flip-flops
3-bit
connected
up-down
t0
1)
counter.
159
Chapter 9
Structural Modeling module
Q;
S2, S3, S4, S5, S6, S7,
wire SI, JK_FF
and
Al
Cnt_Down;
Cnt__Up,
[0:2]
output
Cnt_Down, Q)
Cnt_Up,
{Clk,
Up_Down
input Clk,
JK1
(l'bl,
l'bl,
JK2
(l'bl,
l'bl,
JK3
(l'bl,
l'bl,
S8;
Clk, Q[Q], SI), S4, Q[l], S5), S8, Q[2], );
Q[Q]) , , Cnt_Down)
Cnt_Up,
(S2,
A2
(S3,
SI,
A3
(S7,
Q[l]
A4
(S6,
S5,
, Cnt_Up) Cnt_Down)
, ;
01 {S4, S2, S3),
or
02 {S8,
S6);
S7,
endmodule
9.6
Exercises
1.
the
is
What
a gate
between
difference
and
instantiation
a module
instantiation?
2.
are the
What
values of
ports when
they
are
left open,
that
is,
they
are not
connected?
3.
with
4.
a module
Write
an
Using the module a 4-bit ALU that
Using
the
module
model
for
a 16-to-l
this
generic
using a test bench.
160
described
MUX4xl
chapter,
write a
9.3 of
5.
model
structural
and subtraction.
addition
performs
in Section
5.11, write a
asynchronous
negative
structural
multiplexer.
6. Describea genericAf-bit Instantiate
in this
described
FA
for
5.
in Section instantiates the module FA described 4, an XOR_DELAY of 7 and an AND_DELAY
that
OR_DELAYof
counter
counter
with
as a
5-bit counter.Verify
this
level reset. 5-bit
counter
10
Chapter
Topics
Other
This hierarchy,
L0.1
chapter value
file and
dump
change
topics such
miscellaneous
describes
as functions, tasks,
compiler directives.
Tasks A pieces of
task
code
is like
from
of code is written a task call) from timing
controls,
a procedure, it provides several different places as
a task
different that
is,
(using a places
delays,
in
ability
to execute
a description.
task definition)
in a and
the
so
that
common
This common piece it can be called (by
design description. A task call other tasks and
it can
can
contain
functions
as
well.
10.1.1
Task Definition A
task
is defined
using a
task definition. It is of the form:
161
Chapter10
Other
Topics
task
task_id ; [ declarations
]
procedural_statement
endtask A
task
from a task through arguments. for a task), a task can have inout
to
In addition
is an
module
are
task definition is written a task definition. of example
passed (receive
arguments
input
values from
(return
arguments
output
as well. A
arguments
declaration.Here
or more arguments.Values
zero, one,
have
can
to and values
a task) and
a module
within
Has_Task;
MAXBITS = 8 ;
parameter
task Reverse_Bits;
input
:
[MAXBITS-1
output
-1
[MAXBITS
Din;
0] : 0]
Dout;
K;
integer
begin
for
{K
Dout
=
K <
0;
MAXBITS; -K]
[MAXBITS
K
= Din
= K
+ 1)
[K] ;
end
endtask
endmodule The inputs and outputs of a task are declaredat the beginning of the task. The order of these inputs and the order be in a task to used outputs specify call. Here is another exampleof a task.
task Rotate_Left;
inout [1:16]
In_Arr;
[0:3]
input
Start_Bit,
Stop_Bit,
Rotate_By;
reg Fill_Value;
integer Macl,
Mac3;
begin
{Mac3 = 1;
for
begin
Fill_Value
162
Mac3 <= Rotate_By;
= In_Arr [Stop_Bit];
Mac3
= Mac3
+ 1)
(Macl = Stop_Bit; Macl = Macl - 1)
for
= In_Arr
[Macl]
In_Arr
+ 1;
Start_Bit
- 1] ;
[Macl
= Fill_Value;
[Start_Bit]
In_Arr
Macl >=
10.1
Section
Tasks
end
end
endtask is
Fill_Value
a local
first argument Start_Bit,
inputs,
in
register task
this
that
is
visible
directly
is the inout
array,
only
followed
In_Arr,
task.
the
within
The
the three
by
and Rotate_By.
Stop_Bit
In addition to the task arguments, a task can in the module in which the task is declared.An
reference any
is shown
example
defined
variable
in the
next
section.
0.1.2 Task Calling A
task
statement variables
that
statement
and
(or enabled, as it is said in Verilog HDL) by a task enable the argument values passed to the task that and the specifies receive is a procedural the results. A task enable statement can thus appear within an always or an initial It is of the statement. is called
form:
task_id [ ( exprl , expr2 The list of arguments must match
,
the
.
.
order
. ,
exprN)
of input,
] ;
output
and
inout
arguments are passedby value, not by reference. An important distinction a task and a procedurein other between high-level programming languages such as Pascalis that a task can be called more than once concurrently with each call having its own control. The that a to be careful is variable within a task is static,that is, declared biggest point it never disappears or gets re-initialized.Thus one task call might modify a local variable whose value may be read by another task call. declarations in
the
Hereis definition was
task definition.
an
given
example
in the
In addition,
for the task Reverse_Bits section. previous of a
task call
whose
163
Chapter10
Other
Topics
//
declaration:
Register
reg
-
[MAXBITS
Reverse_Bits The value the
of
is returned
contain
as the
Din. The
that
is, to because
may
value,
input
a value
return
later
task.
Calling
backto NewJReg.Notethat
a task
controls,
timing
//
New_Reg);
(Reg_X,
is passed
Reg_X
task Dout
Reg_X, New_Reg;
1:0]
in time
can it was
when
than
of
output
a task
called.
The output and task enable
considered bad
a
is
procedural as a register.
declared
be
of a
example
task call must be registers because a In the above example, statement.
in a
arguments
statement
NewJRegmust Here is an through
inout
task
references
that
a variable
that is not
list. Even though referencing global variables in style, it is sometimes useful as shown
its argument programming
passed in is
the
following
example.
module Global_Var;
reg [0:7] RamQ
[0:63]
;
Index;
integer
CheckBit;
reg
task GetParity;
input Address; ParityBit;
output
A
=
ParityBit
RamQ
[Address];
endtask
initial
for
[Index = 0; Index <=
63;
Index
= Index
GetParity {Index, CheckBit);
$display
bit
(\"Parity
Index,
of
memory
word
%d
+ 1) is
begin
%b.
\",
CheckBit);
end
endmodule
The address of the is referenced
164
memory
directly
within
is passed
RamQ the
task.
as an argument
and the
memory
Functions
task
A However,
an
argument
until
and or it
have delays to an assignment can
the
can
events to occur. passed to the calling
for certain
wait
argument
output
SECTION 10.2
is not
task exits.
module TaskWait;
reg NoClock;
task
GenerateWaveform;
ClockQ;
output
begin
ClockQ = #2
1; = 0;
ClockQ
#2 ClockQ = #2
1;
= 0;
ClockQ
end
endtask
initial GenerateWaveform
{NoClock);
endmodule
The
assignments
to ClockQ do not only the final
on NoClock;
appears
on NoClockafter
ClockQasa
0.2
global
the
task
register,
returns. that
appear assignment
on
NoClock, to ClockQ,
that is, no which is
waveform
0, appears
One way to avoid this problem is to the task. is, declare it outside
make
Functions
Functions,similarto tasks, alsoprovide
the capability to execute common module. The from a task is that a difference places it one cannot execute contain any delays value, (must only it cannot call any other task. In addition, a function must or inout least one input. No output are allowed in a declarations function may call other functions.
code from different function can return in zero time) and have
at
function.
A
in a
165
CHAPTER
10.2.1
Other
10
Topics
Definition
Function A
can appear
definition
function
anywhere
declaration.
a module
in
It is
of
the form:
function
;
function_id
]
range
[
input_declaration
other_declarations
procedural_statement
endfunction An
specified
function
the
with
Here is an
using the input
is declared
function
to the
input
then a
definition,
If no
declaration.
1-bit return
value
range is
is assumed.
example of a function.
module Function_Example;
parameter
-
MAXBITS
function
8;
: 0]
[MAXBITS-1
input
[MAXBITS-1
integer
K;
:
Reverse_Bits;
Din;
0]
begin
for
=
{K
0;
K <
Reverse_Bits
MAXBITS;
K
-K
[MAXBITS
= K
-1]
+ 1) = Din
[K] ;
end
endfunction endmodule The name of the function function The size MAXBITS. The function function, with
the
definition
same
by assigning a value to
assignment definition.
166
Here
this
register
Reverse_Bits.
has one implicitly
name and to
is another
is
this
input,
The Din.
function
a register
declares
register explicitly must therefore be
example of a function.
local
Kisa
range as the function. in
A the
returns a vector of internal to the returns
function
function
present
integer.
within
definition. a
function
a value An
SECTION
Functions
function
10.2
Parity;
[0:31] Set;
input
reg [0:3]
Ret;
J;
integer
begin
Ret = 0;
for (J =
0;
if (.SetJ] [
Ret =
Parity
=
J <= 31; == 1)
J =J +
1)
Ret + 1; Ret
%
2;
end
endfunction no size has been Since Parity is the name of the function. are the Ret and J local Note function returns a 1-bit value. registers. specified, a which that the last procedural to the register assignment assigns value the same name as function is returns the value from the function (a registerwith within the declared function). implicitly
In this function,
0.2.2
Call
Function A
is an
of a function
example
[MAXBITS
reg
of an expression. It is of the form: , expr2
( exprl
func__id
Here
is part
call
function
New_Reg =
-
, .
. . , exprN)
call.
1:0]
New_Reg,
Reg_X;
II
Reg declaration.
Reverse_Bits(Reg_X);
// Function call in right-handside expression.
Similar
are static,
to that
a task, is,
local
all local registers
multiple invocations of the
registers declared within within a function retain
a function their
values
definition between
function.
167
Other Topics
Chapter
10
10.3
System
Tasks and Functions HDL
Verilog
follows: /. ii.
system tasks and systemfunctions, in the language. These are predefined
built-in
provides
and functions
tasks
are
that
Display
tasks
File I/O
tasks
that
is,
groupedas
Hi. Timescale tasks Simulation
v.
Timing check
vi.
PLA
tasks tasks
modeling
modeling tasks
vii. Stochastic viii.
tasks
control
iv.
for reals
functions
Conversion
ix. Probabilistic distribution PLA this
10.3.1
tasks
modeling
and stochastic
functions
modeling tasks are outsidethe scopeof
book.
Tasks
Display
The display These
systemtasks
tasks are
system \342\200\242
and
Display
\342\200\242 Strobed
Continuous
and
The syntax
Write is
write
used
for displaying
characterized
and
printing
information.
into:
tasks.
monitoring.
\342\200\242
Display
further
are
monitoring.
Tasks
of the
form:
task_name ( format_specificationl
, argument_listl ,
format_specification2 ,
argument_list2
,
argument_listN
);
\342\200\242 \342\200\242 \342\200\242 r
format_specificationN,
168
System Tasksand taskjiame is oneof:
where a
$display $displayb $writeb
$write
The display task end-of-line
the
prints
$displayh
$displayo
$writeh
$writeo
%h
or
%d or
%H
hexadecimal
%D
decimal
octal
task prints
or
%0
%b
or
%B
binary
%C
ASCII character
net signal strength
%v
or
%V
%m
or
%M
%s or
%S
string
%t or
%T
current
If no format
time
be
used
for an
exists
format argument, then the
: for
: for $displayb
octal
: for
$display
and
$displayo
can be
$writeb
$writeh
printed using the
\\n
newline
\\t
tab
\\\\
the
\\ character
\\\"
\"
\\000
the the
character
%%
the
%
is:
and $writeo
hexadecimal : for $displayhand characters
default
and $write
decimal
$display
a
with
information
name
binary
are some
specified
output
hierarchical
specification
Special
the
can following escape sequences
%o
%c or
to standard
information
specified
while the write
character,
without an end-of-line character. The for format specification.
Here
10.3
SECTION
Functions
following
escape
sequences.
character
with octal
value 000
character
examples.
(\"Simulation time is
%t\",
$time);
169
Chapter
Other Topics
10
$display ($time,
\"
: R=%b,
QB) ; II
\342\226\240RS, Q,
//
S=%b,
Q=%b, QB=%b\",
Time is displayed in
decimalsince
format
has been
specification
no
specified.
$write (\"Simulationtime is\; (\"
$write
The following for
is
is
what
time
Simulation
above statements
when
displayed
R, S, Q and
of $time,
values
some
$time);
%t\\n\",
are executed
QB.
10
is
10:R=1,S=0,Q=0,QB=1
Simulationtime is
Tasks
Strobe
tasks are:
The strobe
$strobe These
tasks
system
end of the time processed
10
the
for
$strobeb $strobeh$strobeo display
step.
the simulation of
\"End
time
data at
step\" implies
the
time
specified all
that
events
have
but at the been
time step.
specified
always @
Rst)
(posedge
When current
Rst
has
a positive time.
simulation
$time. Values
are
at
time
%t\",
the of Q and the values edge, the $strobe task prints for of Q and is the output some values generated every time Rst has a positiveedge.
flip-flop
The flip-flop The flip-flop
value
is 1 at is 0 at
time time
17 24
value
is 1 at
time
26
value
Format specificationsare sameas
170
%b
Here
printed
The
value is
(\"The flip-flop Q, $time);
$strobe
that
for
display
and write
tasks.
The strobetask strobe task
is postponed
helpsclarify
to
task
in
the
that
task is
display
is encountered,while the execution of the of the time step. The following example
the statement
time
the
at
executed
the display
from
differs
SECTION 10.3
Functions
and
Tasks
System
end
the
further.
this
Cool ;
integer
initial
begin
Cool =
1;
assignment,
Cool has value %d\",
is executed,
Cool has value %d\",
first
(\"After
$display
Cool);
(\"When strobe
$strobe
Cool);
= 2;
Cool
(\"After second assignment, Coolhas
$ display
value
%d\",
Cool);
end
The
is:
produced
output
After
first assignment.
After
second
assignment,
When strobe is The first
Sdisplay
to Cool).
The secondSdisplay task
second
task
at the
it holds
Cool
executed.
the value
end of the time
has
the
value
the
of Cool
task prints the
2 2
value
of Coolas 1 (from
prints
The $strobe
to Cool).
assignment
value
prints
1
Cool has value Cool has value
value
first
assignment
as 2 (from of
Cool
the
as 2,
the
step.
Monitor Tasks The
monitor
tasks
$monitorb
$monitor
These monitor a changeof
the
tasks
is displayed
are:
specified
an argument
value
in
at the
end of the
time
$monitorh
$monitoro
continuously. Whenever there is list argument list, the entire argument Here is an example.
arguments in the step.
171
Chapter 10
Other
Topics
initial
$monitor
When the Q.
If any
a sampleoutput
some
At At At At At
The
format
monitor is set on D, Clkand list is displayed. Here is argument on D, Clk and Q.
changes
At
x, Clk
= x and Q is
24,
D =
25. 30. 35. 37. 43.
D x. Clk= x and Q is D 0. Clk= x and Q is D 0. Clk = 1 and Q is D 0. Clk= 0 and is D= 1. Clk = 0andQis
any
time
Monitoringcan be turned
on
at
entire
= = = =
0 1 1 1
Q
1
1
same as that for a display for a particular variable.
is the
specification
monitor can be active
\",
a continuous
change values, the
for
%d
%b\", Q);
Q is
\"and
is executed,
task
monitor
of these
%d, Clk =
D =
%t,
(\"At
D, Clk,
$time,
and
off by
task. Only
using the following
two
one
system
tasks.
$monitoroff;
// Disables
$monitoron; //
Enables
all monitors. all
monitors.
These provide a mechanismto control dumping of value The $monchanges. itoroff task turns off all monitoring so that no more messages are displayed. The $monitoron task is used to enable all monitoring.
10.3.2
File I/O Tasks
Opening and
A system
Closing
Files
function $fopen
is available
for
opening
= $fopen ( file_name file_pointer system function returns (a pointer) to the file.
a file.
integer //
//
172
The $fopen
) an
;
integer
value
Tasks
System
while the following
task
system
can be
and
SECTION 10.3
Functions
used to closea file.
$fclose (file_pointer); is
Here
of its usage.
an example
Tq_File;
integer
initial
begin Tq_File
=
(\"-/jb/div.tq\;
$fopen
{Tq_File);
$fclose
end
Writing out to a File The
that can
counterpart
The for
and monitor
strobe
write,
display,
be usedto write
system tasks have to a
information
$fdisplay
$\302\243displayb
$\302\243displayh
$\302\243displayo
$fwrite
$fwriteb
$f writeh
$fwriteo
$fstrobe
$\302\243strobeb
$fstrobeh
$\302\243strobeo
$fmonitor
$\302\243monitorb
$\302\243monitorh
$\302\243monitoro
first argument for task is a list of
the
list. Hereis an
all these tasks pairs of format that
example
integer
illustrates
a file
is
pointer.
specification
a corresponding
file. These
are:
Remaining arguments by an argument
followed
this.
Vec_File;
initial
begin
Vec_File =
$fdisplay
(\"div.vec\;
$fopen
{Vec_File,
\"The
simulation
time
is
%t\",
$time);
//
The
first
argument
$fclose {Vec_File);
Vec_File
is the
file pointer.
end
173
CHAPTER
10
Other Topics
Upon executionof the $fdisplay file
the
task,
statement
following
appears
in
the
\"div.vec\".
0
time is
The simulation
Reading from a File two
are
There
tasks read data tasks are:
system a text
from
$readmemb
tasks available for reading data from file and load the data into memory.
These
a file. These
system
$readmemh
file can contain white spaces, comments and $read(for binary or is hexadecimal numbers. Each number (for $readmemh) memb) separated is executed, each number read is by white space. When the system task to an address in memory. The beginning address corresponds to the assigned text
The
of the
index
leftmost
reg [0:3]
memory. [0:63];
Mem_A
initial
(\"ones_and_zeros.vec\",
$readmemb //
//
an
Optionally
number read from 0 starting
Each
address
explicit
Mem_A);
in is assigned to memory to 63.
can also
be specifiedin
the
locations
task
system
call,
such as:
// The
first
//in address 15, // address30. An
address
may
read
number
explicitly
next
from
the
at
16,
one
be given
of the form:
@address_in_hexadecimal
174
30);
15,
Mem_A,
(\"rx.vec\",
$readmemb
in
the
file \"rx.vec\" and so on until
text
file as
is stored
well. The
addressis
In such a case, the system are loaded Subsequentnumbers
).3.3
and
Tasks
System
Functions
the data into the that address onwards.
reads
task
from
SECTION10.3
specified address.
Timescale Tasks The
task:
system
$printtimescale
specified module. The and arguments Sprinttimescale specified prints the time unit for the module that contains time precision this task call. If a hierarchicalpath to a module is specified as its argument, this system task prints the time name for the unit and module. precision specified the time
displays
time
and
unit
for the
precision
no
with
task
$printtimescale;
$printtimescale Here
is a
sample
of
output
(
what
when these
appears
Timescaleof (CIO) is
scale
Time
The
system
) ;
hier_path_to_module
lOOps
lOOps/
of (C10.INST)is
tasks are called.
lus/
lOOps
task:
$timeformat
specifies how the
format
%t
specification
must
report time
information. The
task is of the form:
$timeformat
(
units_number
suffix where
for 1
,
, numeric_field_width ) ',
is:
a units_number
0
, precision
s
-1 for 100
ms
175
Chapter
10
Other Topics
-2 for 10 ms for
-3
-4 for
-5 for for
-6
-7 for
1 ms
100 us lOus
1 us
100 us
-8 for 10
ns
for
-9
1 ns
-10 for
100 ps
-12
1 ps
-13 for
100 fs
-15
1
-11for 10ps for
-14 for 10 fs for
The system
fs
task call:
$timeformat (-4, 3,
will
the %t specifier
display
value in
Current simulation If no
10.3.4
the
time is
prints
$time);
%t\",
task as:
Sdisplay
time is
is specified,%t
$timeformat
mescalesin
5) ;
ps\",
simulation
(\"Current
$display
\"
0.051
ps
in the
smallest precision
of all ti-
source.
Tasks
Control
Simulation
The systemtask: $\302\243inish;
the
makes
simulator
exit and
return
control
to the
back
operating system.
The systemtask:
$stop;
causes
the
issued
176
simulation
to the
to suspend.
simulator. Here
is an
At this stage, example
interactive commandsmay
of its
use.
be
System Tasksand
time
500
10.3
#500 $stop;
initial After
SECTION
Functions
the simulation
units,
stops.
LO.3.5 Timing Check Tasks The
task:
system
( data_event
$ setup
reports
violation
a timing
, reference_event , limit
);
if:
- time_of_data_event
( time_of_reference_event
)
<
limit
of this task call is:
An example
$setup
{D,
Ck,
posedge
1.0);
The system task:
$hold
(
, data_event
reference_event
reports a violation
);
if:
- time_of_reference_event)
(time_of_data_event
Hereis an
, limit
< limit
example.
$hold
(posedge
Ck, D,
The following systemtask
is a
$setuphold reference_event
0.1); combination
of the
, data_event
(
$setup and $hold tasks. , setup_limit
,
hold_limit );
The
system
$width
task:
( reference_event
, limit
, threshold );
177
CHAPTER
10
Other
Topics
violation if:
reports a
threshold
<
(
-
time_of_data_event
) <
time_of_reference_event
The data with
the
event
edge.
Here is an
(negedge
Ck,
opposite
$
width
the reference
from
derived
is
event:
is
it
limit the
reference
event
example.
0.0,
0);
The systemtask:
$period
(
reports a violation
, limit
reference_event
if:
- time_of_reference_event
( time_of_data_event
The referenceevent from
the reference The system
must
be an
event: it
edge-triggered
is the
reference
) <
event. The data event event
with
the
same
limit is derived
edge.
task:
$skew( reference_event , data_event reports a
);
, limit
);
violation if:
> limit time_of_data_event - time_of_reference_event
If time
of data_event
is equal to the time of reference_event,no violation
reported.
The
system task:
$recovery ( reference_event , data_event , limit ); reports
a timing
violation
if:
( time_of_data_event
178
- time_of_reference_event
)
<
limit
is
System Tasks
new
the
data
SECTION
10.3
system task records reference event time before performing the timing check; thereforeif event and the reference event at the same simulation time, both occur event
The reference the
and Functions
a violation
is
event. This
an edge-triggered
be
must
reported.
task:
The system
$nochange ( reference_event, data_event , start_edge_offset, );
end_edge_offset
a timing violation if the data event reference event. The reference event
reports the
and
start
offsets
stop
will
Each of the violation,
edge.
of
event. The
edge-triggered For
width
example,
Preset, 0, 0);
changes while
Clear is low.
have a last argument tasks may optionally system task a when there is a timing A notifier. system updates notifier, its value according to the following case statement. changing
is a
which
if Preset
a violation
report
be an
must
the specified
during
to the referenceevent
are relative
(negedge Clear,
$nochange
occurs
by
case
above
notifier
(
)
= 'b0;
: notifier
'bx
notifier
'b0 :
notifier
'bz :
=
'bl;
= 'b0;
: notifier
'bl
=
'bz;
end
can be usedto provide
A notifier propagate an
x to
the
output
that
reported
about
information
the violation.
the violation
Here is an
example
or of a
notifier.
reg
NotifyDin;
$setuphold In this register earlierfor
(negedge
Clock, Din,
example, NotifyDin is the
NotifyDin
changes
value
notifier.
according
If
tSETUP,
tHOLD,
a timing
violation
to the case statement
NotifyDin);
occurs, the described
a notifier.
179
CHAPTER
10.3.6
Other
10
Topics
Time Functions
Simulation The
\342\200\242 unit \342\200\242
\342\200\242
the
Hereis an
time
: Returns
Srealtime
as a
that invokes
module
scaled
bits
64
to the
time
bits.
in 32
time
: Returns
$stime
as an integer in
that invoked it.
module
the
of
of
the time
: Returns
$time
simulation time.
return the
functions
system
following
real number scaledto the time unit
it.
example.
/ Ins
10ns
'timescale
module
TB;
initial
(\"Put_A=%d Put_B=%d\",
$monitor
\"
Put_B,
Put_A,
\"at time
Get_0,
Get_0=%d\",
$tirne);
%t\",
endmodule
Here
is the
it produces.
output
Put_A=0
Put_B=0 Get_O=0
Put_A=0
Put_B=l
at time 0 at time
Get_O=0
Put_A=0 Put_B=0 Get_O=0 at The
value
printed.
by $time
returned
then rounded. Here
Note that
is another
is scaled to the time
example
with
its
the
of
unit
how
decides
Stimeformat
5
time16 module
TB and
value is to be
the time
output.
initial
$monitor
(\"Put_A=%d \"
Get_0=%d\",
180
Put_B=%d\",
Get_0,
Put_B,
Put_A,
\"at time
%t\",
Put_A=0
Put_B=l
Get_O=0
at time
5.2
Put_A=0
Put_B=0
Get_O=0
at time
15,6
$realtirne)
;
SystemTasks LO.3.7
SECTION 10.3
Functions
Functions
Conversion
The following number
and
are utility
functions
system
functions
between
convert
that
types. \342\200\242
$rtoi
decimal
the
truncating \342\200\242
$itor
number to
an
integer
by
value.
integer to real. a real into 64-bit vector Converts (real_value): the real number (IEEE 754 representationof the real
(integer_value)
\342\200\242
$realtobits of
representation
a real
: Converts
(real_value)
: Converts
number). \342\200\242
$bitstoreal
: Converts
(bit_value)
a bit pattern into a
real number
(oppositeof $realtobits).
L0.3.8 ProbabilisticDistributionFunctions The
function:
$random
[
) ]
(seed
on the value of the number as a 32-bit signedinteger based seed. The seed (must be a reg, integer or a time register)controlsthe number that the function returns, that seed will generate a different is, a different time If no seed is specified, a random number is generated random number. every a is called based on seed. function default $random
returns
Here
a random
is an
example.
Seed,
integer wire
Rnum;
Clk;
Seed =
initial
12 ;
always @
(Clk)
Rnum
= $random
On every edge of Clk, Srandom random number.
If a number operatorcan
be used
(Seed);
is called
which
returns
a 32-bit
signed integer
to +10 is desired,the modulus to generate such a number as shown in the following example. within
a range,
say -10
181
CHAPTER
10
Other
Topics
= $random
Rnum
Here
is an
(Seed)
sequence,
that that
11;
example where the seed is not
Rnum = $random
Note
%
the
// Seed is
/ 2;
specified.
explicitly
optional.
of numbers generated is a pseudo-random for a starting same sequence of numbersis generated
sequence
is, the
seed
value.
The following expression:
{$random}% returns interprets
number
a random the
11
in
integer
signed
10. The concatenation ({})operator returned by the $random function as an unsigned
the
0 to
range
number.
The following
functions
the probabilisticfunction $dist_uniform
( seed , start ( seed
$dist_normal
( seed
$dist_t
182
parameters
)
, degree_of_freedom
) ( seed , degree_of_freedom
( seed
$dist_erlang
All
)
, standard_deviation , upper)
( seed , mean
$dist_chi_square
end
, mean )
( seed
$dist_exponential
$dist_poisson
, mean
,
to these
according
name.
in the function
specified
numbers
pseudo-random
generate
, k_stage
, mean
)
functions must be integervalues.
)
to
Disable
10.4
Statement
Section
10.4
Statement
Disable
A disable statement is a procedural statement (hence it can only appear within an always or an initial A disable statement can be used to statement). it completes terminate a task or a block (sequentialor parallel) before all its hardware It can be used to model and global statements. executing interrupts
resets. It is of the form:
disable task_id;
disableblock_id ; is executed, execution continues with the task call or the block being disabled.
statement
a disable
After
statement
following begin:
the
next
BLK_A
II
Stmtl.
//
Stmt2.
disable
BLK_A;
II
Stmt3.
//
Stmt4.
end
// Stmt5. 4 are never executed. executed. Here is another
3 and
Statements
5 is
statement executed,
task
After
the
disable
statement
is
example.
Bit_Task;
begin
// Stmt 6.
disable Bit_Task;
II
Stmt
7.
end
endtask
//
Stmt 8.
Bit_Task;
//
Stmt
//Task call.
9.
183
Chapter
10
Other Topics the disable statement is executed, the task is aborted,that is, statement never executed. Executioncontinueswith the next statement following the task call which in this example is statement 9.
When
7 is
Disablinga task
is
is because
not
recommended,
especially
the language
if the task
returns output
of the
and specifies output inout are indeterminate when a task is disabled.A better arguments approach the task. For example, is to disable the sequential block, if any, within
This
values.
that
the
values
task Example; Count;
[0:3]
output
LOCAL_BLK
begin:
II Stmt 10. Count =10;
disable Stmt
II
LOCAL_BLK;
11.
end
endtask statement
disable
the
When
LOCALJ5LK to exit. Sincethis
gracefully and Count has were
its
gets executed, it causes in is the only statement of If value 10. assigned
replaced
then after the
disable
statement
gets executed,
the value of Count is
Events
Consider the following two always statements.
reg II
Done;
Ready,
Get
initial
the always
begin
184
the disable statement
Example;
indeterminate.
Named
the
block sequential task, the task exits
with:
disable
10.5
the
statements
interacting:
Done = #0
SECTION
Events
Named
10.5
0; = 1;
Done
end
always @
begin
(Done)
//
Finished
// Trigger
this always statement.
processing the
next
always
statement.
an event on Ready:
// Create = 0;
Ready
= 1;
#0 Ready
end always @
begin
{Ready)
//
Finished
this always statement.
processing
// Create
to
event
#0
statement:
always
previous
trigger
Done = 0;
= 1;
done
end
The two event
assignmentsin
is created
each
always
statement
are needed
on Ready and Done.It appearsthat
Done are to act only
the
to ensure that
purpose
of Ready
an
and
statements. alternate to achieve this - using an mechanism Verilog HDL provides named events. A named event is yet another data type (the two other data types in the language are the register and the net data types). A named event must be declaredbefore it is used. An example of its declaration is:
event The
event
declared a statement.
as
Ready,
declaration
namedevent,
Examples
of such
handshake
signals
between
the two always
Done;
declares two an
event
statements
named events,
can be
Ready
created using
the
and event
Done.
Having
trigger
are:
-> Ready;
->
Done;
185
CHAPTER
Other Topics
10
Events on named events that
is,
the @
using
@
the event
trigger statement
to occuron Done, which causes Our simpleexample of the namedevents as follows. event
monitored
just like
events on variables,
mechanism, such as:
(Done)
So whenever
be
can
for
Done
two
always
an event
is said
can be rewritten
using
is executed,
to execute.
statements
Done;
Ready,
initial
-> Done; always @
begin
(Done)
//
always statement.
the next
Trigger
// Create
an
event
on
Ready:
-> Ready;
end
always @
begin
[Ready)
event to
//
Create
->
Done;\342\200\242
trigger previous always
statement:
end
machine
A state an
can also be describedusing
state
asynchronous
event
machine.
State2,
Statel,
State3;
II Resetstate:
initial begin
//
Reset
state
-> Statel;
end
186
logic
here.
events.
Here
is an
example of
L0.6
with
Structure
Mixing
Behavior
SECTION 10.6
always @
(Statel)
begin
Statel
//
-> State2;
here.
logic
II Create
event
on
State2.
event
on
State3.
end
always @
{State2)
begin
State2
//
-> State3;
here.
logic
II Create
end
always @
{State3)
begin
here. It can have
State3
logic (InputA)
//
if
II Create
-> State2;
statements
on
State2.
// Create event on
Statel.
event
such
as:
else
-> Statel; end
the describes the reset logic. Upon completion,it triggers statement. The the last statement in this executionof always always statement causes an event to occur on State2; this causes the third always statement to execute and subsequentlythe fourth statement executes. always In the last always statement, an event is made to occur either on State2 or on Statel on the value of InputA. depending
The
initial
statement
second
Mixing
Structure
Behavior
with
In previouschapters,we discussedthe various forms HDL allowsall thesemodeling to be combined in styles of a module is: syntax module
( port_list
module_name
of modeling. Verilog module. The
a single
);
Declarations:
Input, output Net
and
inout
declarations.
declarations.
Reg declarations.
187
CHAPTER
10
Other
Topics
declarations.
Parameter
statement.
Initial
Gate instantiation statement. statement. statement.
instantiation
Module
instantiation
UDP
statement.
Always
Continuous assignment.
endmodule
Hereis
an
of a
example
module MUX2xl //
II
description.
A, B,
(Ctrl,
Ena,
Z)
;
declaration:
Input
Ctrl,
input
mixed style
B,
A,
Ena;
declaration:
Output
output Z;
//
declaration:
Wire
wire
Not_Ctrl;
Mot,
declaration assignment: wire Z = Ena == 1 ? Mot : 'bz; II Net
// Gateinstantiations:
not or
Ctrl);
(Not_Ctrl,
Ta, Tb);
(Mot,
II Continuousassignments:
assign
Ta
assign
= A & Ctrl;
Tb = B
&
Not_Ctrl;
endmodule
contains a mix of built-in logic continuous assignments(dataflow behavior). The module
10.7
Every
hierarchical
character.
188
Path
Hierarchical
gates
(structural
components)
Name
in Verilog HDL has a unique hierarchicalpath name is formed path by using names separated by A new hierarchy is defined by: identifier
and
name. a
period
This
(.)
Path Name
Hierarchical
/.
Module
ii.
Task definition.
instantiation.
definition.
Hi. Function
block.
Named
iv.
path name
The complete
(a module that used
in
any
SECTION10.7
identifier
instantiated
not
is
in a
level
of any
starts
by anybody
description. Here is an
with
the top-level
else). This path Figure
example.
name
module can
be
10-1 shows the
hierarchy.
module Top
wire
function
CI: module
reg
Sbus
Func
CM
task
Proc
reg Art
Art
block BLA integer
Dot
block BLB
reg Art,
Figure
10-1
Cit
Module hierarchy.
module Top;
wire Sbus;
function
Func
endfunction
task
Proc
reg Art;
begin: integer
BLA
Dot;
189
CHAPTER10
Other Topics
end
begin: reg
BLB
Cit;
Art,
end
endtask
. .) ; //
Chil CI (.
instantiation.
module
A
// Module
endmodule
Top.
module Chil;
reg
Art;
endmodule
names
hierarchical
The
in
this
are:
example
Top.CI.Art
Top.Proc.Art
Top.Proc.BLB.Art
Top.Proc.BLA.Dot
Top.Proc.BLB.Cit
Top.Sbus the
in
from
any A
can hierarchy. level of the hierarchy. The value
level
lower
with
variable
not
only
access to any be
read,
can reference an item
module
upward referencing) or below
qualifying the
free data
allow
names
hierarchical
These level
it
(downward
the module
in
in its
instance name. This
any
also be updated above
a module
referencing)
from
item
but can
it (called
hierarchy by
is of the form:
. module_instance_name
variable_jiame
For
downward
level as the
190
path
referencing,
the model
lower-levelmodule.Hereis an
example.
instancemust
be
at the
same
Sharing
module
Tasks and Functions
SECTION
10.8
Top;
wire
Sbus;
Chil CI
(...); (CI.Art);
$display
II
A
//
Downward
module
instantiation.
referencing.
endmodule
module
Chil;
reg Art;
endmodule
10.8
Sharing Tasks and
Functions
is to One to share tasks and functions among different modules approach write the definitions of the shared tasks and functions in a text file, and then directive. include these in the required module using the 'include compiler in a file that we have the and task definitions Assume following function \"share.h\".
function
SignedPlus;
endfunction
function
SignedMinus;
endfunction
task
PresetClear;
endtask
Here is how
the
file
can be
used
in
a module.
191
CHAPTER 10
Other Topics
module SignedAlu (A, input
[0:3]
input
Operation;
Operation,
Z) ;
Z;
[0:3]
output
B,
B;
A,
reg [0:3] Z;
II Includethe definitionsof thesharedfunctions. \"share.h\"
vinclude
always @
B or
or
(A
Operation)
if (Operation) =
Z
(A, B) ;
SignedPlus
else (A, B) ;
= SignedMinus
Z
endmodule
Note that
directive
'include
the
since the task and function a module declaration. An
alternate
way
and functions in a different above,
but
within
must be
in the
definitions
to share a module.
present within
the
module
file \"share.h\" are not
functions and tasks is to define the And then refer to the requiredtask
name.Hereis the same module using a hierarchical this time the task and function definitions appear within
declaration bounded
shared or
function
a module
Share;
function SignedPlus;
endfunction
function
SignedMinus;
endfunction
task
PresetClear;
endtask
endmodule
Here is how
192
the
shared
functions
can be
referenced in
a different
tasks
example
declaration.
module
by
module.
as
Value Change Dump module SignedAlu2 input
[0:3]
input
Operation;
reg [0:3]
SECTION 10.9
File
Z)
Operation,
B;
A,
Z;
[0:3]
output
B,
(A,
(VCD)
Z;
always @
B or
or
(A
Operation)
if (Operation) Z
= Share.
(A, B) ;
SignedPlus
else Z
= Share.SignedMinus
(A, B) ;
endmodule
0.9
Dump (VCD) File
Value Change A changes on
for
value
specified
other
The into
dump (VCD) file contains information variables in design. Its main purpose
post-processing
a VCD
/.
is to provide
information
tools. are provided
tasks
system
following
value
about
change
to create and
direct information
file.
$dumpfiJe : This system
task
of the dump file.
the name
specifies
For example,
$dumpfile (\"uart.dump\;
ii.
: This
Sdumpvars value
changes
to
are
variables whose be dumped into the dump file. system
task specifies the
$dumpvars;
//
With
//
variables
Dumps
it
arguments,
[level,
$dumpvars
II
no
variables
in the
to
specifies
dump
all
design.
module_name) in
specified
// modulesthe specified
number
; module of
levels
and in
all
below.
193
Chapter 10 Other Topics UART);
$dumpvars
(1,
//
Dumps variables
variables in // level below. II All
(0 ,
$dumpvars
// Level 0 // variables $dumpvars
//
Dumps
//
The
//
must
module.
UART
UART);
(2,
$dumpvars
only in
and
UART
UART) ;
causes all variables in UART and in all module instances below
(0,
P_State,
info
about number
level
P_State is not
and N_State variables. relevant in this case,
but
be given.
// case,
to
only
and
all UART.
N_State) ;
$dumpvars (3, Div.Clk, UART); number applies only to II The level II
one
modules
all
in
UART,
that
below. Also dumps Div.Clk.
two levels
// variable
Hi. $dumpoff : This
system
task
causes
modules,in this in
all variables
is,
value
the dumping
UART
changes
on
tasks to be
suspended.
$dumpo\302\243\302\243;
iv.
$dumpon The
syntax
system task
: This
causes all dumping tasksto resume.
is:
$dumpon; v.
$dumpall
variablesat
: This that
is:
$dumpall;
194
system tasks
time,
that is at
dumps
the
the time
it
values
of all
is executed.
specified
The syntax
Value
vi. $dumplimit
bytes)
: This system
SECTION 10.9
(VCD) File
Dump
task
file. Dumping
a VCD
for
Change
size (in
the maximum
specifies
stops when this
limit
is
reached.
For example,
(1024) ;
$dumplimit
vii. $dumpflush file
VCD
system
the
execution of
: This
system
VCD
//
1024
task
system
buffer
//
file
flushes
is
of
maximum
bytes. data
in
the
operating
stored in the VCD file. After the task, dumping resumes as before. to be
$dump\302\243lush;
0.9.1
An
Example
Here is an
of an
example
module
Clk,
initial
counts
between
5 and
12.
Up_Down) ;
Count;
Count;
[0:3]
reg
that
Up_Down;
[0:3]
output
Count,
[Clk,
CountUpDown
input
counter
up-down
Count
=
'd5;
always @
begin
Clk)
(posedge
if
{Up_Down)
begin
Count
= Count
+ 1;
if (Count > 12) Count
= 12;
end
else
begin
Count = Count
if
-
1;
(Count < 5)
Count
=
5;
end
195
CHAPTER10
Other Topics
end endmodule module Test;
reg Clock,
UpDn;
wire
Cnt_Out;
[0:3]
parameter
=
ON_DELAY
CountUpDown CI
1,
OFF_DELAY = 2 ;
{Clock, Cnt_Out, UpDn);
always
begin
Clock
=
1;
%ON_DELAY;
= 0;
Clock
%OFF_DELAY;
end
initial
begin = 0;
UpDn
#50
UpDn = 1;
#100 $dumpflush;
// Stopsthe simulation.
$stop; end
initial
begin
$dumpfile
(\"count.dump\;
$dumplimit (4096); Test);
$dumpvars
(0,
$dumpvars
(0, CI.Count,
end
Cl.Clk, Cl.Up_Down);
endmodule
10.9.2
Format
of VCD
The VCD file \342\200\242 Header
unit.
196
File is
an ASCII information:
file. It has the Gives
following information: date, simulator version and timescale
Value
\342\200\242
of the scope
Definition
information:
Node
(VCD) File
Dump
Change
SECTION 10.9
and type of variables
beingdumped. \342\200\242 Value
are
in
$end
bl
$version
1.0
I
blO\"
$end
blOl
$timescale
K
lOOps
0' module
$scope
parameter
Test $end
1)
32 ! ON_DELAY
0*
$end
$end
$var parameter 32 \" OFF.DELAY
#10
$end
0#
$var reg
$end $end
# Clock
1
$var reg 1 $ UpDn $var wire 1 % CntjDut $varwire 1 &Cnt_Out ' $var wire 1 Cnt_Out $var wire 1 (Cnt_Out $scope module CI $var
wire
1
) Clk
wire
$var wire $upscope
1 1
) Clk
0)
#30 (0) $end (1) $end
+
(3) $end
blOl
+
$end
#40
0# $end
(0:3)$end
$end
*
Up_Down
0)
#60 1#
1)
$end
$end
bl00
+
blOl
+
#70
$end
0#
#0
(continued
1)
bl00
$upscope $end $enddefinitions
1#
(2) $end
$end
* $var wire 1 Up_Down $var reg 4 + Count $var
+
1&
$end
$var
Absolute
$dumpvars 1# 0$
FriSep27 16:23:581996 HDL Simulator
time.
10-2.
Figure
$date
Verilog
with
recorded.
file producedis shown
The VCD
value changes
Actual
changes:
simulationtimes
next column)
Figure 10-2
A
VCD
file.
197
Chapter
10 Other Topics
10.10
Specify Block The delays
are
that
delays
distributed
we have delays.
discussed so far Delays for paths
delays, can be specifiedusing a specify
be used for
the
as gate
a module,
In general,
and net
delays called
module
a specify
path
block can
following.
paths betweena sourceand a destination. To assign delay to these paths. To perform timing checks for the module. To declare
/. ii. Hi.
A
block.
such in
block
specify
appears
within a
module declaration.It is of the form:
specify
spec_param_declarations
path_declarations system_timing_checks
endspecify
A specparam within the
for (or a specify parameter)declarationdeclaresa parameter specify block. Here is an example.
specparam
Three kinds
of
tSETUP
= 20,
module
paths
tHOLD =
25; described
can be
use
a
within
specify
block.
These are: \342\200\242
path.
Simple
\342\200\242
path.
Edge-sensitive
\342\200\242
path.
State-dependent
A simple
path is source
declared using oneof the
following
two
*> destination
each bit // Specifies a full connection: // connects to all bits in destination.
source
=>
//
in
source
destination
Specifies
a parallel
to // connects 198
forms.
exactly
connection: every bit in source one
bit
in destination.
SpecifyBlock Section10.10 Here
are
some
examples.
Clock;
input
input [7:4]
Q;
=> Q[l]) = 5;
(Clock
// (D
D;
[4:1]
output
from
Delay
*>
= {tRISE,
Q)
is 5.
to 2[1]
Clock
input
tFALL) ;
/* Paths are:
D[l] to
Q[4]
D[l]
to
D[l]
to Q[2]
Q[3]
D[l] to Q[l]
D[6]to
Q[4]
to
D[4]
Q[l]
*/
path, the path is describedwith
In an edge-sensitive
to an
respect
source.Forexample,
(posedge
=>
ClocJc
/*
The
path
The
data
delay
path
A state-dependent
Da))
is
from the
is from
inverted as it
true.
(Qb+:
=
Da to
(2:3:2);
propagatesto
path specifies
a path
edge of Clockto Qb.
positive Qb
delay
Da does
and Qb.
under
the
edge on
not get
*/
some
condition
when
it
is
For example,
if
{Clear) (D => Q)
=
(2.1,
// Only if // specified
Here is a list
of
timing
4.2);
Clear is true, use the delay
for
the
path. check
system tasks
that
can
be used
within a
block. specify
199
CHAPTER 10
Other Topics
$hold
$setup
$setuphold
$period
$skew
$recovery
$width
$nochange
Here is an
example of a specifyblock.
specify
// Specifyparameters: =
(5:4:6);
specparam
tCLK_Q
specparam
tSETUP=2.8,
with path specifications:
Path delays
//
{Clock
*>
= tCLK_Q;
Q)
{Data *> Q) =
12;
{Clear, Preset // Timing
= 4.4;
tHOLD
*>
Q)
= (4,
5) ;
check:
$setuphold (negedgeClock,
Data,
tHOLD)
tSETUP,
-,
endspecify
a module
Along propagate
to
the
output.
path, only pulses that are longer However, this can additionally
than
the path delay
be controlledby
addition In specify block parameter called PATHPULSE$. width for a is the which i t range pulse rejected, can also specifying pulse width that will cause an x to appear at the a specify pulse range form of this parameter specification is: path. A simple
special
=
PATHPULSE$
(reject_limit
is less If a pulse width If a output. pulse width
but greater
specified)
than is
less the
than
, [ ,
using
be used to of the
end
] );
error_limit
the rejectjiimit, the pulse does not propagate to than the error Jimit (same as rejectJimitif not an x is generated at the target of the reject Jimit,
path. A
pulse
limit
PATHPULSE$
Here is an 200
specified for a specificpath of the form: parameter
can be
modified PATHPULSE$
example
input_terminal
of a
a
to
$ ou
as
tpu t_terminal
specify block.
well
by using
a
Strengths
10.11
SECTION
specify
PATHPULSE$ =(1,2);
specparam
// Reject limit
=
// Reject limit
=
= 2.
limit
Error
1,
= 6; specparam PATHPULSE$Data$Q Error
= 6,
limit
on path
to
Data
from
Q.
endspecify
0.11
Strengths In addition
the
to
to these
additional attributes
four basic values in values such as drive
0, 1, x
HDL,
Verilog
and
strength
charge
and z, strength
can be
strength
value
specified.
0.11.1 Drive Strength A
drive
strength
/.
A net
can be a net
in
specified for the
declaration
following:
assignment.
of a primitive ii. Output terminal gate instance. Hi. In a continuousassignment. A
net
drive
1, the second assigned a value is assigned a value 0. It is of the form:
( strength_for_l The the
has two values, one is the is the strength
specification
strength
the net is
when
of the
order
values is
strengths
following
value
when
the
, strength_for_0 )
not
important.
For
an assignment
of value
1, only
are allowed.
\342\200\242
supplyl
\342\200\242
strongl
\342\200\242
pulll
\342\200\242 weakl \342\200\242
highzl
For an
assignment
(not
allowed
of value
for gate
primitives)
0, the following
strengths are allowed.
\342\200\242
supplyO
201
Chapter
10
Other Topics \342\200\242
strongO
\342\200\242
pullO
\342\200\242
weakO
\342\200\242
The default
for gate
allowed
(not
highzO
is (strongO,
specification
strength
primitives) strongl).
Here are some examples.
// //
a net:
for
Strength
wire
weakO) #(2, 4) Lrk can be specified Strengths
// wire,
//
Drive
trior,
Ord;
nets
scalar
terminal of a gate Al #(3:4:4) (Mout, MinA,
primitive: MinB,
can only be specified for
strengths
// gateprimitives: xor, nand, nor, // bufif0, bufif1, not, notifO,notifl,
xnor,
//
in a
Strength (weakl,
continuous assignment: Wrt = Ctrl;
#2.56
pullO)
The strength of a net can be printed task. For example, display
$display
buf, pullup.
pulldown,
assign
MinC);
the following
or,
and,
of type:
trireg,
output
strongO)
(pulll,
//
an
for
Strength
&&
for
only
triand,
tri,
wor,
wand,
// triO, tril.
nand
= Pol
(pulll,
(\"Prq is
%v\",
using
the
%v format
specification
in
a
;
Prq)
produces:
Prq is Wei
10.11.2
Charge Strength A
trireg
net
can
optionally
charge strength specifies the the net. It is one of:
have a relative
charge strength
size
of
\342\200\242 small \342\200\242 medium
202
(default,
if not
specified)
specified
the capacitance
as
well.
associated
This with
Race
SECTION
Condition
10.12
\342\200\242
large
a charge
In addition,
decay time can be specifiedfor
a trireg
net. Here
is
an example.
(small) #(5, 4, 20) Tro;
trireg The
0.12
Tro has
net
trireg
is 4
fall delay the net is
in
a small
capacitance.The risedelay
high-impedance)
units, the
5 time
is
decay time (the charge decays units.
the charge is 20 time
and
units
time
when
Race Condition
If statement,
a
a race
HDL does for
or in an always used in a continuous assignment is because This condition can occur due to zero delay. Verilog how events, which occur at the same time, are ordered define is not
delay
not
simulation.
is a
Here
simple example
illustrates
that
this
fact about
zero delays
using
non-blocking
assignments.
begin
Start
<= 0;
Start
<= 1;
end Both
0 and
values
step. Dependingon how result
on Start
Hereis
scheduled to be
1 get
may be
another
the
events
assignedto Start at
are ordered
a 0 or a 1.
example
that
shows
a race
the
(internal to a
end
of the
time
simulator),the
condition dueto event
ordering.
initial
begin
Pal = 0;
Ctrl #5
Pal
=
1;
= 1;
Ctrl = 0;
end
203
CHAPTER
Other
10
Topics
always @
or
(Cot
begin
Ctrl)
(\"Thevalue of Cot at
$display
time\",$time,
\"
is
\",
;
Cot)
end
assign Cot = and Ctrl
Pal
When
Pal;
are assignedvalues and the
assignment
Which one
should be executedfirst?
order. If the
continuous
assignment
initial
the
in
statement
always statement are both
continuous
The
Verilog
ready
at time
the
does not define this
language
first, Cot will get 0, which
executes
0,
execution.
for
in
turn
will trigger the always statement. But since it is already ready for execution, which displays the value statement nothing is done. Thealways gets executed of 0 for Cot. If we
assume
Cotis printed the
always
continuous
(the
continuous
the
that
assignment
assignment
another exampleof a racecondition.
dealing with
zero
updatesthe delay
value
of Cot.
assignments.
Here is
GlobalClk)
@(posedge
always
executes first, the current value of has not yet been executed),and then
gets executed which
be careful when
Therefore
statement
RegB = RegA;
always @(posedgeGlobalClk) - RegB;
RegC
which statement is to be executedfirst always on GlobalClk.If the first statement is always positive edge will get the value of RegA when the executed, RegB immediately. Subsequently second always statement will get the latest value of RegB executes, (the RegC
does
The language when
there
not
define
first
always
is a
one assigned
in
the
If the second always
statement).
statement executes first, RegC will get the old value has not been and RegB (RegB yet assigned), subsequentlyRegBwill be the of So value on which executes assigned RegA. depending always statement will have a different value. The problem occurs because the first, RegC procedural assignment occurs that is, without One way instantaneously, any delay.
of
204
Exercises is to
the problem
to avoid
use
A better
delays.
is shown
This
statements.
assignment
non-blocking
intra-statement
insert
10.13
SECTION
approach is to
next.
GlobalClk) always @(posedge <=
RegB
RegA;
GlobalClk)
@(posedge
always
RegC <= RegB; When
another, avoid
0.13
from one always statement when assigning to the variables assignments
information
communicating
use
non-blocking race conditions.
via variables
to to
Exercises
1.
Can
2. Can a task
have
function
3.
Can a
4.
What is the
5.
What
6.
Write
7.
zero
have
input
parameters?
and $write
system tasks?
difference
between
$display
difference
between
$strobe and $monitor
a function decoding.
Write a
function
string
that
that
performs
converts
a
BCD
coded decimal)
(binary
a four-character
What
10.
Write
string
that
contains
digits to an integer value. For example,if MyBuffer \"4298\", convert it to an integer Mylnt that has the value
is
difference
the
a task
specified begin
What
tasks?
system
Does Verilog HDL have a capability to read files other than admemb and $readmemh systemtasks?
9.
11.
the
delays?
segment
decimal
8.
is
task?
call a
a function
is
and
between
$stop and $finish
dumps the contents end locations.
that
a notifier?
Give an example
to
7-
only
contains
the
4298.
using
the
$re-
systemtasks?
of a memory
starting
from
a
of its use.
205
Chapter10
Other
Topics
How
12.
would you
Hexadecimal values
Write
13.
positive
are
a task edge
load a
the
models
that
text file
statement can be usedto return
15. What
system task impacts
16.
What
mechanism
17.
Write
a function
18.
Show
how
19. Given fileA,
an
write
that
can be
path name
UNIX
value is
to be printed?
shift of
a 10-bitvector.
used to emulatethe behavior
of the
statements
a task?
a pulse rejectionlimit?
an arithmetic
statement
the following
$time
to specify
performs
\"break\"
from
the
how
is used
a disable
absolute
preset clear
of an asynchronous
behavior
counter.
triggered
and
15.
0 through
\"ram.txt\".
14. What
\"continue\"
locations
from
memory
from a
read
C programming
of a file, say of
form
of
the
language. ID1ID2ID3I
functions:
- GetDirectoryName:returns - GetBaseName:returns the Assume that the maximum at most 512 characters.
the
name
number
of file
(i.e. ID1ID2ID3) (i.e..fileA) of characters in the path name can be
directory
of file
\342\226\241
206
11
Chapter
Verification
This
describes
chapter
a program used
for
exercising
VerilogHDL provides
for
techniques powerful
test
writing
the verifying that can constructs
and
bench is correctness of a design. be used to describe test benches.
A test
benches.
1.1
a Test Bench
Writing A
bench
test
has three
i.
To
generate
ii.
To
apply
main purposes.
stimulus this
stimulus
for simulation
(waveforms).
to the module
under test and collect output
responses.
Hi.
To compare
output responses
with
HDL provides a largenumberof ways we chapter, exploresomeofthese. A typical test Verilog
values.
expected to
write
bench is
a test
of the
bench. In this form:
207
Chapter
Verification
11
module Test_Bench;
//A test
bench
has
typically
and outputs.
no inputs
Local_reg_and_net_declarations
Generate_waveforms_using_initial_&_always_statements
Instantiate_module_under_test
Monitor_output_and_compare_with_expected_values
endmodule
is automatically
Stimulus
it in the
11.2
applied to the moduleunder test
by
instantiating
testbench module.
Waveform Generation main
two
are
There
approaches
i. Createwaveforms
and
to generate stimulus values. at certain discrete stimulus apply
time
intervals.
ii.
on the for
11.2.1
A
based on the state of the module. response
stimulus
Generate
output
Two types of waveforms a clock, and example,
other
typically is a
that
module,
is, based
One is a repetitive of values. set specified needed.
pattern,
of Values
Sequence
The best statement.
are the
of the
Here
to
way
is an
generate
a sequence
of values
is to
use
an
initial
example.
initial
begin
Reset #100
=
0;
Reset
= 1;
#80 Reset = 0; #30
Reset
= 1;
end
The waveform generatedis shown in
208
the
initial
statement
use delay
in
Figure
controls to
11-1. generate
The assignment a waveform.
statements Alternately,
11.2
SECTION
Generation
Waveform
Reset
Figure 11-1
Waveform
using
generated
delays can also be used to
intra-statement the
210
180
100
initial
statement.
a waveform
generate
as shown
in
example.
following
initial
begin
Reset = 0;
Reset
=
Reset
= #80
#100
Reset = #30
1;
0; 1;
end
Since
in the above procedural assignments are used, the delays If are absolute delays delays. preferred to be used, with intra-statement can be used delays, procedural assignments
blocking
statements
are
blocking shown in
relative
the
nonas
example.
following
initial
begin
Reset <= 0;
Reset
<=
Reset
<= #180 0
1
#100
Reset <= #210 1
end The
waveforms
one shown
produced in
To repeat initial
statement;
Figure
for all the
a sequence of values, use an this
is because
an
initial
always statement executesrepeatedly. createdfor
the
three initial statements are identical
following
to
the
11-1.
example
with
Figure an
always
always
statement executes
statement
11-2
shows
of an once while an only the waveform instead
statement.
209
Chapter 11
Verification
=35;
REPEAT_DELAY
parameter
CoinValue;
integer
always
begin
CoinValue =
0;
= 25;
CoinValue
#7
#2 CoinValue =
5;
CoinValue
= 10;
#6 CoinValue
= 5;
#8
#\302\253EPEAT_DELAy;
end
CoinValue
25
0 0
7
17
9
11.2.2
Repetitive
A repetitive
11-2
58
23
65
10
5
25
75
67
^|i
sequence generated usingan always
statement.
Patterns
It appears continuous
0
one cycle
!<
Figure
5
10
5
that
assignment
assign
a repetitive
of the
pattern
can simply
be created by
having
a
form:
#(PERIOD/2)
Clock =
~
Clock;
completely correct. The problemis that since Clock is a net net can be a its initial value is an z (only assignedin a continuous assignment), and ~z is x and ~x is x. Therefore the Clock gets stuck at the value x forever. But
this is not
What is neededis a way initial
statement.
initial
Clock = 0;
210
to
initialize
the Clock.
This can
be doneusing
an
Generation
Waveform
Clock has to be assigned values in But now
clock
(since only
register
data
types
11.2
can
and therefore the continuous statement), to an always statement. Here is a complete
initial
an
be changed
to
needs
assignment
data type
a register
be
SECTION
module.
generator
module
(Clk_A) ;
Gen_Clk__A
Clk_A;
output
reg Clk_A;
parameter
=
tPERIOD
10;
initial
Clk_A =
0;
always
A = ~
Clk
#(tPERIOD/2)
Clk
A:
endmodule
The
waveform
Clk
is shown
produced
in
Figure
11 -3.
15
20
A
0
10
Figure 11-3 Periodic An
way of
alternate
module
25
30
clock.
generating a clockis shown
next.
(Clk_B);
Gen_Clk_B
Clk_B;
output
reg Start;
initial
begin
Start #5
=
Start
1;
= 0;
end
nor
#2
(Clk_B,
Start,
Clk_B);
211
Chapter 11
Verification
endmodule
a clock
Generates
//
with on-off width
of
2.
of the nor gate to initial statement sets Start to 1, which forces the output be a 0 (getsout of x value). After 5 time units, when Start goesto 0, the the nor gate produces the clock with an on-off inversion of period of 4 time units. -4. shown in 11 The waveform is Figure produced
The
Start
:
Clk_B
Figure 11-4 A If a
clock
an
always
using
on-off
different
with
as shown
statement
the
15
17
clock.
controlled
is required, this
duration in
13
11
9
7
5
0
next
can be modeled
model.
Gen_Clk_C (Clk_C);
module
parameter output
= 5,
tON
tOFF = 10;
Clk__C;
Clk_C;
reg
always
begin
#tcw
Clk_C
= 0;
#tOFF
Clk_C
= 1;
end endmodule No initialization explicitly
loop
212
assigned.
To generate in an initial
is necessary
Figure
in this
case since the values 0 and waveform generated for
11-5 shows the
a varying on-off clock period statement can be used.
after a
1 are this
being module.
start-up delay, a forever
Clk C
15
10
module Gen_Clk_D
11.2
30
25
Varying on-off period.
11-5
Figure
SECTION
Generation
Waveform
(Clk_D);
Clk_D;
output
reg Clk_D;
parameter
START_DELAY=
5 ,
LOW_TIME
= 2,
HIGH_TIME
= 3;
initial
begin = 0;
Clk__D
# START_DELAY;
forever
begin #
LOW_TIME;
= 1;
Clk_D #
HIGH_TIME;
= 0;
Clk_D
end
end
endmodule
Figure11-6
shows
the
waveforms
produced.
ClkJD
5 Figure
7 11-6
10 12 15 17 Clock with
start-up
20
22
25
delay.
213
CHAPTER 11 Verification
To generate a is
Here
pulses. Even
clock module
that
pulses,
a repeat
generates
such
loop can be used.
a sequence
of
delays are parameterized.
on-off
the
clock
of
number
fixed
a parameterized
module Gen_Clk_E
(Clk_E);
Clk_E;
output
Clk_E;
reg
parameter Tburst
=
= 2,
Ton
10,
Toff = 5;
initial
begin =
Clk_E
1'bO;
(Tburst)
repeat
begin Toff
#
# Ton
Clk_E
l'bl;
Clk_E
1'bO;
end
end
endmodule Module Gen_Clk_E Tburst,
Ton
can
with different
instantiated
be
parameter values
for
and Toff.
module Test;
wire Clk_Ea, Clk_Eb,
Clk_Ec;
Gl
Gen_Clk_E
// Burst of
5
#(25,
Gen_Clk_E
on-time
pulses,
8,
10)
A clock using
214
on that
a continuous
is
Clk_Eb
is shown
phase-delayed
assignment.
in
off-time
of 5.
;
of
1 and
off-time
of 3.
(Clk__Ec) ;
on-time of
// Burst of 25 pulses, endmodule
The waveforms
2 and
of
on-time
(Clk_Eb)
3)
1,
#(5,
Gen__Clk_E
;
(Clk_Ea)
// Burst of 10 pulses,
Figure
8
and
off-time
of
10.
11-7.
another clock can be generatedby 11-8 shows the generatedwaveforms Figure from
for
Clk
Figure
module
following
8 11 12 15 1619 20
7
4
11-7
Fixed number
that
generates
two
clocks,
one of which is
Slave_Clk);
Phase (Master_Clk,
module
of clockpulses.
other.
the
from
phase-delayed
11.2
Eb
3
the
SECTION
Generation
Waveform
output Master_Clk,
Slave_Clk;
Master_Clk;
reg
wire
Slave__Clk;
parameter
= 2,
tON
tOFF = 3,
=
tPHASE_DELAY
1;
always
begin #tOJV
#tOFF
Master_Clk
= 0;
Master_Clk
= 1;
end
assign
= Master_Clk;
Slave_Clk
%tPHASE_DELAY
endmodule
X
Master Clock
0
5
2
7
z
1D
1
15
12
Slave_Clock
0 11
Figure
11-8
13
Phase-delayed clocks.
215
Chapter11
Verification
11.3
Testbench
11.3.1
A Decoder
Examples
Hereis a printed
of
description
there is a change of value
any time
Dec2x4
input
[0:3]
#
Z) ;
B, Enable,
(A,
Z;
Bbar;
wire Abar,
not
either
Enable;
B,
A,
output
on
Ins / Ins
timescale module
and its test
decoder
a 2-to-4
2)
(1,
VO (Abar', VI (Bbar,
,
A)
B);
nand #(4, 3) Bbar) ,
NO
(Z[0],
Enable,
Abar,
Nl
(Z[l],
Enable,
Abar, B) ,
N2
(Z[2],
Enable,
A,
Bbar),
Enable,
A,
B) ;
N3 (Z[3],
endmodule
module Dec_Test;
reg
wire
Dena;
Db,
Da,
[0:3]
Dz;
II Moduleunder test: Dl
Dec2x4
(Da,
Db,
Dena,
// Generate waveforms:
initial
begin Dena
= 0;
Da = 0;
Db =
0;
#10 Dena
216
=
#10 Da
= 1;
#10 Db
=
1;
1;
Dz) ;
the input
bench. Output or the output.
is
Section 11.3
Testbench Examples
#10
= 0;
Da
#10 Db
= 0;
#10 $stop;
end
// Print results: always @
Da or Db
or
(Dena
$display
or Dz)
time
(\"At
Da,
$time,
Db,
is
input
%t,
%b%b%b,
output
is
%b\"
Dz) ;
Dena,
endmodule
Hereis the
produced
output
output is 1111
At time
10,
input
sOOl
, output
At time
13,
input
sOOl
, output
time
At
At time
At time
20, input
101 ,
output
23, input
101 ,
output
26, input
101 , output
33, nput
111, output
30, nput
time
At
At time
111, output
At time
36,nput 111, output 40, nput sOll, output nput sOll, output
At time
50,
At time time
At
44,
54,
time
At
Ll.3.2
bench is executed.
is 000,
4, input
time
At
this test
when
nput
sOOl
nput
sOOl
, output , output
sun
sOlll
sOlll S0101 s 1101
1101
1100
1110
1110
1011
1011
sOlll
A Flip-flop
Hereis a that
a master-slave
of
description
D-type
flip-flop and a
testbench
it.
exercises
module
input output
MSDFF (D, D,
C, Q,
Qbar);
C;
Q, Qbar;
not NT1 (NotD,
D)
,
NT2
(NotC,
C) ,
NT3
(NotY,
Y) ;
217
Chapter
11
Verification
nand
ND1
(Dl,
ND2
(D2,
D, C) , C,
ND4
(Ybar,
ND5
(Yl,
ND6
(Y2,
Y, D2) Y, NotC) NotY, Qbar,
\342\226\240ND7 (Q, ND8
NotD),
Dl, Ybar) ,
ND3 (Y,
NotC), Yl) , Q);
Y2,
(Qbar,
, ,
endmodule
module Test;
reg
C;
D,
Q, Qb;
wire
MSDFFMl
C,
(D,
Q, Qb) ;
always
#5 C = ~C;
initial
begin D
= 0;
C = 0;
#40 D=
1 0
D=
#40
#40 D = 1
#40 D = 0
$Stop;
end
initial
$monitor
::\",
(\"Time=%t
Qb=%b\"
,
C,
D, Q,
$time,
\"
C=%b,
D=%b,
Q=%b,
Qb);
endmodule In this testbench,a monitoris set on the two inputs and the two outputs of the a value the specified argument string is flip-flop. Thus, anytime changes, printed
218
out.
Here
is the
output
produced
upon
execution.
:: C=0.D=0,Q=x,Qb=x
Time=
0
Time=
5 :: C=l,
D=0, Q=x,
Qb=x
10:: C=0,
Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time= Time=
11.4
25::C=1.
30:: C=0,
from
a text
file using
testing a 3-bit full-adder following
two
Section 11.4
Qb=l
Qb=l
Q=0.
D=0.
Qb=l
D=0. Q=0,
Qb=l
D=1.Q=0.
Qb=l
35::C=1. D=0,Q=0,Qb=l 40::C=QD=l.Q=0.Qb=l 45::C=1,
50: 55::C=1.
:C=0.D=l,Q=l.Qb=0
D=l.Q=l,Qb=0
60:
:C=0, D=l,Q=l,Qb=0
65:
:C=1. D=l,Q=l,Qb=0
70:
:C=0,D=l.Q=l.Qb=0
75::
:C=1,D=l,Q=l,Qb=0
80:
:C=Q
85:
:C=1,D=0,
D=0,
Q=l,Qb=0
Q=l.Qb=0
90: : C=0, D=0.Q=0.Qb=l
95: :C=1,D=0,
Q=0,
100::
C=0,
105::C=1. 110:: C=0,
115::C=1, 120
125
D=0. Q=0,
Qb=l
Qb=l
D=0.Q=0,Qb=l D=0,
Q=0,
Qb=l
D=0,Q=0,Qb=l
::C=0, D=1,Q=0. Qb=l
Qb=l ::C=1,D=1.Q=0,
130
::C=0,
135:
:;C=1,
D=l,Q=l,Qb=0
D=l,
140: ::C=0,
Q=l,Qb=0
D=l,Q=l.Qb=0
145 ::C=l,D=l.Q=l,Qb=0
150 ::C=0, D=l,Q=l,Qb=0
155 ::C=l,D=l,Q=l,Qb=0
a
from
read
D=0. Q=0,
File
20:: C=0.D=0.Q=0.Qb=l
Reading Vectors It is possibleto
Q=0,
D=0.
15:: C=l,
a Text
from
Vectors
Reading
vectors
Text
File
(could
contain
the $readmemb system circuit.
Assume
stimulus and expectedvalues) task.
that file
Here is such an example of \"test.vec\" contains the
vectors.
219
Chapter
11 Verification
ExpectedSum
t
The
first
bit is last
bits correspond to
three
Expected Cout
A,
input
next
the carry-in bit, eight to tenth bits are the expected carry-out. Hereis the
for input B, the expected sum result and
bit is
three
bits are
module
full-adder
and
next the
its test-
bench.
module Adder!Bit input
Sum,
Cin,
B,
(A,
Cout);
Cin;
B,
A,
output
Sum, Cout;
assign
Sum
assign
Cout
-
A
(A = (A
A
B) &
B)
Cin; \\
(A
& Cin)
\\
(B
& Cin)
;
endmodule
Adder3Bit
module
(First,
Second, Carry_In,
Sum_Out,
First,
[0:2]
input
Carry_Out)
;
Second;
input Carry_In;
output [0:2]
Sum_Out;
Carry_Out;
output
wire
[0:1]
Car;
AdderIBit Al
(First[2],
Sum_Out[2], A2
(First[l],
A3
(First[0],
Sum_Out[0],
endmodule
220
Second[2],
Carry_In,
Car[l]), Second[l], Second[0],
Car 11], Car[0],
Carry_Out) ;
Sum_Out[l], Car[0]),
from
Vectors
Reading
a Text
Section 11.4
File
module TestBench;
parameter
reg [1:BITS] reg
[0:2]
reg
Cin,
WORDS = 2;
=11,
BITS
Vmem
A, B,
[1:WORDS];
Sum_Ex;
Cout_Ex;
J;
integer
wire [0:2] wire
Cout;
II
Instantiate
Sum;
the module Fl
Adder3Bit
(A,
under test. Sum, Cout);
B, Cin,
initial
begin (J =
for
Vmem);
(\"test.vec\",
$readmemb
1; J
<=
J =
WORDS;
J + 1)
begin Sum_Ex,
Cin,
B,
[A,
// Wait for 5
#5;
if
(
(Sum
$display
!==
Cout_Ex]
=
Vmem
[J]
Sum_Ex)
\\ \\
(Cout
!==
Cout_Ex)
(\"****Mismatch on vector Vmem
;
time units for circuit to settle. )
%b
*****\",
%b\",
Vmem
[J]);
else
$display
(\"No
mismatch
on
vector
[J]
) ;
end
end
endmodule A memory bits in each
Vmem
vector
first
is
and
the word size correspondsto the defined; the number of words in memory corresponds
number
of
to the
the file. The $readmemb system task readsthe vectors into the memory Vmem. The for-loop goes through each of the memory that is, each vector, applies theseto the module under words, for the A waits module to be stable and the module test, probes outputs. conditional statement is used to compare expected output values and the If a to monitored values. is the mismatch occurs, any message printed output is is Here the when the above test bench executed. output. output produced Sincethere are no errors in the model, no mismatchesare reported.
number of in
the
file
vectors in
\"test.vec\"
221
Chapter
11
Verification
11.5
Vectors to a
Writing
01001111100
vector
on
mismatch
No
01001001000
on vector
No mismatch
Text File
are on testbench examples, we saw how values be a file well of in a can to as design printed printed to output. Values signals to a file such as $fdisplay,$fmonby using the display system tasks that write Here is the same testbench exampleas is the previous itor and $fstrobe. vectors and in this case, the testbench prints out all the but section, input In
the
observed
section
previous
file \"mon.out\".
to a
vectors
output
module F_Test_Bench;
parameter
=
BITS
WORDS -
11,
reg
[
reg reg
[0:2] A, B, Sum_Ex; Cin, Cout_Ex;
1: BITS]
Vmem
2;
WORDS];
[1:
J;
integer
wire [0:2] wire
Cout;
II
Instantiate
Sum;
the module Fl
Adder3Bit
(A,
B, Cin,
under test. Sum, Cout);
initial
begin:
INIT_LABEL
Mon_Out_File;
integer
= $fopen
Mon_Out_File
for
(J =
1; J
<=
(\"mon.out\; Vmem);
(\"test.vec\",
$readmemb
WORDS;
J =
J + 1)
begin B,
Cin,
Sum_Ex,
//
Wait
for 5 time
if
((Sum
$display
!==
5u2i!_Ex)
) ;
=
Vmem[J]
;
units for circuit
| |
(\"****Mismatch Vmem[J]
222
Cout_Ex)
[A,
#5;
to settle.
!== Cout_Ex) ) (Cout %b on vector *****\302\273,
Some More
Section 11.6
Examples
else
$display
on
mismatch
(\"No
vector
%b\", Vmem[J] ) ;
the input and output vectors (Mon_Out_File, \"Input = %b%b%b, Output =
// Write
$fdisplay
Cin,
A, B,
Sum,
to
a file:
%b%b\",
Cout);
end
;
(Mon_Out_File)
$fclose
end
endmodule
Hereis what
11.6
11.6.1
in the
is contained
file
after
\"mon.out\"
Input
= 0100100,
Output = 1000
Input
= 0100111.
Output
simulation.
= 1100
Some More Examples A
Clock
Divider
A complete testbench that uses shown next. The module under test written into a file for later comparison. Div (Ck,
module
Ck,
input
output
the
waveform
is called
application
Div. The
output
method is responses
are
Reset, TestN, Ena); TestN;
Reset,
Ena;
reg [0:3] Counter; always @
(posedge
if
Ck)
begin
(-Reset)
Counter = 0;
else
begin 223
Chapter
11
Verification
(~ TestN)
if
Counter =15;
else Counter
=
Counter
+ 1;
end
end
assign
=
Ena
== 15)
(Counter
? 1
: 0;
endmodule
module
Div_TB;
Out_File;
integer
reg Clock, Reset, TestN;
wire Enable;
initial = $fopen
Out_File
(\"out.vec\;
always
begin
#5 Clock = #3
0;
= 1;
Clock
end
Div Dl (Clock, Reset, TestN,
Enable);
initial
begin
Reset = 0; #50
= 1;
Reset
end
initial
begin
TestN =
0;
TestN
#100
= 1;
#50 TestN = 0; #50
$fclose
;
(Out_File)
$finish;
//
Terminate
simulation.
end event // For // write to file. every
224
on
the
Enable
output
signal,
More
Some
SECTION 11.6
Examples
initial
$fmonitor (Out_File,
\"Enable
to
changed
Enable,$time);
at
%b
time
%t\"
endmodule
Here is the
in the
contained
output
\"out.vec\" file.
Enable changed to x at time Enable to 0 at time changed
0
8
Enable changed to 1at time Enable
to 0
changed
56
at time
104
Enable changed to 1at time
11.6.2
A Factorial
152
Design
a different approach to stimulus generation; in value is generatedbased on the state of the module under test. a finite-state machine for which This approach is useful in testing different is applied based on the machine's Consider a stimulus state. input in is the of an which the to factorial number. input design objective compute The handshake mechanism between the module under test and the test bench This
this
illustrates
example
case
the stimulus
modelis shown
in
Figure
11 -9.
Reset
(^Driver
j
Start
TEST
BENCH
under
test
FacjDnt Exp_Ont
FACTORIAL
Done
(^Monitor^)
Figure
Module
Clock Data
11-9
The Reset input The Start signal is the output complete,
between test
Handshake to
the
Done
resets the factorial model input is applied. When set to indicate that the computed
module
set after
the
is
benchand entity
Data
test.
under
to
an
initial
computation
result
state. is
appears
225
Chapter 11 on
Verification
the
outputs. The resultingfactorial
and Exp_Out
FacjOut
value
is Fac_Out
on Data starting from data The test bench model provides input Start of one. It applies the data, sets the values 1 to 20 in increments signal, the next Error waits for the Done signal, and then data. input messages applies correct. The if the values appearing at the output are not are printed out for the module and the test bench follows. descriptions
* 2ExP-0ut.
timescale Ins / Ins FACTORIAL
module
Clk,
StartSig,
(Reset,
Data, Done,
FacOut, ExpOut);
input Reset, StartSig,
Clk;
Data;
[4:0]
input
Done;
output
output [7:0] FacOut,ExpOut; reg
Stop;
reg
[4:0]
InLatch;
reg [7:0] Exponent,Result;
integer I;
initial
=
Stop
1;
always @
Clk)
(posedge
if
begin
== 1)
( (StartSig begin
Result
&&
(Stop
==
1)
&&
= 1;
Exponent =
0;
= Data;
InLatch
Stop = 0;
end
else
begin
if
(
> 1)
(InLatch
&&
(Stop
begin
Result InLatch
= .Result = InLatch
end
if
226
<
(InLatch
Stop
= 1;
1)
*
InLatch;
- 1;
== 0) )
(Reset
== 1) )
SomeMore Examples Section11.6
//
Normalization:
for
1=1+1)
I<= 5;
= 1;
(I
if (Result
>
256)
begin
= Result
Result
Exponent
=
I 2; + 1;
Exponent
end
end
end
assign
Done
assign
FacOut
assign
ExpOut
=
Stop;
= .Result; =
Exponent;
endmodule
module
FAC_TB;
parameter
OUT_MAX = 8 ;
= 5,
IN_MAX
RESET_ST= 0,
parameter
START_ST
= 3
WAIT_RESULT_ST
=
1,
APPL_DATA_ST
= 2,
;
Start;
reg C2A:, Heset,
wire Done;
reg
:
[IN_MAX-1
wire
Data;
0] :
[OUT_MAX-l
Fac_Out,
0]
Exp_Out;
Next_State;
integer
parameter
MAX_APPLY
=20;
Num_Applied;
integer
initial
Num_Applied = 1;
always
begin: #6
CLK_P
= 1;
Clk
#4 Clk = 0
;
end
always @
Clk)
(negedge
II
Falling
edge transition.
case (Next_State) RESET_ST:
begin
Reset
= 1;
Start
= 0;
227
Chapter11
Verification
= APPL_DATA_ST;
i\\fext_State
end APPL_DATA_ST:
begin
Data = Num_Applied; = START_ST;
Next_State
end
START_ST :
begin
Start
=
1;
= WAIT_RESULT_ST;
Wext_State
end WAIT_RESULT_ST:
begin
Reset
= 0;
Start
= 0;
wait (Done== if
1)
;
==
(Num_Applied
* ('hOOOl \302\253Exp_Out)) result from factorial\",
Fac_Out $display
(\"Incorrect \"
Num_Applied
if
for
model
value
input
= Num_Applied
%d\",
Data);
+ 1;
< MAX_APPLY)
(Num_Applied
= APPL_DATA_ST;
Next_State
else
begin
$display (\"Testcompleted successfully\;
$
//
finish;
Terminate
simulation.
end
end
default : = START_ST;
JVext_State
endcase
// Apply FACTORIAL
to module Fl
under test: (Reset,
Start,
Fac_Out, Exp_Out) endmodule
228
Data, Done,
Clk, ;
Some More
A
Here is
its
a modelfor
test
detector.
a sequence
consecutive one's on
data
the
Figure 11-10 shows the
of clock.
edge
Section 11.6
Detector
Sequence
of three
Examples
line. state
The model checks for a sequence Data is checked on every falling Here is the model with diagram.
bench.
module
(Data, Clock, Detect3_ls);
Count3_ls
input Data, Clock; Detect3_ls;
output
Count;
integer
reg Detect3_ls;
initial
begin = 0;
Count
= 0;
Detect3_ls
end
always @
begin
Clock)
(negedge
(Data == 1)
if
+ 1;
= Count
Count
else
Count = 0;
if
(Count
>=
3)
= 1;
Detect3_ls
else
= 0;
Detect3_ls
end endmodule
module
Top;
reg
Data,
integer
Clock;
Out_File;
II Instantiate Count3_ls
module
Fl
under
test;
(Data, Clock, Detect);
initial
begin
229
Chapter
11
Verification
- 0;
Clock
forever Clock
#5
-
-Clock;
end
initial
begin
Data =
0;
= 1;
Data
#5
#40 Data = 0 Data
#10
= 1
#40 Data = 0 #20
//
$stop;
Stop simulation.
end
initial
begin
//
monitor
Save
Out_File
information
= $fopen
in
file.
(\"results.vectors\;
$fmonitor (Out_File, \"Clock
= %b,
Clock,
Data,
= %b. Detect);
Data
Detect
end
endmodule
Figure 11-10 A
230
sequence
detector.
=
%b\",
Section 11.7
Exercises
1.7
Exercises
1.
and
an on-period
with
a clock
Generate
an
and 10ns
of 3ns
off-period
respectively.
2.
HDL model that
a Verilog
Write
the
generates
shown
waveform
in
Figure
11-11.
a clock
Generate
4.
ClockV that
[Hint:
Using
Write
5.
a test
bench
that
module
a
starts
clock
positive
is set to
two clocks, ClockA while ClockB starts with
have
is 2ns.
ClockB is synchronizedwith
same
on-off
the
of ClockA
edges
of 40ns. the
but
such
ClockA
ClockB.
and a delay
period, on-period is Ins while
clocks
the
a
an
checks
detector
edge for a pattern 10010. If 1, else it is set to a 0.
generates
of 10ns
a delay
with
the clock Clk_D The phase-delayis 15ns. may not be appropriate].
from
phase-delayed
a sequencedetector.The
that tests the output
is found,
Write
waveform.
A
Gen_Clk_D (Figure 11-6). a continuous assignment statement
input data stream on every
a pattern
is
23
module
in
described
30ns
27
22
16
11-11
Figure 3.
17
15
10
Both
off-period
has
opposite
polarity.
6.
Describe a behavioral
model with described values
and
two
test the
within
monitored
7. Describean on
a
4-bit
ALU
model for
bench.
All
a 4-bit
input
that
operands.
the expectedresult from
and
itself. Dump the values to a text file.
test bench output
Write a
test bench that
expected
input
all the relational
performs a text
/ subtracter.
adder
values
values,
Exercise this values
are
expected
operations (<, <=,>,>=) reads
the
test patterns
and
file.
231
Chapter 11
Verification
8.
a module
Write
that
shift of an input vector. with a default value of as a parameter with a default value of a module which performs an arithmetic an arithmetic
performs
of the
size
Specify the
a parameter
as
input
specify the amount of shift a test bench that tests such on a 12-bit vector and shifts
9.
clock of an of
period
10.
the
edge reference
on an
input
clock].
that
a model
Write
shift
8 times.
times clock multiplier. The input is a reference The be should output synchronized with frequency. of the reference clock. [Hint:Determine the clock
unknown
positive
every
1. Write
for an N
model
a
Write
Also
32.
displays
the time
whenever
a 0
occurs
to 1 transition
clock.
clock pulses is Count_Flag 1.If count exceeds at the the Overflow MAXjCOUNT, output is set and counter stays to limit. The rising edge of Count_Flagcausesthe counter MAXjCOUNT reset to 0 and start Write a test bench to test this model. counting again.
11. Write
a model for
12.
a model
Write
of 3. The counter The
a 4-bit
13.
Gray
gets
a
toggle
is 1,
asynchronously
the
output
code
reset
counter.
when the
it to a size Default variable Resetis 0.
negative edge of a clock.Then instantiate test bench and test the model.
on every
code counter
behavioral
Write
the number of
during the period
for a parameterizedGray
transitions
counter
that counts
a counter
occur
that
(positive edges)
in
model toggles
a
for an asynchronous reset toggle flip-flop. between 0 and 1. If toggle is 0, output
in previous state. Then, using the specify block,specify a setup 2ns and a hold timeof 3ns.Verify the model a test bench. using
If stays
time
of
\342\226\241
232
12
Chapter
Examples
Modeling
This
Verilog
L2.1
chapter
A
of hardware
modeling examplesusing
Elements
Simple
Modeling
HDL
a number
provides
HDL.
basic
hardware
as a
net data
is a
element
type. Considera
describednext.
wire. 4-bit
A
and
wire
can
gate,
be modeled the behavior
in
Verilog
of which is
timescaleIns / Ins module
input
And4
B,
(A,
[3:0] B,
output
[3:0]
assign
#5
A
C) ;
C;
A; = B & C;
endmodule
233
Chapter
12 ModelingExamples
The delay represented
by
model
this
logic is specifiedto be 5ns.The
& (and)
the
for
is shown
in
12-1.
Figure
B[l] C[l]
B[2] C[2]
B[3] C[3]
C[0]
B[0]
gate delay
A[l]
A[2]
A[3]
Figure
12-1
A
(xor)
= 5ns
A[0]
A 4-bit
This exampleand the one following modeled as expressionsin continuous modeledas net data types. For example, represents
hardware
and gate.
show
that
Wires can
following description,
that connects
Boolean_Ex
input
E);
D;
output
wire
(D, G,
E;
G,
F;
assign F = - E;
assign
D
= F A G;
endmodule
D
Figure
A
the following behavior shown in Figure 12-3.
Consider representationas
12-2
combinational
circuit.
and its correspondinghardware
be
F
the output of the ~ (not) operator to the input 12-2 showsthe circuitrepresented the module. by operator. Figure
a wire
module
234
can be
equations
statements.
assignment
in the
Boolean
of
the
Simple
Modeling
Elements
SECTION 12.1
module Asynchronous;
wire
D;
C,
B,
A,
assign
C=A
reassign
A =
|
~ (B
&
C) ;
endmodule
\342\226\240-^Of^O^'
Figure 12-3
An
asynchronous
loop.
asynchronous loop. If the model were simulated with a time would never advance because 1, D = 0), simulation the two assignments. the simulator would always be iterating between The be time be two extracaution iteration would zero delays. Therefore, must that have exercised when values are assigned to nets using continuous assignment are used in expressions. zero delay and when these samenet values circuit has an
This
of values
set
certain
In certain
(B =
cases,
it
is
desirable
to have
such an asynchronous
loop. An
such an asynchronous represents loop is shown next; the statement waveform with a cycle of 20ns. Its hardware representationis shown an always statement needs an initial statement in Figure 12-4. Note that such that initializes the register to eithera 0 or a 1, else the register will be stuck of
example
a
periodic
the
value
at
x.
reg Ace;
initial Ace = 0; always
#10
Ace
= ~
Ace;
Elements of a vector net element
called
bit-select,
or a
or
a register
slice called
can be
accessed, as eithera single
part-select.Forexample,
235
CHAPTER
12
Examples
Modeling
Ace
Ace
Figure 12-4 reg
A
clock
generator.
A;
reg [0:4]
C;
reg [5:0] B,
D;
always
begin
D[4:0]
= B[5:l]
| C;
// D[4:0] andB[5:l]
are part-selects.
D[5]=A&B[5]; //D[5]
andB[5]
are
bit-selects.
end
The
first
D[4]
D[3]
implies:
assignment
procedural
= B[5] |
C[0];
=
C[l];
B[4]
I
and vectors can
Bit-selects, part-selects For example,
be concatenatedto form
larger
vectors.
wire
[7:0] C, CC;
wire
CX;
assign
C = {CX,
CC[6:0]};
It is also possibleto referto an element computable only at runtime. For example, Adf
= Plb
[K] ;
of a
vector whose
index value
is
Modeling SimpleElements whose output is Adf,
a decoder
implies
Plb is a vector;it
behavior
the
models
Shift operationscan be performed shift
Alternately,
K specifies
decoder. the
using
be modeled
can
operations
and
of the
the selection
the
address.
shift operators.
predefined
using
12.1
SECTION
concatenation
operator.
For example,
wire
[0:7]
assign
Z =
assign assign
Z;
A,
A[0]};
{A[l:7],
Z
=
[A[l],
Z
=
{A[l:7],
// // //
A[0:6]}; 1'bO};
A
left-rotate
A
right-rotate
A
left-shift
operation. operation. operation.
called part-select,can also be used in expressions. in which the consider a 32-bitinstruction register, Instr_Reg, denote the address, next 8 bits representthe opcode,and the of a vector,
Subfields
For example, 16
first
bits
8 bits
remaining
Given the following
declarations,
Memory [0:1023];
[31:0]
reg
the index.
represent
wire [31:0] Instr_Reg;
wire [15:0]
Address;
Index;
wire
[7:0]
wire
[0:9] Prog_Ctr;
Op_Code,
wire Read_Ctl; one
way
to
continuous
are
statements.
assignment
to specific
assigned
assign
Address
assign
Op_Code
InstrJReg is to use three of the
The part-selects
instruction
register
wires.
assign Instr_Reg =
assign
information from the
the subfield
read
;
[Prog_Ctr]
Memory
= Instr_Reg[31:16] =
Instr_Reg[
15:8]
Index = Instr_Reg[l
-. 0]
; ;
;
always
Read_Ctl)
@(posedge
Task_Call A assignment
tristate statement.
gate An
(Address, Op_Code,Index);
be modeled is: example
can
behaviorally using a
continuous
237
Chapter 12
Examples
Modeling
has
12.2
a high
impedance
then
the in
multiplies
The
Enable
is 0,
input C.
it with
first modeling are
statements
C,
(A, A;
input
[0:3]
C;
input
ClkB;
output [0:11] wire
buffered
Z;
SI; = Si
*
C;
assign
Z
assign
SI = ClkB ?
endmodule
multiplier.
style is the dataflow style to model the circuit.
[0:7]
input
A
in which
used
module Save_Mult_Df
238
When
Triln.
of the
examples
gives
Figure 12-5
assignment
of
TriOut
three different modeling styles dataflow, behavioral, and structural. Considerthe circuit language: of the input A into a register and 12-5, which saves the value Figure
section
This
shown
value
: l'bz;
Styles of Modeling
Different
provided by
gets the value.
1, TriOut
is
Enable
When
? Triln
= Enable
TriOut
wire
A
:
SI;
ClkB,
Z) ;
continuous
Different Styles of
does
This representation it.
describes modeled
program
module
statement
with
Save_Mult_Seq
been
is to
(A,
model it
C,
as
a sequential
block.
a sequential
Z) ;
ClkB,
A;
input
[0:7]
input
[0:3] C;
input ClkB; output [0:11]
Z;
Z;
[0:11]
reg
implicitly
is very clear. The registerhas
the circuit
describe
to
way
an always
using
but
12.2
control.
a clock
The second
structure,
any
imply
directly
its functionality
However,
using
not
SECTION
Modeling
always @
(A
C or
or
begin:
ClkB)
SEQ
so that a local register SI
The block is labeled can be declared.
II II
[0:7] si;
reg
if
(ClkB)
Si
= A;
= Si
Z
* C;
end
endmodule
This model alsodescribes the either
an if
but
behavior,
In this case,
or implicitly.
explicitly
does
not imply any
the register has
been
structure,
modeled
using
statement.
The third assuming
way
the Save_Mult
to describe
the existence of an
8-bit
register
module SaveJiult_Netlist [0:7]
A;
input
[0:3]
C;
input
ClkB;
input
output [0:11] Si,
(A,
circuit is to model it 8-bit multiplier.
as
a netlist
and an
C,
ClkB,
Z) ;
Z;
S3;
wire
[0:7]
wire
[0:15] S2;
239
Chapter12
Examples
Modeling
Rl
Reg8
Mult8 endmodule
Ml
the structure, but the behavior is and and Mult8 modulenames are arbitrary, have any behavior associated with them. is because
This
could
they
Of
describes
the Reg8
three different modeling styles, the behavioral the fastestto simulate.
these
is generally
12.3
.Z(Z));
C}) ,
.B({4'b0000,
(.A(S1),
This description explicitly unknown.
.Dout(Sl));
.Clk(ClkB),
(.Din(A),
of modeling
style
Modeling Delays a 3-input
Consider continuous
assignment,
assign statement
This
such
represents
the
on
appears
signal
nor
gate. Its
as shown
in
behavior can be modeledusing
the
#12 GatejOut = ~
(A
example.
following
\\
B
\\
C) ;
the nor gate with a delay an event on signal A, B, An event could be any GatejOut.
models time
from
of 12 or C value
delays
in
the
time
wereto be explicitly
delay
value
for example,
change,
0.
and the fall time such as: assignment,
rise
the
time units. This
until the result
-> z, x -> 0, or1 -> If
a
use
modeled,
x
two
assign #(12, 14) Zoom = ~ (A \\ B \\ C) ; and /* 12 is the rise delay, 14 is the fall delay = 12 is the transition to x 14) min(12, delay */ In
is the
case turn-off
of logic delay,
that can be assignedthe value z, a third delay can also be specified, such as:
assign #(12,14, is // Rise delay
10)
12,
= A
Zoom
fall
//is min(12,14,10),
and
240
> B
delay turn-off
? C : 'bz; is 14,
transition
delay
is
10.
value, which
to x delay
ModelingDelays delay values can
of the
Each
the following
as in
such
notation,
also be represented using
min.typ.max
example.
= A > assign #(9:10:11, 11:12:13,13:14:15)Zoom
A
Delays in the specifying primitive
delay
and
The output
rise
been
has
3)
in
For
Al
'bz;
and UDPs can be modeledby instances instantiation. Here is an example of a 5-input
In2,
ml,
(Ot,
In3,
In4, In5) ;
specified as 2 time units
has been
delay
and
the
output
at port boundaries can be specifiedusing a here is an example of a half-addermodule.
a module
example,
module
Hal\302\243_Adder
input
(A,
B, S,
specify
C) ;
B;
A,
output
fall
time units.
as 3
specified
Delays
block.
in the
C:
gate.
and #(2,
delay
gate
primitive
values
B ?
be an expression.
in general
could
value
delay
12.3
SECTION
S,
C;
S)
=
(1.2,
0.8);
=
(1.0,
0.6);
=
(1.2,
1.0);
=
(1.2,
0.6);
specify (A
=>
(B => S) (A
=>
C)
(B => C) endspecify
assign
S=A
assign
C = A
A
\\
B; B;
endmodule
Instead
of modeling
been modeledusing
the delays in a specify
the
block.
continuous
Is there
assignments,
a way
to
specify
the delays
have
the delays
is to use the SDF (Standard Format) Delay and the backannotation mechanism possiblyprovided simulator. by a Verilog If this information needsto be specifiedin the Verilog HDL model explicitly, external to
the
module?
One option
1. SeeBibliography.
241
Chapter
12
Modeling Examples
one approachis to createtwo module each
a different
with
module Half_Adder input
modules
dummy
set of
on top
of the Half_Adder
delays.
(A,
S, C) ;
B,
B;
A,
output
S, C;
assign
S=A
assign
C = A
A
1
B; B>
endmodule
module Ha_Opt
input
(A,
C) ;
B, S,
B;
A,
S, C;
output
specify (A
=>
=
S)
(B => S) = (A
=>
=
C)
(B => C) =
(1.2, 0.8)
(1.0, 0.6)
(1.2, 1.0)
(1.2,
0.6)
endspecify Hi
Hal\302\243_Adder
B, S,
(A,
C)
endmodule
module Ha_Pess (A,
B,
C)
S,
,\342\200\242
B;
A,
input
S, C;
output
specify (A
=>
S)
(B => S) {A => =>
(B
=
(0.6,
0.4)
=
(0.5,
0.3)
C) = (0.6, 0.5) C) = (0.6, 0.3)
endspecify Half_Adder
H2
(A,
B, S,
C)
endmodule With
and
these
depending
the module Half_Adder on which delay mode that you
modules,
appropriatetop-levelmoduleHajOpt orHa_Pess. 242
is independentof would
like to
any
delays,
use, simulate the
SECTION 12.3
Delays
Modeling
TVansport Delays
inertial with
assignment
and gate-level
assignments
using delay. Transport delay can be modeled an intra-statement delay. Here is an example.
module
primitives
a non-blocking
(WaveA, DelayedWave);
Transport
parameter
= 500;
TRANSVORTJDELAY
WaveA;
input
output
reg
continuous
in
specified
Delays
model
DelayedWave;
DelayedWave;
always
<=
DelayedWave
&{WaveA)
WaveA;
#TRANSPORT_DELAY
endmodule
contains a non-blocking assignment
always statement statement delay. Any
change
TRANSPORT_DELAY
in the
The
on WaveA example
of
WaveA
delayed appears on DelayedWave by such a delayed waveform is shown in
WaveA
0 3
an
intra-
DelayedWave
that
TRANSPORT_DELAY;
appears
an
12-6.
Figure
At-
7?
io
56
with
gets scheduled on future. Consequently, a waveform on
..
DelayedWave
77^
\"^
1 500
Figure
503
506
510
12-6 Transport delay example.
243
Chapter12
12.4
Examples
Modeling
Conditional
Modeling
conditions can be modeledusing conditional operator, or using an if assignment Let us consideran a an statement. or case statement in always circuit. Its behavior can be modeled using a continuous
Operationsthat statement arithmetic assignment
certain
under
occur
with a
continuous
a
either
Operations
logic as
below.
shown
module
Simple^ALU
input
[0:3]
input
PM;
[0:3]
output
C,
PM, ALU) ;
: A
- B;
C;
ALU;
ALU = PM ?
assign
B,
{A,
B,
A,
+ B
A
endnodule A
of the statement
also be
can
multiplexer
select linesare first the
selects
determined
(Sel,
C,
B,
A,
A, B,
Sel;
[0:1]
input output
is to
that
D;
Mux_Out;
reg
Mux_Out;
reg
Temp;
parameter
=
MUXJDELAY
15;
always @
A or
or
(Sel
case
(Sel)
0:
Temp
1:
Temp = :
= A;
B;
Temp
= C;
Temp
= Q;
3: endcase
244
B or C or
PI
begin:
2
an
always
based
statement.
on this value,
be assigned
D)
C, D,
Mux_Out)
The value
a case
to the output.
Ins / Ins
Multiplexer
input
and,
input
appropriate
timescale module
modeled using
;
Modeling SynchronousLogic =
Mux_Out
SECTION
12.5
Temp;
%MUX_DELAY
end
endmodule
could also have
The multiplexer
modeled
been
a continuous
using
assignment
of the form:
assign
(Sel
L2.5
So far combinational
been
this
in logic.
provided
in
? C
== 0) ? A : : (Sel == 3)
== 1)
(Sel
?
D
:
?B :
l'bx;
language
data type infers register synchronous logic is by controlling
every
examples that
we
have
seen
are
logic, the register data type synchronous to model registers and memories.However
modeling
the
2)
most of the
chapter, For
==
Logic
Synchronous
Modeling
= (Sel
Mux_Out
%MUX_DELAY
synchronouslogic.
A
the
common
not
to model
assignment.
how shows Consider the following example,which can modela synchronous D-type flip-flop. edge-triggered
timescale Ins / Ins module D_Flip_Flop(D,
way
has
controlling
a register
Q) ;
Clock,
D, Clock;
input
output Q;
reg
Q;
always
Clock)
@(posedge
Q = #5
D;
endmodule The semanticsof
edge
on
change behaviorin Given this
Clock,
(a register the
always
module,
the
always
statement
else
expresses the semanticsof a D-type register can be modeledasfollows.
statement an 8-bit
that when there is a rising the value of Q does not 5ns, a new value). The assigned
indicates
the value of D after it is retains its value until
Q will get
flip-flop.
245
Chapter12
Modeling
Examples
module
parameter input
:
[START
input
STOP] :
[START
[START :
Q;
STOP]
STOP] Cak;
D_Flip_Flop
DFFO
:
[START
buf
STOP = 1; D;
= 0,
START
Clock;
output wire
Clock);
(D, Q,
Register8
.Clock
(.D(D),
STOP]
(Cak) , .(?((?));
(Cak[0], Cakll], Cakl2],Cakl3],Cakli],
Bl
Clock);
Cakll],
Cakl6],
CaklS],
endmodule latch Consider a gated cross-coupled
its dataflow
circuit,
as shown
in Figure
12-7, and
model.
Q
Qbar
12-7
Figure module
input output
Gated^FF
assign
;
Q, Qbar;
S2;
assign si assign
Qbar)
Q,
latch.
gated
G;
A,
wire Si,
assign
G,
{A,
A
=
~
(A
&
G) ;
S2 = ~ {Si & G) ; Q = - (Qbar & Si) Qbar = - (Q & S2)
; ;
endmodule
In this
example, the semantics of the
continuousassignmentsimpliesa latch.
can be modeledas an
A memory
ASIZEis the number bits
SECTION 12.5
Logic
Synchronous
Modeling
of
on the
bits
Here is an example. of registers. array of address port, and DSIZEis the number
data port of the RAM.
on the
module RAM_Generic input
[ASIZE-1
input
[DSIZE-1 : 0]
input
:
Data_Out,
Data_In,
(Address,
RW)
;
DSIZE = 4 ;
= 6,
ASIZE
parameter
Address;
0]
Data_In;
RW;
Data_Out;
: 0]
[DSIZE-1
output
reg [DSIZE-1 : 0] Data^Out;
reg [0 :
[0
Mem__FF
DSIZE-1]
: 63];
always @
{RW)
if
II
(RW)
Read
Data_Out = Mem_FF
[Address]
;
else
Mem_FF
= Data_In;
[Address]
endmodule
edge-triggered
For
controls.
modeled
as
also
can
logic
Synchronous
example,
be
modeled
a level-sensitive
using level-sensitive or D flip-flop can be
follows.
module
Level_Sens_FF Strobe, D;
input
output
Q, Qbar;
reg
Qbar;
Q,
(Strobe,
D,
Q,
Qbar);
always
begin
wait
(Strobe
== 1) ;
= D; Q
Qbar
= ~D;
end
endmodule When
Strobe
becomes
0, the
longer affects
1, any events on D are transferred values in Q and Qbar are retained,and the of Q and Qbar. values is
to Q, but any
when
change
Strobe
in input
D no
247
Chapter12
Examples
Modeling
It is
to understand
important
determinethe inferenceof between
the
the
procedural
Consider
logic.
synchronous
the
assignment to difference
Bodyl and Bodyl.
two modules,
following
of a
semantics
module Bodyl;
reg
A;
A = 0;
initial
always
A
= ~A;
endmodule
module
Body2;
wire Clock;
reg
A;
A = 0;
initial
always @
(Cloc*)
if A
(- ClocJc) = - A;
endmodule
impliesthe circuit shown the in Figure 12-9. circuit shown implies
Module Body]
in
Figure
12-8,
while module
Bodyl
X ^>o\342\200\224i-
12-8
Figure
If Bodyl weresimulated
due to the zerodelay In module Bodyl, the
asynchronous
Clock signal, and thereafter, the
248
output
of
flip-flop.
as
value
of any
No flip-flop
implied.
would go into an endless loop time does not advance). loop (simulation of the A is latched only on the falling edge on A of do not affect (input changes flip-flop) is,
simulation
A Generic Shift
L2.6
A
Shift
Generic A
for-loop
with
instantiatedin
another
12.6
implied.
flip-flop
register can
shift
serial-out be modified
it can
be modeledusing
of registers statement. The number when the generic shift
an always
parameter so that
SECTION
Register
serial-in,
generic
A
12-9
Figure
Register
is specified register
a
as a
is
design.
module
(D, Clock,
Shift_Reg
;
Z)
D, Clock;
input
Z;
output
parameter [1 :
reg
= 6 ;
NUM_REG
Q;
NUM__REG]
P;
integer
always @
Shift
for
begin
Clock)
(negedge
//
register =
(P
1;
P <
one bit right:
NUM__REG;
P =
P + 1)
Q[P+1] = Q[P];
II
in
Push
the
data:
serial
Q[l] = D;
end
// Get the assign
Z
output
from
the
rightmost
register:
= Q[NUM_REG];
endmodule
249
CHAPTER
12
Modeling
Examples
Shift registers of varying sizes different parameter ShiftReg using
be obtained
can
by
module
instantiating
values.
module Dummy, wire
Za, Zb,
Clk,
Data,
II 6-bit shift
register:
SRA
Shift_Reg
Zc; Za) ;
Clk,
{Data,
shift register:
II 4-bit
#4
Shift_Reg
SRB
II 10-bit shift
Zb) ;
Clk,
register:
SRC
#10
Shift_Reg
(Data,
(Data,
Zc) ;
Clk,
endmodule
12.7
State Machine Modeling State always
can
machines
The
statement.
branches of the
be modeled usually is state information
case statement
contain
the
using a case statement stored in a register. behavior
for each
an
with
The
multiple
state. Here is an
algorithm representedas a state machine. is the Ace and the counter Count are accumulator signal high, starts. If the bit of the initialized. When Reset goes low, multiplication in position to the Count is 1, the multiplicand Mendis added multiplier Mplr accumulator. the multiplicand is left-shifted by one bit, and the counter is Next, incremented. If Count is 16, multiplication is complete and the Done signal is set high.If not, the Count bit of the multiplier Mplr is checkedand the always in Figure statement 12-10 and the repeated. The state diagramis shown state machine model is shown next. corresponding example
When
of a
simple multiplication
the Reset
module MuItiply {Mplr,Mend, II Mplr is multiplier, [15:0]
input
Mplr, Mend;
input Clock, Reset; Done;
output
reg
Done;
output
[31:0] Ace;
reg [31:0] Ace; 250
Reset,
Clock, Mend
is
Done,
multiplicand.
Ace);
Machine
State
If
Reset==0
Modeling
SECTION 12.7
is 1 then Mplr[Count] Add Mend to Ace.
Ace.
Reset
Initialize
Count
Reset==l
^S
= 0,
INIT
parameter
Left
State diagram for
12-10
Figure
=
ADD
Count.
[SHlFTje^Increment
77
;T\"~
Count==16
SHIFT
1,
shift
Atod.
multiplier.
= 2;
Mpy_State;
reg [0:1]
reg [31:0]
Mcnd_Temp;
v
initial
II Initial
= INIT;
Mpy_State
state is INIT.
always
Count;
integer
case
PROCESS
begin:
Clock)
@(negedge
(Mpy_State)
INIT
:
if
(.Reset)
= INIT;
Mpy_State
/* since else The
above
is
statement will
Mpy_State
retain
not really necessary its old value */
begin Ace
Count
= 0;
= 0;
Mpy__State = Done
ADD;
= 0;
Mcnd_Temp[15:0]
= Mend;
Mcnd_Temp[31:16] = 16'dO;
end ADD
:
begin
if
{Mplr[Count])
251
Chapter 12
Modeling
Examples
= Ace +
Ace
Mcnd_Temp;
Mpy_State = SHIFT;
end
:
SHIFT
begin
Left-shift
//
==
{Count
1'bO};
{Mcnd_Temp[30:0],
= Count +
Count
if
Mcnd_Temp: =
Mcnd_Temp
1;
16)
begin
Mpy_State
Done = 1;
= INIT;
end
else
= ADD;
Mpy_State
end
// case
endcase
Mpy_State
// sequentialblock
end
PROCESS
endmodule
the model is holds the state of the model.Initially, When is in state as long as Resetis true. Reset stays Count is reset, the false, the accumulator Ace is cleared,the counter is loaded into a temporary variable multiplicandMend and the model McndJTemp, ADD. When model is in the ADD advances the to state state, multiplicand in is added to Ace if the bit of the at the Count McndJTemp only position and then the model advancesto state SHIFT. In this state, the multiplier is a 1 is left-shifted once, the counter is incremented,and if the counter value multiplier is 16, Done is set to true and the model returns to state INIT.At this time, Ace contains the result of the multiplication. If the counter value was less than 16, the model the states ADD and SHIFT until repeats itself going through counter value becomes 16.
The
register
Mpy_State
state INIT and
it
in this
State transitions occur at
using the @(negedgeClock)
252
every timing
falling control.
edge
of the
clock; this is specified
Interacting
SECTION
12.8
Machines
State
Interacting
State Machines
statements Interacting state machinescan be describedas separatealways via common registers. Consider the state diagram shown in communicating 12-11 for two interacting processes, TX, a transmitter, and MP, a Figure If TX is not MP sets the data to be microprocessor. process busy, process transmitted on a data bus and sends a signal LoadJTX to process TX to load the data and begin transmitting. is set by process TX during TXJBusy transmission to indicate that it is busy and cannot receiveany further data from process
MP. A
control
skeleton
model
signals and
for these two interacting processes is shown. state transitions are shown.Data manipulation
Only
code
the
is not
described.
(Load_TX==0) TX=l
(TX_Busy==0)
TX_Busy=l
TX=0
(Note: Expressions in
(TX_Busy==l)
Figure
12-11 State diagram
module Interacting__FSM
input Clock;
parameter
reg [0:1] reg
[0:1]
= 0,
M2 =
denote
interacting
processes.
control)
(Clock);
1, M3 Tl =0, T2 = 1, T3
Ml
parameter
of two
parentheses
= 2 ; = 2,
T4 = 3;
MP__State;
TX_State;
reg Load_TX, TX_Busy,
253
Chapter 12
Modeling
Examples
always case
begin:
Clock)
@(negedge
MP
(MP^State)
II Load data
Ml :
on data bus.
begin = 1 ;
hoadJTX
= M2;
AfP_State
end / /
:
Af2
if
for acknowledgment.
Wai t
(TX^Busy)
begin
= M3;
MP_State =
Load__TX
0;
end
II Wait (~TX_Busy)
M3 :
if
MP^State =
TX to
for
finish.
Ml;
endcase
//
end
of
End
MP
block
sequential
always @
begin:
Clock)
(negedge
case
(TX_State)
II
Tl : if
TX Wait
for
data
to
load.
(Load__TX)
begin
= T2;
TX^State
TX_Busy =1;
// Read data
from
data
bus.
end
II Sending leading
T2 : =
TX_State
flag.
T3;
T3 :
TX_State = T4; T4
II
:
Sending
begin TX_Busy
TX_State
end
254
=
0;
= Tl;
// Transmitting data. trailing
flag to
end transmission.
SECTION 12.8
Machines
State
Interacting
endcase
//
end
of
End
block
sequential
TX.
endmodule The sequence of
actions for
this
finite-state
interacting
machine
is shown
in
12-12.
Figure
Clock
: Ml
MP_State
Ml
Ml
M3
M2:
\\ -
1
Load_TX
Tl
TX_State
Tl
T4
T3
T2
TX_Busy
Figure
12-12
Sequence of actions for
Consider another divider,
process
and
RX goes
clock. Thestate
New
example of two
RX, a receiver.
Clock~l
through
its
/-^V_-V
S~^\\
sequence
is shown
diagram
L
In this case,
the
two
interacting
interacting processes,
processes. DIV, a
process DIV generatesa new of states
in Figure
synchronized
clock clock
and
to this new
12-13.
XNew_C/ocA:=0
Process DIV
(3
^
Figure 12-13 DIV generatesclock
for
RX.
255
CHAPTER12
ModelingExamples
module Another_Example__FSM2
(Clock)
;
Clock;
input
Dl = 1, D2 Rl = 1, R2 Div_State,
parameter
parameter [0:1]
reg
reg
D3 = 3 ;
= 2, = 2;
RX^State;
New__Clock;
always @
DIV
begin:
(posedge
ClocJc)
case
(Div_State)
Dl :
begin Div_State
=
D2;
= 0;
New_Clock
end
D2 :
Div_State
=
D3;
:
D3
begin
New_Clock
= 1;
Div_State
=
Dl;
end
endcase
end
// Sequential
block
DIV
always @
case
begin:
Wew_ciocJc)
(negedge
RX
(RX_State)
Rl
: RX_State =
R2
:
RX_State
R2;
= Rl;
endcase
// Sequential blockRX
end endmodule
a new clock NewjClock asit goesthrough in this occur on the rising process block RX is executed on edge of Clock.Sequential every time a falling edge occurs. The waveforms for these of state NewjClock sequence interacting block
Sequential
its
sequence
machines
256
is
of states.
shown
DIV generates
The state transitions
in Figure
12-14.
SECTION12.9
FSM
a Moore
Modeling
Clock
State
Div
D3
D2
Dl
Dl
D2
D3
D3
D2
Dl
New Clock
Rl
RX_State
Figure 12-14
The
always
output
in
of
statement
Figure
of
between
processes
RX and
DIV.
a state 12-15
finite state machine (FSM) depends only This inputs. type of behavior can be modeledusing
a Moore
and not on its
example
Interaction
a Moore FSM
Modeling state
Rl
R2
on
the
an
statement that switches on the state value. An is shown transition diagram for a Moore finite state machine and its corresponding behavior model appearsnext.
with
a case
(A==0)
(A=l)
Figure
12-15
State diagram
ofa Moore
machine.
257
CHAPTER 12
Modeling Examples
module Moore_FSM
(A,
Z) ;
Clock,
A, Clock;
input
output Z;
reg
Z;
STO =
parameter
reg
0, STl =
1, ST2 = 2,
Moore_State;
[0:1]
always
@(negedgeClock)
case
(Moore_State)
STO:
begin Z =
if
1; (A)
Moore_State
= ST2;
end
STl :
begin Z
= 0;
if
end
(A)
Moore_State
= ST3;
ST2:
begin Z
=
if
0;
(~A)
Moore_State
= STl;
else
Moore_State =
ST3;
end
ST3:
begin Z
=
if
1;
(A)
Moore_State
end
endcase endmodule
258
= STO;
ST3
=
3 ;
a Mealy
Modeling
2.10
FSM
SECTION12.10
a Mealy FSM
Modeling
state machine, the outputs not only depend on the state of the machine but also on its inputs. This type of finite can be state machine modeled in a style similar to that of the Moore FSM, that is, using a single statement. To show the variety of the language,a different is used always style to model a Mealy machine.In this case we use two always statements, one In
that
a Mealy
models
models
finite
the synchronous aspect of the finite state machine and one that combinational state Here is an example machine. part of the finite shown in Figure 12-16 and its corresponding transition table
the
of a state behaviormodel.
1
0
STO^^
STO
ST3
STl^^1
STl
^^
^^
STl
STl
ST3
STl
>^^^ 0
Input
^^
STO^^
^>^ 0 STl ^^
STl
A
(Entries
in table
next state and
are output
Z)
>^^^ 0
Present state
Figure 12-16 State transition module
Clock,
(A,
Mealy_FSM
table
for a
Mealy machine.
Z) ;
A, Clock;
input
output Z;
reg Z;
parameter reg
[1:2]
STO
=
0,
P_State,
STl
= 1,
ST2 = 2, ST3 =
3 ;
N_State;
always
@(negedge Clock) P_State
II
Synchronous
part.
= N_State;
259
CHAPTER 12
Modeling Examples
always
@(P_Stateor case
A)
COMB_PART
begin:
(P_State)
STO:
if
(A)
begin
Z =
1;
N_State
= ST3;
end
else Z
= 0;
:
STi
if
(A)
begin
Z =
0;
N_State
= STO;
end
else =
Z
1;
:
ST2
if
(~A)
Z =
0;
else
begin Z
=
1;
ALState
= STI;
end
ST3 :
begin Z
if
=
0;
(-A)
N_State
= ST2;
else
N_State
=
STI;
end
endcase
end endmodule
260
// Sequential
block
COMB_PART
Blackjack Program
A Simplified
type of finite state machine,it event list for the combinational part
In this in the
may directly
does
block
sequential
clock. Such a condition
of the
machine since outputs
state changesoccursynchronously
A Simplified
to put the input signals since the outputs
important
independent
inputs
Moore finite state
in a
occur
not
states and
2.11
depend on the
is
on
12.11
SECTION
only
depend
on
clock.
Program
Blackjack
machine description of a simplifiedblackjack is played with a deck of cards. Cards 2 to 10 program have values equal to their face value, and an ace has a value of either 1 or 11. The object of the game is to accept a number of random cardssuch that the total score of values of all cards) is as closeas possible to 21 without (sum section
This
a state
presents
program.Theblackjack
21.
exceeding
value of the a new
card is
a new
When
card.
card. If a
Lost is set to true indicating
that
the
Clock.
The
input
inserted, Card__Rdy
sequenceof cards is acceptedsuch it has
that
indicating
and
true
when the
indicates
RequestjCard
is
program is ready the
that
lost; otherwise
has the
CardJValue
Won
total is
set
to
accept
exceeds to true
21,
won. The state sequencing is controlledby and outputs of the blackjack program are shown in Figure
game
has been
12-17.
Card_Rdy
^
>
Request_Card
>
Lost
Card_Value
Blackjack Clock
> Won
Figure 12-17 The behavior of the
view
External
of blackjack
program.
following module least 17. The first ace as a 11 unless the score exceeds counted 21, in which case 10 is subtracted that the value of 1 is used for an ace. Three registers are used to store the values of the program: Total to hold the sum, Current_Card_Value to hold declaration.The
program
program
accepts
cards
is described until
its
in the
score
is at
is so
the
261
CHAPTER
12
Modeling
Examples
card read (which
value of the remember
blackjack
is stored
program
module
1 through
be
could
counted as a
ace was
an
whether
in
of
to
Ace__As__ll
a 1.
The state
BJ_State.
register
(Card__Rdy, Card__Value,
Blackjack
Reguest_Card,
Won,
Clock);
Lost,
Clock;
Card__Rdy,
input
10), and
11 instead
input [0:3] Card_Value;
output Reguest_Card,Lost, Reguest_Card,
reg
INITIAL_ST-
parameter
0
GETCARD_ST
,
= 1,
ADD_ST = 3 , CHECK_ST= BACKUP_ST = 6, LOSE_ST = 7 ;
= 2 ,
REMCARD_ST
=
WIN_ST
Won;
Won;
Lost,
5,
reg
[0:2]
BJ_State;
reg
[0:3]
Current__Card_Value;
4,
reg [0:4] Total;
reg
Ace_As__ll;
always
Clock)
@(negedge
case
(BJ_State)
INITIAL_ST :
begin
Total
=
0;
= 0;
Ace_As_ll =
Won
0;
= 0;
Lost
=
BJ_State
GETCARD_ST;
end
GETCARD_ST
:
begin
RequestJCard
if
- 1;
(Card_i?dy)
begin
= Card^alue;
Current__Card__Value
BJ_State end
end
262
=
REMCARD_ST;
//
Else
stay in
GETCARD__ST
state.
of
the
A
if
Wait
//
:
REMCARD_ST
Blackjack
Simplified
Program
for card
SECTION 12.11
to be removed.
(Card_Rdy)
= 0;
Reguest__Card
else
= ADD_ST;
BJ_State :
ADD_ST
begin
if
[~Ace_As_ll
&&
Current__Card__Value)
begin
Current_Card_Value
= 11;
Ace__As_ll = 1;
end
Total
=
= CHECK_ST;
end :
CHECK__ST
if
+ Current_Card_Value;
Total
BJ_State
< 17)
(Total
BJ_State = GETCARD_ST; else
begin
if
(Total
< 22)
BJ_State
=
WIN_ST;
else
= BACKUP_ST;
BJ_State
end :
BACKUP_ST
if
(Ace_As_22)
begin
Total = Total =
Ace_As_22
- 10;
0;
= CHECK_ST;
BJ_State
end
else
BJ_State LOSE_ST
=
LOSE_ST;
:
begin
Lost
= 1;
i?eguest_Card =
1;
263
Chapter
12
Modeling Examples
if
(Card_Rdy)
= INITIAL__ST;
BJ_State
stay in this
II Else
state.
end
:
WIN_ST
begin
Won = 1;
= 1;
Reguest_Card
if
(Card_Rdy)
= INITIAL_ST;
BJ_State
stay in this
II Else
state.
end
endcase
endmodule
12.12
Blackjack
//
Exercises
1.
model for a mango juice drink machine. The costs 15 cents. Only nickels and machine a can of mango juice that dispenses dimesare accepted.Any change must be returned. Test the model using a Write
HDL
a Verilog
test bench.
2. 3.
a model
preset
and clear.
a model for a 4-bit shift register with a clock and parallel-outdata. Test the model
Write
4. Describea D-type module,write a 5.
the behavior of a
that describes
Write
Write
a
test
using
flip-flop
model
bench
for a
behavioral
with
flip-flop
serial-in
using
data,
a test
constructs.
synchronous
parallel-in
data,
bench. Then using this
8-bit register.
that tests
the blackjack model describedin
Section
12.11.
6.
Using the shift operator,
test bench.The number
264
describe a decodermoduleand then test to the decoder is specifiedas: inputs
of
it with
a
Exercises '
NUM_INPUTS 4
define
7.
the
out
8-bit parallel to
for a
a model
Write
operator to figure
Use the shift of decoder]
[ Hint: outputs
SECTION
12.12
number
of
serialconverter.The input
is
a 8-bit
bits out, one bit at a time, starting from the most after only rising edge of a clock.Readthe next input been sent vector have out. previous input
vector. Send the
bits of
8.
all the
on the
significant bit
the
8-bit serial to parallelconverterthat does the opposite Samplethe input stream after a small delay from the the models positive edge of clock to account for transmissiondelay. Connect written in this exercise and the one in Exercise 7 using a top level module test it out using a test bench. and for a
a model
Write
of Exercise 7.
9.
the counterholds
its
when
value,
and starts counting again.Write
10. Write
for a
a model
of words in
queue
If the hold is a 1, with a hold control. is reset to 0 hold goes to 0, the counter test bench to test this model.
N-bit counter
for a
a model
Write
a
generic queue,
in M.
InputData
sizeof word is the word
in that
queue gets
is N
and number
written
into
the
to the queue when input AddWord is a 1. A word queue; the word is added the word is read from that is read from the queue is stored in OutputData; Full are set is a 1. Flags Empty and the queue when input ReadWord All transactions occur at the falling edge of clock ClockA. appropriately. a test bench to test out the model. Write
11. Write
a model
output clock synchronized the
for
is 2*N to
the
divider. The period of clock clock. The output input a test bench of the clock. Write input edge clock
a parameterizable
times rising
that
of
the
the
is
and test
model.
a
265
A
Appendix
Reference
Syntax
This
the
presents
appendix
complete
of
syntax
the
Verilog
HDL
language.
A.l
Keywords
Following
lowercasenames
are
of the
Verilog
HDL
language.
and
assign
begin
buf
bufifO
bufifl
case
casex
casez
cmos
deassign
default
defparam
disable
here
Note
that
only
keywords.
always
1. Reprinted
266
are the keywords
from IEEE
Std 1364-1995,Copyright
\302\251 1995,
IEEE,
All rights reserved.
Keywords
A. 1
SECTION
end
endcase
endmodule
endprimitive
endspecify
endtable
endtask
for
force
forever
fork
function
highzO
highzl
if
ifnone
initial
inout
input
macromodule
medium
module
nand
negedge
nmos
nor
not
notifO
notifl
or
output
parameter
pmos pullup
posedge
primitive
pullO
realtime
reg
release
rpmos
rtran
rtranifO
specparam
strongO
time triO
tran
tranifO
tril
triand
weakO
weakl
while
edge
endfunction
else
event
integer
join
large
pulll
rcmos
repeat rtranifl
real rnmos
pulldown
scalared
small
specify
strongl
supplyO
supply 1
table
task
tranifl
tri
trior
trireg
vectored wait
wand
wire
wor
xnor
267
APPENDIX
A.2
A
Reference
Syntax
Conventions
Syntax
The following described
using
i.
The syntax rules are organized left-hand nonterminal name.
ii.
Reserved
words, operators
the syntax appear in A name
Hi.
italics
in
semantic
The vertical
v.
Square
vi.
Curly
an
alphabetical
and punctuation
marks
in
order by their that
are part
to a
nonterminal name
with
associated
that
([...]) denoteoptional an item non-bold, ({...}) identify
braces,
representsthe
non-bold,
brackets,
Square characters(such
as
characters
that
The
viii.
ix. Theterminal
A.3
The
,;) appearing are part of the in
names
bold
that is
used
( [ ...
in this
always
statement
binary_base ::= \342\200\242bl'B
x
I
::= X I z I Z I 0 I 1
::=
binary_number
[ size ] binary_base binary_operator
+
268
I
-1
{
binary_digit
_ I binary_digit}
::= *
I
==
I
& | | |
I
/1 %
| \302\273= | ===
| \302\273== | &&
a | a_ |
| |
| |<
_a | \302\273| \302\253
], (
... ), {...})
grammar appear in
::=
binary_digit
braces and other indicate
\"source_text\".
Syntax always_construct
repeated
syntax.
name is
nonterminal
starting
and curly
parentheses,
items.
items.
zero or moretimes.
vii.
of
name.
nonterminal
bar symbol,non-bold,(I) separatesalternative
brackets,
is
boldface.
prefixed
meaning
iv.
the syntax, which
used in describing Form (BNF).
are
conventions
Backus-Naur
the
|<= | > | >=
upper
case.
The
SECTIONA.3
Syntax
blockJtem_declaration::= parameter_declaration I
reg_declaration
I
integer_declaration
I
real_declaration
I
time_declaration
I
realtime_declaration
I
event_declaration
::=
blocking_assignment
regjvalue = [ delay_or_event_control ::= casejtem
] expression
}:statement_or_null expression {, expression I
[: ] statement_or_null
default
::=
case_statement
case (expression) casejtem{casejtem} endcase
I
casez
I
casex
(expression
) casejtem
(expression
) casejtem
{ casejtem { casejtem
} endcase } endcase
charge_strength::=
(small)
I
(medium)
I
(large)
::=
cmos_switch_instance
[ name_of_gateJnstance
] (outputjerminal,
inputJerminal,
ncontrolJerminal,pcontrolJerminal) ::=
cmos_switchtype
cmos
I
rcmos
::=
combinationaLbody
table combinationaLentry
endtable
{combinational_entry}
::=
combinationaLentry
output_symbol
leveljnputjist:
;
comment ::= short_comment I
long_comment
commentjext
::=
{ANY_ASCII_CHARACTER}
concatenation ::=
{expression{, expression conditional_statement if
(expression
}}
::= ) statement_or_null
[ else
statement_or_null
]
269
APPENDIX
A
Syntax Reference
constant_expression::= constant_primary I
unary_operator
I
constant_expression
I
constant_expression
I
string
constant_primary
constant_expression binary_operator : constant_expression ? constant_expression ::=
constant_mintypmax_expression
constant_expression I
: constant_expression
constant_expression
: constant_expression
::=
constant_primary number I
paramete/Jdentifier
I
consfanLconcatenation
I
consfanf_multiple_concatenation
::=
continuous_assign
assign
[ drive_strength
] [
delay3 ]
list_of_net_assignments;
::=
controlled_timing_check_event
specify_terminal_descriptor
timing_check_event_control
]
[ &&&timing_check_condition
::=
current_state
leveLsymbol data_source_expression::= expression
::=
decimal_base \342\200\242dl'D
::=
decimal_digit
011I2I3I4I5I6I7I8I9
decimaLnumber
::=
[ sign] unsigned_number I
[
size
] decimal_base
unsigned_number
delay2 ::=
# delay_value
I
# (delay_value
[, delay_value
])
[, delay_value
[, delay_value ] ])
delay3::=
# delay_value
I
# (delay_value
delay_control
I
::=
# delay_value # ( mintypmax_expression
delay_or_event_control ::= delay_control
270
)
The
I
event_control
I
repeat
Syntax
SECTIONA.3
) event_control
(expression
delay_value ::= unsigned_number I
parameter_identifier
I
constant_mintypmax_expression
::=
description
module_declaration I
udp_declaration
::=
disable_statement
disable fas/cjdentifier ; disable
I
;
Woc/cjdentifier
drive_strength ::=
(strengthO,strengthl I
(strengthl,
I
(strengthO,
I
(strengthl
I
(highzl
I
(highzO,
)
strengthO) highzl
)
,highzO) , strengthO
)
strengthl
)
::=
edge_control_specifier
edge [ edge_descriptor[, edge_descriptor
]
]
::=
edge_descriptor
01 I
10
I
Ox
I
x1
I
1x
I
xO
::=
edge_identifier
posedge
I
negedge
::=
edge_indicator
(level_symbol level_symbol) I
edge_symbol
::=
edge_inputjist
{level_symbol} edge_indicator {level_symbol} ::=
edge_sensitive_path_declaration
parallel_edge_sensitive_path_description I
= path_delay_value = path_delay_value
full_edge_sensitive_path_description
edge_symbol ::=
rl
R
If
I
Flpl
PI
n INI*
enable_gate_instance ::= [
name_of_gate_instance
] (outpuMerminal,
inpuMerminal,
enable_terminal)
271
APPENDIX
A
Reference
Syntax
::=
enable_gate_type I
bufifO
bufifl
I
notifO
I
notifl
::=
enable_terminal
sca/ar_expression
escaped_identifier ::= \\ {
::=
event_control @ I
} white_space
ANY_ASCII_CHARACTER_EXCEPT_WHITE_SPACE
evenMdentifier
@ (event_expression
event
)
::=
event_declaration
evenMdentifier
{,
\342\200\242
evenMdentifier}
::=
event_expression
expression I
evenMdentifier
I
posedge
expression
I
negedge
expression
I
event_expression
or event_expression
event_trigger ::=
-> evenMdentifier
;
::=
expression
primary I
unary_operator
I
expression
I
expression
I
string
primary binary_operator ? expression
expression
: expression ::=
full_edge_sensitive_path_description
([ edge_identifier ] list_of_path_inputs [
*> list_of_path_outputs
)
]: data_source_expression
polarity_operator ::=
full_path_description
(list_of_path_inputs
[
] *>
polarity_operator
list_of_path_outputs)
function_call ::= (expression
fcyncf/'onjdentifier I
[
] funcf/onjdentifier
range_or_type
function_item_declaration
statement
endfunction function_item_declaration
block_item_declaration I
272
{, expression
::=
function_declaration
function
})
{, expression [ (expression
name_of_system_function
input_declaration
::=
;
{function_item_declaration}
}) ]
The Syntax
Section A.3
gatejnstantiation ::= [
n_input_gatetype
{, I
};
]
[ drive_strength
enable_gatetype
] n_output_gate_instance
delay2
] enable_gate_instance
delay3
[
};
{, enable_gate_instance
] mos_switch_instance
[ delay3
mos_switchtype
[
};
{, n_output_gate_instance
I
]
[ drive_strength
n_output_gatetype
I
] n_input_gate_instance
] [ delay2
drive_strength
n_input_gate_instance
{, mos_switch_instance }; I
pass_switchtype
I
pass_en_switchtype
I
cmos_switchtype
I
pullup
I
pulldown
{, pass_switch_instance ] pass_en_switch_instance
pass_switch_instance [ delay3
{, pass_en_switch_instance
};
};
] cmos_switch_instance
[ delay3
{, cmos_switch_instance } ; [ pullup_strength
{/ pull_gate_instance
{, pulLgate_instance } ;
] pull_gate_instance
] pull_gate_instance
[ pulldown_strength
};
hex_base ::= \342\200\242hl'H
::=
hex_digit
xlXIzIZ I
011I2I3I4I5I6I71819
I
alblcld
lelfIAIB
hex_number [
El
ICI DI
F
::=
size
hex_digit { _
] hex_base
I
hex_digit}
:=
identifier
IDENTIFIER [{.IDENTIFIER}] /* The period may not be followed
by a
or preceded
space */
::=
IDENTIFIER
simple_identifier I
escaped_identifier
::=
init_val
1'b0 11'b1
11'bx 11'bX11'BO
I
1'B1
11'Bx
11'BX 11
::=
initial_construct initial
statement
::=
inout_declaration
inout [ range ] Iist_of_port_identiffers; ::=
inout_terminal
term/na/jdentifier I
[ constant_expression
term/na/Jdentifier ::=
input_declaration
input
[
range
] list_of_port_identifiers;
]
I
0
APPENDIX A
Syntax Reference
input
::=
^identifier
/npuf_po/t_identifier I
/nouLportJdentifier
::=
inputjerminal
sca/ar_expression
integer_declaration ::=
integerlist_of_register_identifiers
;
::=
leveUnPutJist
level_symbol {level_symbol} ::=
level_symbol
IxI
011
X
I
?IbIB
::=
limit_value
constant_mintypmax_expression
::= list_of_module_connections {, ordered_port_connection
ordered_port_connection I
{, named_port_connection
named_port_connection
}
}
::=
list_of_net_assignments
net_assignment {, net_assignment} ::=
list_of_net_decl_assignments
{, net_decl_assignment}
net_decl_assignment ::=
list_of_net_identifiers
nefjdentifier
{, neHdentifier}
list_of_param_assignments ::= {, param_assignment}
param_assignment
list_of_path_delay_expressions
::=
f_path_delay_expression I I
fnse_path_delay_expression, fnse_path_delay_expression
tfa//_path_delay_expression , tfa//_path_delay_expression,
tz_path_delay_expression I
f07_path_delay_expression,
fOz_path_delay_expression, f I
7z_path_delay_expression,
f07_path_delay_expression,
fOz_path_delay_expression, f
7z_path_delay_expression,
fOx_path_delay_expression, f
7x_path_delay_expression,
fxz_path_delay_expression, list_of_path_inputs
tzO_path_delay_expression f 70_path_delay_expression,
tz7_path_delay_expression, tzO_path_delay_expression,
fx7_path_delay_expression, fxO_path_delay_expression,
tzx_path_delay_expression {, specify_input_terminal_descriptor}
::=
specify_output_terminal_descriptor
274
tz 7_path_delay_expression,
::=
specify_input_terminal_descriptor list_of_path_outputs
f 70_path_delay_expression,
{, specify_output_terminal_descriptor}
The Syntax
SECTION
::=
list_of_port_identifiers
{, porHdentifier}
porHdentifer ::=
list_of_ports
(port
{, port}) ::=
list_of_real_identifiers
{, rea/Jdentifier}
rea/_identifier
::=
list_of_register_identifiers
{, register_name
register_name
}
list_of_specparam_assignments: := {, specparam_assignment}
specparam_assignment
::=
long_comment
I* comment
*/
Jext
::=
loop_statement
forever statement I
repeat
I
while
I
for
) statement
(expression ( expression
) statement reg_assignment)
expression;
(reg_assignment;
statement
::-
mintypmax_expression
expression I
expression
: expression
: expression
module_declaration
::=
module_keyword
modu/ejdentifier
[ list_of_ports
];
{modulejtem}
endmodule
modulejnstance ::= ([
name_of_jnstance
module_instantiation
list_of_module_connections
::=
modu/ejdentifier[
parameter_value_assignment
};
{, modulejnstance
moduleJtem ::= moduleJtem_declaration I
parameter_override
I
continuous_assign
I
gatejnstantiation
I
udpjnstantiation
I
modulejnstantiation
I
specifyjDlock
I
initial_construct
I
always_construct
moduleJtem_declaration
::=
parameter_declaration I
input_declaration
I
output_declaration
]) ] modulejnstance
A.3
Appendix
A
Syntax Reference
I
inout_declaration
I
net_declaration
I
reg_declaration
I
integer_declaration
I
real_declaration
I
time_declaration
I
realtime_declaration
I
event_declaration
I
task_declaration
I
function_declaration
::=
module_keyword
module
I
macromodule
::=
mos_switch_instance
] (outpuMerminal,
[ name_of_gate_instance
inpuMerminal,
enablejerminal)
::=
mos_switchtype
nmos
I
I
pmos
rnmos
I
rpmos
::=
multiple_concatenation
{, expression}}}
{expression {expression ::=
n_input_gate_instance
] (outpuMerminal,
[ name_of_gate_instance
inpuMerminal
{, inpuMerminal}) ::=
n_input_gatetype
and
I
nand
I
or
I
nor
I
xor
I
xnor
::=
n_output_gate_instance
] (outpuMerminal
[ name_of_gate_instance inpuMerminal)
n_output_gatetype buf I not
::=
::=
name_of_gateJnstance
[
\302\243fate_/'nstencejdentifier
name_ofJnstance
]
range
:.=
[ range ]
modu/e_/nsfanceJdentifier
name_of_systemJunction::= identifier
::=
name_of_udpJnstance
udp_/'nstencejdentifier
[ range ]
named_port_connection ::=
. porHdentifier
ncontroljerminal
([
expression
::=
sca/ar_expression
276
])
{, outputjerminal},
The
Section
A.3
] list_of_net_identifiers
;
Syntax
::=
net_assignment =
net_lvalue
expression
::= neMdentifier = expression
net_decl_assignment
::=
net_declaration
neMype
vectored
[
[ vectored
I
trireg
I
net_type
I I
scalared
]
[
delay3
]
] [ charge_strength
] [ delay3
range
[
]
;
list_of_net_identifiers [ vectored
] [ range
scalared
I
scalared
] [ drive_strength
]
[
] [ delay3
range
]
;
list_of_net_decl_assignments
netjvalue ::= neMdentifier
[ expression ] [ ms\302\243>_constant_expression
I
neMdentifier
I
neMdentifier
I
nef_concatenation
: fe\302\243>_constant_expression
]
::=
net_type
wire
I
tri
I
trh
I
I
supplyO
wand
I
triand
I
triO
I
supplyl
I
wor
I
trior
::=
next_state
output_symbol
I
-
.:=
non_blocking_assignment
reg_lvalue <= [ delay_or_event_control
]
expression
::=
notify_register
refif/ster_identifier
number ::= decimal_number I
octal_number
I
binary_number
I
hex_number
I
real_number
::=
octal_base
'ol'O ::=
octal_digit
xlXIzlZIOI1I2I3I4I51617
::= [ size ] octal_baseoctal_digit
octal_number
{_
I
octaLdigit}
::=
ordered_port_connection
[ expression ] ::=
output_declaration
output
[
output_identifier
range
] list_of_port_identifiers;
::=
oufpuf_porLidentifier I
/nouf_porMdentifier
277
APPENDIX A
Syntax Reference ::=
output_symbol
011
I
x I X
::=
outpuMerminal
term/'na/Jdentifier I
]
[ constant_expression
term/'na/Jdentifier
par_block ::= fork
[: Woc/f_identifier
]
{block_item_declaration}
{statement} join
parallel_edge_sensitive_path_description ::=
([ edge_identifier
=>
specify_input_terminal_descriptor
]
[ polarity_operator
specify_output_terminal_descriptor
]:
data_source_expression) ::=
parallel_path_description
(specify_input_terminal_descriptor
[
polarity_operator
] =>
specify_output_terminal_descriptor)
::=
param_assignment
paramete/Jdentifier= constant_expression ::=
parameter_declaration
;
list_of_param_assignments
parameter
parameter_override::= ;
list_of_param_assignments
defparam
::=
parameter_value_assignment
# (expression {, expression ::=
pass_en_switchtype
tranifO
I
})
tranifl
I
rtranifl
I
rtranifO
::=
pass_en_switch_instance
[ name_of_gate_instance
] (inouMerminal, inouMerminal,
enablejerminal) ::=
pass_switch_instance
] (inouMerminal,
[ name_of_gate_instance
pass_switchtype ::= tran
I
rtran
path_declaration
::=
simple_path_declaration; I
edge_sensitive_path_declaration
I
state_dependent_path_declaration;
path_delay_expression
::=
constant_mintypmax_expression
278
;
inouMerminal)
The Syntax
A.3
SECTION
::=
path_delay_value
list_of_path_delay_expressions I
(list_of_path_delay_expressions)
::=
pcontrol_terminal
sca/ar_expression ::=
polarity_operator
+ 1-
port ::=
[ port_expression] I
. portjdentifier
([ port_expression
])
{, port_reference
}}
port_expression::= port_reference I
{port_reference
port_reference ::= portjdentifier I
portLidentifier
[ constant_expression
I
portjdentifier
[ msb_constant_expression
]
: feb_constant_expression
::=
primary
number I
identifier
I
identifier
I
identifier
I
concatenation
[ expression ] [ msb_constant_expression
I
multiple_concatenation
I
function_call
I
(mintypmax_expression)
.:=
procedural_continuous_assignment
reg_assignment ;
assign I
deassign
I
force
reg_assignment
I
force
net_assignment
I
release
I
release
regjvalue;
regjvalue; netjvalue
; ; ;
procedural_timing_control_statement
::=
delay_or_event_control statement_or_null ::=
pull_gate_instance [
] (outputjerminal)
name_of_gate_instance
::=
pulldown_strength
(strengthO, I
(strengthl
I
(strengthO)
pullup_strength
strengthl
, strengthO
)
)
::=
(strengthO,
strengthl
)
: teb_constant_expression
]
]
APPENDIX
A
Syntax Reference
I
(strength
1 ,strengthO
I
(strength
1 )
)
::=
pulse_control_specparam
PATHPULSE$= (re/'ecf_limit_value
I
I*no space; =
$specify_output_terminal_descriptor
[, errorJimit_value
]) ;
[, erro/-_limit_value
PATHPULSE$specify_input_terminal_descriptor
continue*!
(re/'ecfjimit_value
]) ;1
range ::=
[ ms\302\243>_constant_expression I
I
integer
realtime
I
time
;
::=
unsigned_number.
[ sign ] [
I
list_of_real_identifiers
real_number I
real
::=
real_declaration
real
]
::=
range_or_type
range
: fe\302\243>_constant_expression
] unsigned_number
sign
unsigned_number
[. unsigned_number
] e [ sign ]
[. unsigned_number
] E [ sign ]
unsigned_number I
[
] unsigned_number
sign
unsigned_number
realtime_declaration ::= realtime
;
list_of_real_identifiers
::=
reg_assignment
reg_lvalue = expression ::=
reg_declaration
reg
[
range
;
] list_of_register_identifiers
::=
regjvalue
reg_identifier I
reg_identifier
[ expression
I
regudentifier
[
I
recjLConcatenation
register_name
] : fe\302\243)_constant_expression
ms\302\243>_constant_expression
::=
re\302\243f/ster_identifier I
[ uppe/\"_//m/f_constant_expression
memoryjdentifier
]
/oiver_//m/f_constant_expression
scalar_constant ::=
1'bO11'b111'BO 11'B1 I 'bO
scalar_timing_check_condition
I
'b1
I
'BO
I
'B1
::=
expression I
~
I
expression
expression == scalar_constant
= (5,3); 1. For example,PATHPULSE$CLK$Q
280
11
I
0
:
]
The
I
expression
I
expression
I
expression
==
Syntax
A. 3
SECTION
scalar_constant
!= scalar_constant !== scalar_constant
seq_block ::=
begin
[: Woc/cj'dentifier {block_item_declaration}
]
{statement}
end
seq_input_list ::= I
level_input_list
edge_input_list
::=
sequential_body
[ udp_initial_statement
]
table
sequentiaLentry
{sequentiaLentry} endtable
::=
sequentiaLentry
::=
short_comment
// comment_text sign
: next_state;
current_state
seqjnputjist:
\\n
::=
+ 1-
simplej'dentifier ::= [a-zA-Z|[a-zA-Z_$0-9] \342\200\242.:=
simple_path_declaration
= path_delay_value
parallel_path_description I
= path_delay_value
full_path_description
size ::= unsigned_number
source_text
::=
{description}
specify_block ::=
specify
{specifyj'tem} endspecify
:=
specify_input_terminal_descriptor:
inputjdentifier I
inputjdentifier
I
inputjdentifier
specifyj'tem
[ constant_expression [ ms\302\243>_constantjaxpression
] : fe\302\243>_constant_expression
]
::=
specparamjdeclaration
281
APPENDIX
A
Reference
Syntax
I
path_declaration
I
system_timing_check
:=
specify_output_terminal_descriptor:
outputjdentifier I
outputjdentifier
I
outputjdentifier
]
[ constant_expression [ ms\302\243>_constant_expression
: /ab_constant_expression
::=
specifyJerminal_descriptor
specifyJnputJerminal_descriptor I
specify_outputJerminal_descriptor
::=
specparam_assignment
= constant_expression
specparamjdentifier I
pulse_control_specparam
specparam_declaration
\342\200\242.:=
specparam
list_of_specparam_assignments
::=
state_dependent_path_declaration if
) simple_path_declaration
( co/iaW/o/ia/_expression
I
if (
I
ifnone
;
) edge_sensitive_path_declaration
co/ic//f/o/ia/_expression simple_path_declaration
::=
statement
blocking_assignment ; I
nonjDlocking_assignment;
I
procedural_continuous_assignment
I
proceduralJiming_control_statement
I
conditional_statement
I
case_statement
I
loop_statement
I
wait_statement
I
disable_statement
I
eventjrigger
I
seq_block
I
par_block
I
task_enable
I
systemJask_enable
statement_or_null
;
\342\200\242.:=
statement
I
;
::=
strengthO
supplyO
I
strongO
I
pullO
I
weakO
I
strongl
I
pulM
I
weakl
1 ::=
strength
supplyl ::=
string \"
{
ANY_ASCII_CHARACTERSJEXCEPTJSIEWLINE
systemJask_enable
::=
system Jask_name
282
[ (expression
{, expression})];
\"
}
]
The
SECTION
Syntax
A. 3
system_task_name ::= identifier
be
$ cannot
/* The
followed
by
a space
7
system_timing_check ::=
$setup(timing_check_event, [, notify_register I
$hold
I
I
$width
I
[,
]) ;
notify_register
timing_check_event,
(timing_check_event,
timing_check_event,
(controlled_timing_check_event,
$recovery
notifyjegister]) ;
(timing_check_event,
$setuphold
timing_check_limit
]) ;
notify_register
timing_check_limit [, I
timing_check_limit,
(controlled_timing_check_event,
$skew
[,
timing_check_limit
notify_register
constant_expression I
timing_check_limit
]);
(controlled_timing_check_event, ]) ;
$period
[,
timing_check_event,
(timing_check_event,
[ / notify_register
timing_check_limit
timing_check_event,
]) ;
timing_check_limit,
timing_check_event,
timing_check_limit
[,
notify_register
]) ;
task_declaration ::=
task tes/c_identffier
;
{task_item_declaration}
statement_or_null
endtask
task_enable ::= fas/c_identifier
[
{, expression
(expression
}) ] ;
::=
task_item_declaration
block_item_declaration I
input_declaration
I
output_declaration
I
inout_declaration
time_declaration
time
::=
list_of_register_identifiers;
::=
timing_check_condition
scalar_timing_check_condition I
(scalar_timing_check_condition)
::=
timing_check_event
] specify_terminal_descriptor [ &&&timing_check_condition ]
[ timing_check_event_control ::=
timing_check_event_control
posedge I
negedge
I
edge_control_specifier
timing_check_limit
::=
expression
283
APPENDIX
A
Reference
Syntax
udp_body ::= combinational_body I
sequential_body
::=
udp_declaration
primitive
(udp_port_list);
udp_identifier
udp_port_declaration
{udp_port_declaration}
udp_body
endprimitive ::=
udp_initial_statement
initial
udp_output_portJdenX\\f\\er
=
init_val
;
::=
udp_instance
[ name_of_udp_instance
] (output_port_connection
, input_port_connection
})
{, input_port_connection
::=
udp_instantiation
[
udp_identifier
drive_strength
] [ delay2
] udp_instance
{, udp_instance
::=
udp_port_declaration
output_declaration I
input_declaration
I
reg_declaration
::=
udp_port_list
input_portJdenX\\i\\er
output_port_\\denXW\\er,
unary_operator ::=
+ I -1!
~ I &
I
I
~&
I
I I
~ I I A I ~A
\342\200\242.:=
unsigned_number
{_
decimal_digit
I
decimal_digit}
::=
wait_statement
wait (expression ) statement_or_null ::=
white_space
space
284
I
tab
I
newline
I
A~
{, input_portJdenX\\i\\er}
};
Bibliography
1.
Arnold
M.,
Digital
Verilog
PrenticeHall,NJ, 1998.
2.
Bhasker Publishing,
J.,
ISBN
1998,
PA,
3.
Lee J., Verilog
4.
Palnitkar
Prentice
HDL
Verilog
S.,
Hall,
Synthesis: A 0-9650391-5-3. Kluwer
Quickstart,
HDL:
5. SagdeoV.,CompleteVerilog 6. Smith D., HDL Chip Design, 7. SternheimE., R. Singh and Verilog
8.
Thomas
9.
IEEE
HDL,
Practical
Star Galaxy
Primer,
MA, 1997.
Academic,
Digital Design and Synthesis, 1996, ISBN 0-13-451675-3.
Verilog
NJ,
Design: Algorithms to Hardware,
Computer
Automata
A Guide to Kluwer
Book,
Doone Y
Publications,
MA, 1998.
1996.
Design and Synthesiswith 1993. CA, Company,
Trivedi,
Publishing
Academic,
Digital
D. and P. Moorby, The Verilog Hardware Description Kluwer Academic, MA, 1991, ISBN0-7923-9126-8.
Hardware
Standard
Hardware
Description
Description
Language,
Language
IEEE Std
Based on
Language,
the
Verilog
1364-1995,IEEE,1995.
285
Bibliography
10.
Open
Verilog
International,
OVI Standard
Delay File(SDF)
Format
Manual.
\342\226\241
286
Index
- character -
173,222
$fmonitor
94
57
operator
173
$fmonitorb
62
$fmonitorh
173
: 61
$fmonitoro
173
:= 61
$fopen 172
$fstrobe 173,222
181
$bitstoreal
18,113,169,205
$display
$displayb
169
$displayh 169 $displayo 169 182
$dist_exponential
$dist_normal 182 $dist_poisson 182 $dist_t
173
$fstrobeo
173 173
173
$fwriteb
173 $fwriteo 173 $fwriteh
182
$hold
$itor
177
181
$monitor
182
182
$dist_uniform
$dumpall
$fstrobeh $fwrite
182
$dist_chi_square
$dist_erlang
173
$fstrobeb
194
$dumpfile 193
$monitorb
21,171,205 171
$monitorh
171
$monitoro
171
$dumpflush
195
$monitoroff
172
$dumplimit
195
$monitoron
172
$dumpoff 194 194
$dumpon
193
$dumpvars
$fclose 173
$fdisplayh
$fdisplayo $finish
179
$period 178 $printtimescale 175 \342\200\242 $random
$fdisplay 173,222 $fdisplayb
$nochange
$readmemb
181
43,174, 205,219
173
$readmemh 43,174,205
173
$realtime
173
$realtobits
176,205
180
181
$recovery 178
287
= assignment symbol
181
$rtoi
==
177
$setup
177
$setuphold
$skew 178 $stime 180 $stop 123,176,205
=== 61
=> 198 > 60 60
>=
\302\273 66
170,205
$strobe
$strobeb
170
? character
$strobeh
170
A
$strobeo 170
A~ 63
175,180
$timeformat
$width
34,92,136
63,65
vcelldefine 31
26,180,206
$time
126
61
177
Mefault_nettype 28,40,
$write 169,205
selse 28
$writeb
169
vendcelldefine31
$writeh
169
sendif
$writeo 169
28
28
vifdef
% character 169
include
28,191
%B 169
Vesetall
29
%b 169
stimescale
%
57
operator
169
%D
II 62
-
169
~| 65
%0 169 169
169
absolute delay 209
%s 169
always statement
169
%t
%V
169
and gate
%v 169,202 62
(??)
94
assignprocedural 57
asynchronousloop preset
asynchronous
asynchronous state
188
57
base
< 60,66 <=
statement
199
character
format
32
based integer
60
<= assignment
83
169
symbol 128
BCD
205
behavior
107
140
clear 95
asynchronous
+ operator 57 .
57
of instances
array
94
/ operator
244, 245
4
operator
ASCII character
*> 198 +:
235,
arithmetic shift 206
(01) 94 operator
3,15, 71
arithmetic
(?0) 94 (Ox)
11,17,107,110,123,
209, 131,139,184,
architectural-level
& 4, 63,65 &&
xv, 1,3,4
algorithmic-level
%T 169
*
65
~A 63,65
%m 169
%S
63
~&
169
%o
81
| 4,63,65
%H 169 %M
8,10, 21,29,
27
sundef
169
%d 169 %h
vnounconnected_drive31 vunconnected_drive31
%C 169 %c
83
27
sdefine
51
235,248
112 machine
186
Index
behavioral modeling 107 behavioral
compiler directive xviii, 8,10, complete path name 189
238
3,8,11,
style
switch 80
bidirectional
concatenated
and
coded decimal
binary
exclusive-nor
binary
exclusive-or
binary
minus
binary
number
binary
or
binary
plus 57
205
concatenation
63
constant
expression
constant
literal 206
continuous
bitwise-or 4
blackjackprogram
261
19,119
blockstatement
21,126,209 Boolean
break
data type
74 75
bufifl
75
dataflow
decadecounter decimal
caseexpression
66
61
default
case item expression 134
casestatement
133,244,
case-sensitive
delay
136
delayed
31
disable 203
edge
111, 114,125
18,108,
243
waveform
119,137,183, 206
statement
distributed
202
divide
clock 137
clockdivider
control
display task 168,202
charge decaytime strength
48,152
delay specification81,102
character 35 charge
202
specification
strength
delay 8,9,29,81,101,115,240
250,257
casex statement 136 cell module
237, 264
defparam statement
24,26
casezstatement
34
decoder 9, 85, 216, default delay 81
134
inequality
158
33,169
decimal notation
61
equality
case equality operator
clock
9,238
3, 8,
style
deassign procedural statement 140
C
case
178 36,185
dataflow behavior 6, 8,10,98 dataflow modeling 107
capacitive node 39 case
19
xviii
brace
data event
206
gate
curly
D
234
equation
bufifO
206,265
cross-coupled nand-gate 12,
assignment
xviii
BNF
buf
counter
119
procedural
blocking
181
function
conversion
block label
6,8,9,10,17,
assignment
98,107,130,139,202, 210, 234, 237, 240, 243, 244
183
block
68
68
constant-valuedexpression46 continue
4
bitwise-and
131, 221
constant 32,51
33
244
67,
statement
conditional
63
28
compilation
conditionaloperator
63
57
operator
237
operator
conditional
63
bit-select 41,53,99,150,156,235 bit-wise
79
18
concatenation 67,99,150,156
63
binary
binary
MOS
target
complimentary
binary 169
27,191
198
delay
57
don't-care 34,92,136 223
downward
97
closing file 172
190
referencing
drive strength
201
drive strength specification D-type flip-flop 95, 264
cmos 77
98,245
combinational
logic
combinational
logic primitive
combinational
UDP
91
3
201
E
edge-sensitive path
199
289
94
UDP 94
sequential
edge-triggered
edge-triggeredtiming operator
equality
116
event control
edge-triggered
edge-triggered flip-flop 61
escape sequence169
escapedidentifier event
99,185,240
12,108,111,116,125 185
event
declaration
event
trigger statement
explicit zero delay 116
185
name 169,192
hierarchical path
file I/O task
implicit net inertial
statement
18,109,139
26
full
11,15,100,219
function
call 54,167
function
definition
166,189
15,17,21,
gate primitive
14, 202
1, 3,14
gate-levelmodeling gate-level
107,147
primitive
generic queue code
input
parameter
input
port 148,150
166 205
6,243
45
57
division
integer register
45,53,59
interconnection
15
port
156
inter-statement delay
13,21,125
intra-statement
13,125,205,209,
delay
243 71, 80,
83, J
JK flip-flop 97
K keywords 25
265
variable
Gray code
declaration
21,80,198
107,147,150,154 gate-level
argument
input
internal
G
gate instantiation
162
input
integer
165,205
function
gate delay
argument
port 148
integerdeclaration
198
connection
162
inout
inout
integer 32,45,109
257
full-adder
11,13,17,18,21,93,
97,107,108,139,208,235
format specification 169,172,175 FSM
102
initial statement
121
free-format
184
delay
141
loop 212
for-loop
declaration 28,40
indeterminate
forever-loop statement 137 fork
83
net
implicit
2
66,131, 239, 244
172
force procedural statement forever
2
1364-1995xv,
impedance 78
112, 245, 248,264 point value 53
floating
24,150,188
standard
252,256
172
pointer
flip-flop
265
if statement
32
false
152,188
232
IEEE Std
81,102
edge
falling
name
14,148
control
IEEE
fall time 240
Gray
design
hierarchical
I
225
design
3
hierarchical
identifier
fall delay
global
signal 185
hold time
F
file
7, 241
handshake
hold
external port 155 factorial
60
high-impedance 32
50, 99,123,150
expression
60
or equal to
half-adder
hierarchy
66
operator
exponentiation
than
hexadecimal 33,169
25
event control
than
greater
H
112
control
greater
164
L
232 counter
232
Language
Reference
Manual
xvii
latch
N
93,246
237
left-rotate less
equal to
60
level-sensitiveevent level-sensitive local
nand
247
D flip-flop
level-sensitive
control
112,118
UDP 93
sequential
4
logic function
net
logicalequality
61
operator
logical
shift
net
62
LRM
netlist
66
239
169
newline
136
77
nmos
nmos gate 3
xvii
106
comparator
magnitude
majority circuit master-slave
217
flip-flop 86,105
flip-flop
state machine
finite
non-blocking procedural
259
42,54,247
memory
54
element
memory
min.typ-.max 82,241
mixed-design style mixed-level
declaration
module
instance
4
14 16,18,48,147,
171
77
33,169
172
file
opening
50 xviii,
55
50,
3,15,71 162
output
argument
output
port 148
OVI 2
machine
state
257
P
77
gate
71
gate 74
multiplexer 84,
92,244
algorithm
multiplier 154 57
179,205
or gate
delay 198
multiple-output
multiply
75
operator
200
multiple-input
multiplication
notifl
operand
152
parameter
MOS switch
75
Open Verilog International 2
189
finite
74
notifO
octal
29,192
module instantiation
Moore
not gate
O
module
path
71
nor gate
n-type MOStransistor
16
module 6,147
modulus 57 monitor task
78
switch
non-resistive
notifier
modeling
module path
assignment 128,209
96
D-type
master-slave
module
203, 205,
assignment
243
M
module
169
strength
signal
non-blocking
Mealy
101,104
assignment
net type 28,36
logical or 62
loop statement
36,52,101,104,148
declaration
net part-select54
66
operator
logicalinequality logical
3,8,36,185
net delay 104,198
61
equality
logical
53
bit-select
net declaration
and 62
logical
negedge 118 210 net 9,15,52,58,98,148,202, net data type
32
79
118
edge
negative
net
logic-0 32 logic-1
3, 71
gate
n-channel control
121,163,167,239
register
16,21
named block 189 named event 185
60
than
less than or
association
named
left-shift 66,237
250
parallel
block
parallel
connection
parallel to parameter
119,121
serial
265
47,52,249
parameter declaration parameter
198
converter 28,47,
name 68
parameter specification
200
52,68
154
value
parameter
R
265 parameterizable clockdivider parameterized Gray code counter 232
87
generator
parity
path delay
real
path
specification
200
real
188
realtime
phase-delayed214
reduction operator
3
gate
reduction xnor 65
port 6,148 list
reductionxor reg declaration
association
16,18,149
edge 118
register 52,119,166,239,245
register
primitive logic gate encoder
3 13,93,98,109,
continuous
assignment
procedural statement
139
propagationdelay
interface
80
pulldown pulse
repeat loop
214
repeat-loop
statement
77
reservedidentifier
77
resistance
word
Q
25
xviii 77,
78, 80
response monitoring 206
237
right-rotate
66
right-shift xviii
81,102
rise delay
rise time rising
3
137
78
resistive switch 200
statement 141
control 125,138
event
repeat
reserved
pulse rejection limit pulse width 200 punctuation mark
queuing-level
xv, 1,
60
57
77 77
limit
209
delay
replication 68
182
p-type MOS transistor
pullup
200
limit
remainder
language
gate
reject
release procedural
3
pull
3
register-transfer-level
relative
161
pseudo-random
52,148
54
part-select
register
relational operator
108,110,114,
process-level 3 programming
registerdeclaration
register type 36,41
117,163,183
procedure
type 3,11,17,123,185,
211,245
88,97
111,123,130,204,248 6,11 procedural construct procedural
data
register
assignment
procedural
53
bit-select
70,88
gate
priority
41
41, 53, 58,59,148
reg register
precedence 55 primitive
178
reg 12
posedge 118 positive
65
event
reference
148,155
positional
65
65
or
reduction
port association 149 148 port declaration port
65
65
nor
reduction
pmos 77 pmos
and 65
reduction nand
xv, 3
PLI
46,53
register
reduction
3
delay
pin-to-pin
47
46,53
register
realtime declaration 47
79
control
period character
51
real declaration
PATHPULSE$200 p-channel
32,34
real constant
206
name
37,83
specification
rcmos 77
3,200
path
181
number
random
range
41, 53,99,150,156,235
part-select
race condition 203
rnmos
240
edge
rpmos
RTL 3
77
77
245,256
4
80
rtran
6
structure
rtranifO
80
rtranifl
80
supplyO 40
supply 1 switch
40
71,77,80
xv, 1, 3
switch-level
69
scalar expression
scalarnet 52,99
scalarregister
52
scalared
41
keyword
35
seed 181 detector
229
sequential behavior
12,14,19,109,
111,
256
3
logic primitive
sequential UDP 93 setup time
operation
shift
operator
237
control
simulation
time 180,248
simulation
time
198 198
xviii
Delay Format 241 186,250
252
transition
path
state-dependent
timescale task 175 timing
control
timing
violation
108,110,114
toggle flip-flop
flip-flop
toggle-type
80
tran
177 232
80
tranifl
80
199
transistor-level
14
transport delay
243
78,80
value
3,199
tranifO
119 stimulus 4,17,207 201
32, 35,169 task
8,10,29,175,240
259
static
strobe
46,53
register
check task 177
bracket
string constant
time
check
state transition table
string
169
timing
parameter
76,
46
declaration
82,198,232,241
specparam declaration
strength
27
driver 75
timing
specify
strength
4
substitution
time unit 180
function
block
state
207
constraint
constant 51
specify
state machine
test bench
time precision 8,10,29,175 176
task
simulation
Standard
163
terminal 71
time
simulation 207
square
statement
time format
198
sized integer
161,189
enable
time 46
32
path
simple
161
task definition
three-state
value 59
simple decimal
99
161,183,205
task call
text
51,53
33,
18,26,168
text macro 27
249,264
signed number
task
test
66,237,264
shift register signed
265
232
shift
26,168
xviii,
call 54
169
target
task
converter
to parallel
serial
function
table entry 94
239, 119,121,124,128,184,
sequential
function
system
3, 6,14
245
logic
system
tab
6,98
block
sequential
primitive
T
237
address
sequence
switch-level
system task xviii,
SDF 241 selection
modeling
synchronous
scientific notation
3
switch-level
51
170
structural style
3,8,14,158,238
structural-level
4
37
tri net
triO 40
tril
40
39
triand
trior
38
trireg 39
triregnet tristategate
202
75,237
97
32 turn-off delay true type
193
VCD
81,92,102,240 45
conversion
VCD file vector
UDPdeclaration
91
definition
unary
logical negation
unary
minus
unary
negation
unary
plus
62
statement
while-loop
63
white
wire
57
unconnected
module
input
unconnected
module
output
151
unconnectedport 151
151
wire
138
space 25,26,44 233
net
37
wor 38
write task 168
40
net
X
32
unidirectional switch
77
xnor
32
unknown
39
waveform 21,120,207,243
57
underscore
W
wand
147
modeling
undeclared
177
violation
90
UDP instantiation 90,92,107,147 UDP
keyword 41
verification 18
UDP 3, 90 UDP
52
register
vectored
U
193
vectornet 41,52,99,103
unsigned
number
unsigned
value
34,42, 51,53 58
gate
xor gate
71
15, 71
Z
unsized decimal number
51
unsized integer constant
51
counter 159,195 upward referencing 190
zero
delay
9,13,101,116,128,137,203,
235, 248
up-down
user-definedfunction user-defined
call
primitive
3,6,14,90
V
value
change
value set
32
dump
\342\226\241
54
193
ENGINEERING
ELECTRICAL
and Digital
Electronic
Design
Bhasker
J.
\302\256
Primer
HDL
Verilog
A
Second Edition this
With
book,
\342\226\241
Learn
\342\226\241
Obtain
building
can:
you
a
the fast and
HDL
Verilog thorough
understanding
of
HDL.
blocks
Verilog
\342\226\241
Find
out
how
to model
\342\226\241
Find
out
how
to test
easy way. basic
of the
hardware.
the hardware
model using a
test
bench. J.
is
Bhasker
Lucent
a Distinguished
Technologies.
Member
He has taught
of Technical Staff
VHDL and Verilog
HDL
at
Bell courses
Laboratories, at
Lucent
four years. He has also four other books on hardware description languages and synthesis includingthe best-selling \"A VHDL Primer\" and \"A VHDL Synthesis Primer\". Bhasker has a Ph.D.in Computer Science the University of Minnesota, M.Tech. in Computer Technology and a Technologies
for more than
written
books
from
B.Tech.in Electrical
Engineering
from
the
Indian
Institute
of Technology,
New
Delhi. ISBN
0-9650391-7-X
56495>
Star
Galaxy
Publishing
780965\"039178