Вы находитесь на странице: 1из 63

The Verilog Hardware Description Language

Introduction
Increasing complexities of contemporary systems
Demand the use of increasingly powerful tools
Pencil and paper methods
No longer reasonable in large sense

Tools today increasingly computer based


Collection and practice
Called electronic design automation - EDA

Today hardware portion of design


Follows design flow similar to software development
Many of the same methodologies apply
Designs developed using hardware design languages HDLs
Managed same way as software developments
Following a formal and disciplined development process
Can lead high quality reliable safe products at its end

Major focus in ensuing discussions will be on hardware side of the development cycle
None-the-less software plays major role in development of todays embedded
systems

Will use Verilog HDL as major tool in developing then synthesizing hardware models
Should be quite familiar with basic Verilog and structure of Verilog program

Over next several lessons will take study of language and modeling to next level
Will begin with review of purpose of Verilog
Introduce embedded development cycle
Examine some good design and coding practices
Examine how to utilize different modeling levels
Incorporate real-world effects into Verilog models
Then identify some Verilog constructs that cannot be synthesized into hardware
How to model real-world effects

Important considerations
9 End goal of Verilog program
A solid robust reliable system
9 Verilog is a hardware design language not a software programming language
- 1 of 63 -
9 Many of tools and techniques appropriate to good software development
Also appropriate to developing good Verilog designs
9 Modeling design using Verilog is intermediate step
9 End goal of Verilog program is synthesis into hardware

Birefly examine traditional approach to hardware design

Traditional Hardware Design Traditional Hardware Design HDL Based Hardware Design
User Inputs

Traditional approach
9 Identify requirements and formulate specification Requirements
Analysis

9 Functional decomposition Requirements


Requirements
Definition
Definition

9 Formulate architecture Specification

9 Map modules to architecture Functional Functional


Specification Specification

Functional Functional

9 Design comprising modules Diagram


System
Architecture
Diagram

Hardware
Architecture
At gate level Hardware
Architecture
Specification
Behavioural Model
Specification
Draw logic diagram or schematic Hardware Design

9 Build modules Block Diagram Data Flow Model


Verified Model

Test modules to verify functionality Hardware


Implementation

Make necessary modifications Schematic and


Logic Diagrams Electronic Data Files
Physical Prototype
Prototype(s)

Based upon testing Hardware Testing

9 Integrate modules into subsystems Verified


Hardware
Verified Physical
Hardware

Test modules to verify functionality System


Integration

Make necessary modifications Verified System Verified System

Based upon testing System Validation

9 Integrate modules into systems Validated System Validated System

Test modules to verify functionality Operation and


Maintenance

Make necessary modifications


Based upon testing
9 Formulate and confirm
Timing and operational requirements
Other constraints

For contemporary designs


Serial path of traditional approach no longer feasible
Driven by
Complexity
Physical constraints
Circuit will operate differently
When spread out on bench
Reduced to IC or PLD
- 2 of 63 -
Most contemporary designs
Mix of hardware and software
Dont have luxury of approaching in serial manner
First hardware then software

Models and Modeling


Based upon limitations of traditional approach to hardware design
Need to consider alternate approaches
Today modeling and HDLs are an essential part of design

Lets look briefly at


Motivation for modeling
What we are modeling
Essential characteristics for modeling method

Why are We Modeling?


Primarily we use models to represent a description of
Real system or one that will become real
When it is designed
Models give us different views of our system
External, internal, abstract, behavioural, structural
Model gives us means to describe characteristics of system to be designed
Provides basis for later verification
Models are cheaper than building complete system
To test design concept
Models allow us to execute test that may be too hazardous to run
During preliminary development

In design process
Model precedes actual design
Provides opportunity to quickly explore variety of alternative approaches
Cheaply
Quickly

What are We Modeling?


To effectively formulate a good model
Must understand what we are modeling
Our target is embedded applications

- 3 of 63 -
We know that embedded systems are
Reactive
System runs continuously
Responds or reacts to signals from external environment
Often real-time
Time constraints imposed on behaviour
Heterogeneous
Composed of hardware and software pieces
Hardware can be PLD, ASIC, custom IC, microprocessor, combination
Supported by different development environments

We need to distinguish
9 Model
9 Language used to express the model
Can very easily develop models using
C, C++, Java
Matlab, PSPICE
Etc.
9 Final hardware implementation

Qualifying the Model


Restating the model expresses an abstraction of the real world
Intended to give an abstract representation
Portion of real world
Allows us to temporarily ignore certain details
As we gain understanding of problem

To be useful
We can hypothesize some essential general capabilities
Abstraction
Must allow us to express and examine behaviour
Of complete system
Unburdened by details of sub-components
Refinement
Must allow us to express and decompose behaviour of system
At different levels of granularity
Structure
Must be able to express system as set of interconnected modules
Communication
- 4 of 63 -
Must support inter module communication method
Should support synchronization method
Easy to interpret
Must express anticipated behaviour or aspect being modeled
In comprehensible format

Two classifications of model are particularly useful


Conceptual and analytic

Conceptual
Precedes analytic
Allow us to work at high level of abstraction
Uses a symbolic means
To capture qualitative aspects of problem

Useful during early stages of design


9 Formulating specification
9 High-level architecture
9 Early stages of partitioning the system
9 Allow us to grasp and work with complexities of a design
To focus on essential details while ignoring others
Are behavioural in nature

Analytic
Permits analysis at lower levels of detail
Use mathematical or logical relations
Express quantitative physical behaviour

Useful during middle and later stages of design


9 Later stages of partitioning
9 Modeling and analyzing detailed architectures
9 Verifying detailed performances
9 Making performance trade-offs
Are more structural in nature

- 5 of 63 -
Important Characteristics of Models
To be effective
Models should give us ability to express
1. Modularity and hierarchy
Should be able to express
Static and dynamic behaviour
Structural and functional construction
2. Relationships among subsystems
Should be able to express
Sequential and concurrent flow of control
Inter subsystem synchronization and communication
Temporal behaviour
3. Communication amongst tools
4. Use of legacy designs or behaviours
5. Affects of real-world physics on circuit and signal behaviour
6. Ideally models should be executable

Later this is how we verify the system throughout design process

Major focus of discussions will be on hardware side of the cycle


None-the-less software plays major role in development of todays embedded
systems

Will use Verilog HDL as major tool in developing then synthesizing hardware models
Should be quite familiar with basic Verilog and structure of Verilog program

What is Verilog?
Verilog is a hardware description language - HDL
Provides a means of specifying a digital system
At a wide range of levels of abstraction
Language supports
Early conceptual stages of design
With its behavioral level of abstraction
Later implementation stages
Data and control flow with dataflow level of abstraction
Detailed device level model
With its structural level of abstraction

- 6 of 63 -
Language provides hierarchical constructs
Allows the designer to control the complexity of a description

Note: this description is an excerpt from the book


Verilog Hardware Description Language, by Thomas and Moorby.

Typical introduction to Verilog focuses on modeling ability


Generally little emphasis on mapping of model into physical hardware
Lets examine the difference

Why use Verilog?


Why use Verilog indeed
Why use any modeling language for that matter
As we know circuits and systems we are developing today
Growing in capability and complexity every day

As noted: yesterday a sketch on a piece of paper and a handful of parts


Sufficient to try out a design idea
Today that is no longer possible
Why not viable approach today
Speed
Parasitics
What else
Idea is
Modeled using computer based tools and languages
Synthesized into the desired hardware implementation
Test and verify the design
We use two key words here model and synthesize
While test is important
It applies no matter what approach is used

- 7 of 63 -
Looking at two components of development process
Objectives of Verilog HDL modeling
Capture and verify behaviour of design prior to committing to physical hardware
Process entails
9 Mapping the system requirements into design that meets those
requirements
Sentence makes very strong and important statement
9 Understanding real-world physical constraints and limitations of
Modeled parts and environment
9 Incorporating effects of identified constraints and limitations into model
Includes variations on such constraints and limitations
9 Verifying that modeled design meets or exceeds specified requirements
Subject to real-world physical constraints and limitations

Objectives of Verilog HDL synthesis


Map modeled design to physical hardware and verify behaviour of design
Process entails
9 Removing all modeled constraints and limitations from model
Real-world constraints and limitations already exist in target
environment
9 Mapping design to physical hardware as programmable logic device or IC
9 Verifying that design meets or exceeds specified requirements
Subject to actual real-world physical constraints and limitations
9 Revisiting modeling process as necessary if design does not meet specs

A number of languages that support such a design approach


Verilog and VHDL
Two of the more common
SystemC
For modeling both the hardware and software components
Finding its way into an increasing number of designs in the embedded world

- 8 of 63 -
Working with the Verilog HDL HDL Based Design
We will
Begin with some useful information on
Several different Verilog data types
Follow with quick review of
Basic components and organization of a Verilog program
Review gate-level or structural modeling
Combinational logic circuits
Sequential circuits
Introduce dataflow and behavioral models
Examine some important tools and capabilities of language
Facilitate fine grained modeling and test of a design

Emphasizing last point important to recognize


Design is only one aspect of the product development
Each design must also be tested
Confirm that it meets specified requirements and the objectives
Of the modeling process

To do so must have a specification


Level of formality varies
To that end will also discuss how one can formulate test suites
To verify the intended operation.
Material on testing will lay the foundation
To enable developer to build test cases that will support testing to desired level

Variables and Nets


Verilog language defines several different kinds of variables and nets
These used to
Hold logical signals
Interconnect various components or modules
That make up a Verilog program

- 9 of 63 -
Variable
Verilog variable like a variable in C, C++, or Java
Can be assigned a value
Will hold that value until a subsequent assignment replaces the value
Net
Net represents a class of primitive data types
Used to model a node or electrical connection in a circuit
Cannot
Be assigned to
Hold a value
Value results from being continuously driven by output of a logical device
If a net is not driven
Takes on the default value of z
Meaning high impedance or floating.
Wire
A wire type is a kind of net
Like real world wires are used to
Connect output of one logic element to
Input(s) of other logical elements
Because it is a net
Value of a wire can only be changed
As result of a gate or a behavioral statement driving it
Reg
A reg is a kind of variable
Value of a reg or register
Can be changed directly by an assignment
One should not confuse the Verilog reg with the hardware register
The reg is simply an entity that can hold a value
Default value of a reg data type is x, or unknown
The syntax for the reg and wire declarations is given as

Syntax
reg regList;
wire wireList;

- 10 of 63 -
Declaring Multi-Bit Signals
Often necessary to represent multi-bit wires
Formally such sets called vectors
A 3-bit wire that can carry digital signals representing the values 0..7
Called a 3 bit vector
Types reg and wire can also be formed into a bus such as

Syntax
Big Endian
reg [msb:lsb] reg_list
wire [msb:lsb] wire_list;

Little Endian
reg [lsb:msb] reg_list
wire [lsb:msb] wire_list;

msb is the bit index of the most significant bit


lsb is the bit index of the least significant bit

The value of the lsb index must be zero


Since bit position 0 conventionally denotes the least-significant bit

Such statements configure a set of individual wires


So that they can now be treated as a group

wire [2:0] myWires; // a 3-bit signal (a bus)


reg [15:0] aState; // a 16-bit state holding value

The declaration myWires


Declares a 3-bit signal that has
MSB (the 22s place) as myWires[2]
Middle bit of myWires[1].
LSB (the 20s place) as myWires[0]
The individual signals can be used
Just like any other binary value in Verilog

and a1(myWires[2], myWires[0], C);

Statement
ANDs together C and the LSB of myWires
Puts the result in the MSB of myWires.

- 11 of 63 -
Note again
We are not assigning conjunction to myWires[2]
The gate a1 is driving that signal
Only way myWires[2] can change
If output of gate changes because input changed

This bus specification


Can be extended to input and output lists as well
Multi-bit signals can be passed together to a module
module random(bus1, bus2);
output [31:0] bus1;
input [19:0] bus2;
wire c;

anotherRandom ar1(C, bus2, bus1);


endmodule

Subsets of Multi-Bit Expressions


On occasion its necessary to break apart multi-bit values
Can do that by selecting a subset of a value

reg [31:0] myReg;


initial myReg[3:1] = b101;

This would set


myReg[3] = 1
myReg [2] = 0
myReg [1] = 1
All other bits of myReg will not be altered

One can also use the same form to take a subset of a multi-bit wire
Pass it as an input to another module

wire[31:0] myWires;

output myWires[3:1];

- 12 of 63 -
Numbers
Verilog supports two types of number specification
Sized
Unsized

Sized Numbers
Sized numbers declaration comprises
Size, base, value

Syntax
size base value
size specifies number of bits in number
base identifies the base
legal bases: d or D decimal
o or O octal
h or H - hexadecimal
value numeric value in specified base

Examples
4b1010 // a 4 bit binary number
8d35 // an 8 bit (2 digit) decimal number
16hface // a 16 bit (4 digit) hex number

Unsized Numbers
Unsized numbers
Without a base specification
Decimal by default

Without a size specification


Have simulator/machine default number of bits
Must be at least 32

Examples
1010 // a 32 bit decimal number by default
o35 // a 32 bit octal number
hface // a 32 bit hex number

- 13 of 63 -
Unknown or High Impedance Values
Verilog supports numeric specification
For numbers with unknown or high impedance bits/digits
Symbols used for specification
x unknown value
z high impedance value

Examples
4b101x // a bit binary number with lsb unknown
8dz5 // an 8 bit (2 digit) decimal number
// with high impedance ms digit
16hfzxe // a 16 bit (4 digit) hex number with high impedance and
// unknown digits
The Verilog Models
Will now examine models and modeling tools
At each of the levels
Three Models The Gate-Level, the Dataflow, and the Behavioral
Verilog language supports the development of models
At three different primary levels of abstraction
Gate level model
Gives most detailed expression
Behavioral level
Gives most abstract

Gate level
Modules are implemented by interconnecting the various logic gates
Similar to working with SSI and MSI components
Also known as a structural model
Dataflow level
Module is implemented by specifying the movement of the data
Amongst the comprising hardware registers
Model is analogous to the RTL (Register Transfer Level) level
Used in specifying a microprocessor / computer architecture
Behavioral level
Modeling is based upon an algorithmic description of the problem
Without regard for the underlying hardware.
Language does support modeling at the transistor level
- 14 of 63 -
Work at that level will not be discussed here

Model Development
Will begin at the gate level and work up
Path will be to use the three different levels
To introduce the core aspects of the language
Because working at the gate level is the most familiar
Will begin / review at that level then move up to higher levels of abstraction
As we do so we will also introduce several aspects of the language
Apply to all levels of abstraction
Will utilize the same combinational and sequential designs
To illustrate how a model is developed at each of the different levels

Combinational circuits
Will use an AND and an OR gate
Extended to implement a NAND and a NOR circuit

Sequential circuits
Will progress from
Basic latch
Gated latch
Flip-flop
Two bit binary counter

Structural / Gate Level Development


At the gate level
Working with the basic logic gates and flip-flops
Typically found in any detailed digital logic diagram
Devices model the behavior of the parts
We can buy from any electronics store
Might design into an ASIC or use in FPGA
buf not
and nand
or nor
Verilog supports logic gate primitives identified in adjacent figure xor xnor
bufif1 bufif0
As predefined intrinsic modules notif1 notif0
Prototypes for each of the gates given in the following figure

- 15 of 63 -
buf <name> (OUT1, IN1); // Sets output equal to input
not <name> (OUT1, IN1); // Sets output to opposite of input
and <name> (OUT, IN1, IN2); // Sets output to AND of inputs
or <name> (OUT, IN1, IN2); // Sets output to OR of inputs
nand <name> (OUT, IN1, IN2); // Sets to NAND of inputs
nor <name> (OUT, IN1, IN2); // Sets output to NOR of inputs
xor <name> (OUT, IN1, IN2); // Sets output to XOR of inputs
xnor <name> (OUT, IN1, IN2); // Sets to XNOR of inputs
bufif1<name> (out, in, cntrl) // Sets output to input if ctrl is 1 tristate otherwise
bufif0<name> (out, in, cntrl) // Sets output to not input if ctrl is 1 tristate otherwise
notif1<name> (out, in, cntrl) // Sets output to input if ctrl is 0 tristate otherwise
notif0<name> (out, in, cntrl) // Sets output to not input if ctrl is 0 tristate otherwise

Prototypes appear as for C or C++ function or procedure


The <name> for a gate instance
Must begin with a letter
Thereafter can be any combination of
letters,
numbers
underscore _
$.

Gates with more than two inputs


Created by simply including additional inputs in the declaration
Output list appears first followed by the input list

Example
A five-input and gate is declared as

and <name> (OUT, IN1, IN2, IN3, IN4, IN5); // 5-input AND
Creating Combinational Logic Modules
At the gate level
Verilog module really is a collection of logic gates
Each time we declare and define a module
We are creating that set of gates

Structural or gate level model of a combinational circuit


Reflects the physical gates used to implement the design

To illustrate the basic process of


Creating a Verilog program
- 16 of 63 -
Modeling combinational logic at the gate level
Will begin with the following simple circuit.
Example of a simple module begins with following logic diagram
Module requires a name
Call it AndOr
// Compute the logical AND and OR of inputs A and B.
module AndOr(AandB, AorB, A, B);
output AandB, AorB;
input A, B;

and myAnd (AandB, A, B);


or myOr (AorB, A, B);
endmodule

Can analyze the module line by line

// Compute the logical AND and OR of inputs A and B

First line is a comment designated by the //


Everything on a line after a // is ignored
Comments can appear
On separate lines or at the end of lines of code
Top of module begins with keyword module
module AndOr(AandB, AorB, A, B);
output AandB, AorB;
input A, B;

Indicates
Start of module
Name of the module
AndOr
List of signals connected to that module
Subsequent lines
Declare
First two binary values generated by module are outputs
Next two (A, B) are inputs to the module

The next lines

- 17 of 63 -
and myAnd (AandB, A, B);
or myOr (AorB, A, B);

Create instances of two gates


AND gate called myAnd with output AandB and inputs A and B
OR gate called myOr with output orOut and inputs A and B
We declare such intrinsic components
Same as we did in C, C++ or Java with int, float, or char

The final line declares the end of the module


endmodule

All modules must end with an endmodule statement


Observe endmodule statement
Is the only one that is not terminated by a semicolon

Using Combinational Modules


We build up a complex traditional software program by
Having procedures call sub procedures
Composing or aggregating classes into larger and more powerful structures
Verilog builds up complex circuits and systems from modules
Using a design approach similar to composition or aggregation

To illustrate the process,


Will use the previous AndOr module to build NandNor circuit
Begin with the logic diagram and Verilog module in following figure

- 18 of 63 -
// Compute the logical AND and OR of inputs A and B.
module AndOr(AandB, AorB, A, B);
output AandB, AorB;
input A, B;
and myAnd (AandB, A, B);
or myOr (AorB, A, B);
endmodule

// Compute the logical NAND and NOR of inputs X and Y.


module NandNor (XnandY, XnorY, X, Y);
output XnandY, XnorY;
input X, Y;
wire XandY, XorY;

AndOr myAndOr (XandY, XorY, X, Y);


not n1 (XnandY, XandY);
not n2 (XnorY, XorY);
endmodule

The NandNor module declares instance of the AndOr module


As it would any of the intrinsic types
One can declare multiple instances of a submodule
Another instance of the AndOr module
Could be added to the NandNor module
Each instance of the submodule
Creates a new set of gates
Three instance of AndOr would create a total of 23 = 6 gates
The wire
Statement

wire XandY, XorY;

Used to connect the outputs of the AndOr module


To the two not gates
These wires comprise a net that carries the signals
From the output of the AndOr module
To the inverters

- 19 of 63 -
The Real-World Affects Part 1
Lets take a first look at incorporating real-world affects
Into HDL models

Timing and Delays A First Look


In perfect world
Parts are ideal
Signals flow through wires and parts with no delay
In real world
Parts are not perfect
Signals are delayed by varying amounts
Verilog can model signal propagation delay through basic gates
Using the # operator

Device Delays
Basic syntax is given as

Syntax
#delay device;

We modify the AndOr module


To incorporate delays into the design
To model real world behavior

// Compute the logical AND and OR of inputs A and B.


module AndOr(AandB, AorB, A, B);
output AandB, AorB;
input A, B;

and #5 myAnd (AandB, A, B);


or #10 myOr (AorB, A, B);
endmodule

The line
and #5 myAnd (AandB, A, B);

states the AND gate takes 5 time units


to propagate a change on the input to the output
The delay through the OR gate is twice as long
Taking 10 time units
or #10 myOr (AorB, A, B);

- 20 of 63 -
Units of time can be whatever we want
As long as we use consistent values

Net Delays
The delay operator
Can also be applied to a net
When delay specified on a net
Any state change on input to net
Delayed accordingly
Syntax follows that of device delay
Syntax
#delay wire;

Using Symbolic Constants


One can use what are called magic numbers
More robust design
Will use named or symbolic constants
Variables whose value is
Set in one place
Used throughout a piece of code
Learned symbolic constant in Verilog
Called a parameter
Parameter defined and initialized
Using the following syntax.
Syntax
parameter = aValue

The following code fragment illustrates symbolic constant for


Inclusion of a delay of 2 time units in a part model

parameter propagationDelay = 2;
not #propagationDelay myNot (sigOut, sigIn);

Lets modify the previous example to


Reflect more professional approach
Also incorporate the signal rise and fall times

- 21 of 63 -
// Compute the logical AND and OR of inputs A and B.
module AndOr(AandB, AorB, A, B);
output AandB, AorB;
input A, B;

parameter delay0 = 5;
parameter delay1 = 10;
parameter riseTime = 3;
parameter fallTime = 4;

and #(riseTime, fallTime, delay0) myAnd (AandB, A, B);


or #(riseTime, fallTime, delay1) myOr (AorB, A, B);
endmodule

Modified code sets


Gate delays delay0 and delay1
Rise and fall times
To the values specified by remaining two parameters
To speed up either gate
One could simply change the value in the parameter lines
Sequential Logic
Sequential logic modeled at the gate level
First developing the appropriate flip-flop module
Then implementing the design
As a composition of
Instances of that module
Necessary gates
Interconnecting the components with wires
SR Latch
Begin with the basic SR latch

// Gate Level Model S R Latch


module srLatch(q, qnot, s, r);
input s, r;
output q, qnot;
parameter delay0 = 2;
// implement the latch
nor #delay0 n0(q, r, qnot);
nor #delay0 n1(qnot, s, q);
endmodule

- 22 of 63 -
SR Latch with Enable
Basic design can be extended to include
Enable as an additional level of control

// Gate Level Model


// Gated SR Latch with clear

module gsrLatch(q, qnot, sg, rg, clr, enab);


input sg, rg, clr, enab;
output q, qnot;
parameter delay0 = 2;

// Build the gating logic


not n0(nclr, clr);
and and0(rL, rg, clr, enab);
and and1(sL, sg, clr, enab);

// Build the basic RS latch


nor #delay0 n0(q, rL, nclr, qnot);
nor #delay0 n1(qnot, sL, q);

endmodule

Master Slave Configuration


The master slave implementation using the gated latch follows naturally

// Use two SR Latches


// in a master slave configuration to build a flip-flop

module srmsff(q, qnot, s, r, clr, clk);


input s, r, clk, clr;
output q, qnot;

not n0(nclk, clk);


gsrLatch master(qm, qnotm, s, r, clr, clk);
gsrLatch slave(q, qnot, qm, qnotm, clr, nclk);

endmodule

- 23 of 63 -
Binary Counter
Can use the SR flip-flop to build
Simple two-bit synchronous binary up counter

// Build a two bit binary up counter


// using master slave SR flip-flops

module TwoBitCntr(qA, qB, clr, clk);


input clr, clk;
output qA, qB;

and a1(sA, qAnot, qB);


and a2(rA, qA, qB);

srmsff FFB(qB, qBnot, qBnot, qB, clr, clk );


srmsff FFA(qA, qAnot, sA, rA, clr, clk);

endmodule

The Dataflow Model


Gate level modeling is an effective approach for working with smaller problems
Such an approach directly follows typical detailed logic diagram
Thus simplifies moving
From design
To model and simulation

Today embedded applications


Continually increasing in complexity

SSI and MSI modules of yesterday


Being replaced by ASICs, FPGAs, and microprocessors
Developing a complete design at the gate level
No longer feasible
Working at the gate level
Similar writing sophisticated application in assembler
Can be done but is impractical

- 24 of 63 -
Developing at a higher level
Not without problems
Farther that one moves
From the low level details and
Increases reliance on tools
To produce those details
The greater the risk that the tools
Will produce less than optimum design

Ability to push the limits of a design and a technology


Comes from
Years of experience
Understanding of the problem
Tools
Can help us to solve the majority of the design problems
Not sufficiently advanced to solve all autonomously

Dataflow Modeling
Views a design from the perspective of
Data moving through the system
From source to destination
In the digital world
Such a view often referred to as RTL or register transfer level design
Contemporary tools able to accept a dataflow model as input
Produce a low-level logic gate implementation
Through a process called logic synthesis
Operators
Syntax and operators used in Verilog at the dataflow level
Follow that of the C language very closely
Table below gives the most commonly used operators

- 25 of 63 -
Operator Symbol Operation
Arithmetic + Add
- Subtract
/ Divide
* Multiply
% Modulus

Relational > Greater Than


< Less Than
>= Greater Than or Equal
<= Less Than or Equal

Equality == Equal
!= Not Equal

Logical ! Logical Negation


&& Logical AND
|| Logical OR

Bitwise ~ Bitwise Negation


& Bitwise AND
| Bitwise OR

Shift << Shift Left


>> Shift Right

Continuous Assignment
At the dataflow level
Design is modeled as movement of data
From module to module
To affect the application
That data moves over a net
Thus, a fundamental element of such modeling
Is ability to drive a value
From a source module
Onto the interconnecting net
To the destination modules
In Verilog such ability
Expressed by continuous assignment

- 26 of 63 -
Continuous assignment statement
Specified using the following syntax

Syntax
assign destination net = source net expression

Left hand side of the continuous assignment


Must be
Scalar or vector (multiple lines) net
Right hand side of the expression
Can be a net, register, or function call return
Must be of the same size as the left hand side

Scalar cannot be assigned to a vector


Vice versa, for example.
A continuous assignment is always active
Change on the right hand side forces evaluation of the left hand side
With the resulting assignment of the right hand side value
To the left hand side net

Combinational Logic // continuous assignment


module AndOr(AandB, AorB, A, B);
We illustrate a combinational dataflow model output AandB, AorB;
input A, B;
Using the AndOr circuit designed earlier
wire AandB, AorB;
That model using the continuous assignment parameter delay0 = 10;
Expressed in the adjacent code fragment assign AandB = A&B;
assign AorB = A|B;
Implementation using the bitwise AND and OR operators
endmodule
Should be familiar from work with C counterparts

The Real-World Affects Part 2


Delays
Moving up one level of abstraction from the gate level
Does not preclude need to model real world effects on circuit behavior
The Verilog model for delay at the dataflow level
Follows naturally from that at the gate level
The syntax is given as
Syntax
assign #delay net

- 27 of 63 -
The model for the AndOr circuit designed earlier
Can include delays as seen in the following code fragment

// continuous assignment
module AndOr(AandB, AorB, A, B);
output AandB, AorB;
input A, B;

wire AandB, AorB;


parameter delay0 = 10;

assign #delay0 AandB = A&B;


assign #delay0 AorB = A|B;

endmodule

The outputs of the system


Will now change 10 time units after either of the input signals changes

Time, A, B, AandB, AorB


0 1, 1, x, x
10 0, 1, 1, 1
20 0, 0, 0, 1
30 0, 1, 0, 0
40 0, 1, 0, 1

Rise and fall time delays incorporated in a similar manner


Will discuss in greater detail later

Syntax for all three is given as

Syntax
assign # (rise time, fall time, delay) net

The model for the AndOr circuit designed earlier


Can include all three delays

- 28 of 63 -
// Compute the logical AND and OR of inputs A and B.
module AndOr(AandB, AorB, A, B);
output AandB, AorB;
input A, B;

wire AandB, AorB;


parameter delay0 = 10;
parameter rise = 5;
parameter fall = 7;

assign #(rise, fall,delay0) AandB = A&B;


assign #(rise, fall,delay0) AorB = A|B;

endmodule

Outputs of the system


Now change 10 time units after either of the input signals changes
Reflect the rise and fall times

Time, A, B, AandB, AorB


0 1, 1, x, x
5 1, 1, 1, 1
10 0, 1, 1, 1
17 0, 1, 0, 1
20 0, 0, 0, 1
30 0, 1, 0, 0

Sequential Logic
// Dataflow Level Model
Following three code modules // Gated SR Latch
Evolve the dataflow implementations of module gsrLatch(q, qnot, sg, rg, clr, enab);
input sg, rg, clr, enab;
Gated SR latch output q, qnot;
Master-slave SR flip-flop wire rL, sL;
wire q, qnot;
Two bit binary counter designed earlier
// Build the gating logic

assign rL = rg & clr & enab;


assign sL = sg & clr & enab;

// Build the basic RS latch


assign q = ~(rL | ~clr | qnot);
assign qnot = ~(sL | q);

endmodule

- 29 of 63 -
// Use two SR Latches in // Build a synchronous two bit binary up counter
// a master slave configuration to build a flip-flop // using master slave SR flip-flops

module srmsff(q, qnot, s, r, clk, clr); module TwoBitCntr(qA, qB, clr, clk);
input s, r, clk, clr; input clr, clk;
output q, qnot; output qA, qB;

gsrLatch master(qm, qmnot, s, r, clr, clk); wire sA, rA;


gsrLatch slave(q, qnot, qm, qmnot, clr, ~clk); wire qA, qAnot, qB;

endmodule assign sA = qAnot & qB;


assign rA = qA & qB;

srmsff FFB(qB, qBnot, qBnot, qB, clk, clr);


srmsff FFA(qA, qAnot, sA, rA, clk, clr);

endmodule

The Behavioural Model


The behavioral model increases the design abstraction
By an additional level
Thinking about the design
Moves above considerations of the flow of data within the system
To the algorithms that express the behavior of the system
At the behavioral level
Model begins to appear more like a C or C++ program than a digital circuit
Flow of control through the system
Expressed in the familiar looping and branching constructs
Rather than in logic gates

Program Structure
At the behavioral level
One of the major differences between languages such as C or C++ becomes clear.
Unlike either C or C++in which flow of control is generally sequential
Flow of control in Verilog is concurrent
Statements in C or C++ execute in series
Those in Verilog execute in parallel

always and initial Statements


At the behavioral level
Verilog program is structured as
Collection of initial and/or always blocks

- 30 of 63 -
Each such block
Express a separate flow of control
Each will finish execution independent of any other block
Module may define multiple initial and/or always blocks
Such blocks cannot be nested

Beyond the input, output statements, and parameter declarations


All behavioral statements must be included in either one of these blocks
Statements contained in an initial block
Delimited by begin and end
Evaluated one time at the start of a simulation
Statements contained in an always block
Delimited by begin and end
Evaluated continuously from the start of a simulation

The always and initial statements


Two keywords that allow one to set stimuli to a module
The syntax for the initial statement is given as

Syntax
initial
begin
Initial statements
end

The syntax for the always statement is given as

Syntax
always
begin
Statements to be always executed
end

- 31 of 63 -
Operators
Like dataflow model
Syntax and operators used in Verilog at the behavioural level
Follow that of the C language very closely
Table below several additional operators

Operator Symbol Operation


Reduction & Reduction AND
~& Reduction NAND
| Reduction OR
~| Reduction NOR
^ Reduction XOR
~^ Reduction XNOR

Condition ?: If else

Concatenation {expr0,expr1..exprn-1} Concatenate smaller expressions

Replication {number {expr0,expr1..exprn-1} Expr set replicated number times

Reduction
Reduction operators
Operate on all bits of single operand
Product 1 bit result
If any bit in operand is z or x
Result is x
Reduction AND
If any bit in operand is 0 result is 0 else result is 1
Reduction NAND
Inverse of reduction AND
Reduction OR
If any bit in operand is 1 result is 1 else result is 0
Reduction NOR
Inverse of reduction OR
Reduction XOR
If even number of 1s in operand result is 0 else result is 1
Reduction XNOR
Inverse of reduction XOR

- 32 of 63 -
Condition
Condition operator
Similar to triple operator in C

condExpr ? expr0 : expr1


if condExpr is true
return expr0
else
return expr1

Concatenation
Concatenation is operation of joining bits
From smaller expressions to form larger one

a[7:0] = {b[3:0], c[3:0]};


builds 8 bit expression from two four bit ones
Can also use to swap upper and lower fields within number
a[7:0] = {a[3:0], a[7:4]};

Replication
Creates expression by replicating and concatenating
Target expression
Specified number of times

dbus = {4, {4b1101}};


Builds following 16 bit expression
1101110111011101
Can also use to implement sign extension

abus = {8,{dbus[7],dbus};

Procedural Assignment
Assignment in the behavioral model differs from
That in either the gate level or dataflow model
In the behavioral model procedural assignment statements
Used to update the circuit state variables

- 33 of 63 -
In the dataflow model
Continuous assignment construct
Continually updates the value on the net on left hand side
In the behavioral model
Value is only updated
As result of the execution of a procedural assignment statement
Verilog supports
Two kinds of procedural assignment
Blocking and non-blocking
Two kinds of blocks
Sequential and parallel
Statements in a sequential block
Delimited by a begin and an end
Executed in sequence
Statements in a parallel block
Delimited by a fork and a join
Executed in parallel

Blocking assignment statements


Executed in the order written in a sequential block
Will block the execution of subsequent statements
That appear in the same sequential block
Will not block the execution of statements
That appear in a parallel block
Non-blocking assignment statements
Will not block subsequent statements in a sequential block

Blocking assignment will successively evaluate


Right hand side then the left hand side
Each an assignment statement in a sequential block
Non-blocking assignment will evaluate all
Right hand sides then all of the left hand sides
Each statement in a sequential block

- 34 of 63 -
Syntax for the two types of assignment is given in the following

Syntax
Blocking
aVariable = aValue;
Nonblocking
aVariable <= aValue;

The Real-World Affects Part 3


Delays
Delays may be incorporated on either side of the assignment statement

Syntax
Blocking
aVariable = #d aValue;
#d aVariable = aValue
Nonblocking
aVariable <= #d aValue;
#d aVariable <= aValue

How each is interpreted can be a bit confusing

Blocking
The first statement says
Evaluate aValue then block for d time units
Before assigning aValue to aVariable
Any subsequent use of aVariable will get the new value
The second statement says
Block for d time units
Before evaluating aVariable = aValue
The variable aVariable will have the value aValue
d time units in future

Non-blocking
The first statement says
Evaluate aValue
Schedule aVariable to be updated d time units later
However continue processing other statements
Any other variables using the value of aVariable
Within the next d time units will be assigned the old value
The second statement says
- 35 of 63 -
Wait d time units before evaluating aVariable = aValue
Variable aVariable will have the value aValue
d time units in future

// Illustrate Procedural blocking and nonblocking assignment


// Illustrate Procedural blocking and // Separate initial block
// nonblocking assignment
// Separate initial block initial
begin
module blockingNonblocking(); // delay on left hand side
// declare temp registers
reg a,b,c,d,e,f,g,h,i,j,k,l; // blocking
#10 g = 1;
// initialize reg variables #2 h = 1;
initial #4 i = 1;
begin
a = 0; b = 0; c = 0; d = 0; e = 0; f = 0; // nonblocking
g = 0; h = 0; i = 0; j = 0; k = 0; l = 0; #10 j <= 1;
end #2 k <= 1;
#4 l <= 1;
initial
begin end
// delay on right hand side
initial
// blocking begin
a = #10 1; $display("\ttime, \ta, \tb, \tc, \td, \te, \tf, \tg, \th, \ti, \tj, \tk, \tl");
b = #2 1; $monitor($time, " \t%b, \t%b, \t%b, \t%b, \t%b, \t%b, \t%b, \t%b,
c = #4 1; \t%b, \t%b, \t%b, t%b",a,b,c,d,e,f,g,h,i,j,k,l);
#50 $finish(1);
// nonblocking end
d <= #10 1;
e <= #2 1;
f <= #4 1;
end

time, a, b, c, d, e, f, g, h, i, j, k, l
0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
10 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0
12 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0
16 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0
18 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0
20 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0
26 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0
28 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0
32 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1

From the execution of the code fragment


Variables a and g from the two initial blocks change state at time 10
Variables (b and c) and (h, and i) follow similarly
According to their specified delays or 2 and 4 time units
After a and g respectively

After the blocking statements have been evaluated

- 36 of 63 -
Non-blocking statements are evaluated.
Variable d is assigned the value 1 10 time units
After the blocking statements in the first initial block
Expression j<=1 is evaluated 10 time units
After the blocking statements in the second initial block
Variables e and f are evaluated 2 and 4 time units respectively
After the blocking statements in the first initial block
Finally expressions k<=1 and l <= 1 are evaluated 2 and 4 time units
After the blocking statements in the second initial block

// Illustrate Procedural blocking and


// delay on left hand side
// nonblocking assignment // blocking
// Single initial block #10 g = 1;
module blockingNonblocking(); #2 h = 1;
// declare temp registers #4 i = 1;
reg a,b,c,d,e,f,g,h,i,j,k,l;
// nonblocking
// initialize reg variables #10 j <= 1;
initial #2 k <= 1;
begin #4 l <= 1;
a = 0; b = 0; c = 0; d = 0; e = 0; f = 0; end
g = 0; h = 0; i = 0; j = 0; k = 0; l = 0; initial
end begin
$display("\ttime, \ta, \tb, \tc, \td, \te, \tf, \tg, \th, \ti, \tj, \tk, \tl");
initial $monitor($time, " \t%b, \t%b, \t%b, \t%b, \t%b, \t%b, \t%b,
\t%b, \t%b, \t%b, \t%b, \t%b",a,b,c,d,e,f,g,h,i,j,k,l);
begin
#50 $finish(1);
// delay on right hand side end
// blocking endmodule
a = #10 1;
b = #2 1;
c = #4 1;
// nonblocking
d <= #10 1;
time, a, b, c, d, e, f, g, h, i, j, k, l
e <= #2 1;
0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
f <= #4 1; 10 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
12 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
16 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0
18 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0
20 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0
26 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
28 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0
32 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0
42 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0
44 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0
48 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1

- 37 of 63 -
Major differences between the two implementations
Reflected in the evaluation times for the variables d, e, f, g, h, and i
Combinational Logic
The next example implements the earlier NandNor combinational logic circuit
Using a behavioral model
Utilizing both the blocking and non-blocking assignments
Right and left hand side delays

module blocking_nonblocking();
reg a,b, AandB,AorB, AnandB,AnorB;
reg e,f, EandF,EorF, EnandF,EnorF;

initial
begin
// Blocking Assignment
a = 1; b = 1;

// Delay on the right hand side


AandB = #10 a&b;
AnandB = #11 ~AandB;

// Delay on the left hand side


#10 AorB = a|b;
#11 AnorB = ~AorB;
end

// Non blocking Assignment


initial
begin
e = 1; f = 1;

// Delay on the right hand side


EandF <= #10 e&f;
EnandF <= #11 ~EandF;

// Delay on the left hand side


#12 EorF <= e|f;
#13 EnorF <= ~EorF;
end

initial
begin
$display("\t time\t a, \tb, \tAnandB, \tAnorB, \t\te, \tf, \tEnandF, \tEnorF");
$monitor($time, "\t%b \t%b \t%b \t\t%b \t\t%b \t %b \t %b \t\t%b", a,b, AnandB, AnorB, e, f, EnandF, EnorF);
#50 $finish(1);
end

endmodule

The outputs of the circuits for each of the cases are given

time a, b, AnandB, AnorB, e, f, EnandF, EnorF


0 1 1 x x 1 1 x x
21 1 1 0 x 1 1 x x
25 1 1 0 x 1 1 x 0
42 1 1 0 0 1 1 x 0

- 38 of 63 -
Based upon the order of evaluation of the non-blocking assignment
NAND operand is never assigned a valid value

Tools and Techniques


Before looking a behavioural models of sequential circuitry
Want to look at tools and techniques to
Make development and execution of models simpler
Will look first at those to aid in modeling flow of control
Essential in sequential machines
Flow of Control
The behavioral Verilog model supports
Familiar flow of control constructs
Branches, switches, and loops
Language provides support for event based control
Events
Verilog supports four different types of event based control
Given as
Regular event
Named event
OR event
Level
Each is identified by the event control symbol @
Verilog interprets an event as
Change in the value of either a net or a register
Such a change can be used to invoke
Evaluation of either a single statement of a block of statements
Syntax for each is given as follows

Syntax
Regular Event
@(signal) action
variable = @( signal) action
signal may be clock, posedge clock, negedge clock for example

Named Event
event anEvent // event is a keyword
always @(anEvent) action

OR Event
always @( signal1 or signal2 or signal3 or) action

Level
always wait( signal) action // wait is a keyword

- 39 of 63 -
Branches
Like the C and C++ languages
Verilog utilizes the if and if else constructs
Select alternate paths of execution
Based upon the value of a condition variable
Permitted combinations follow the C and C++ syntax

Syntax
if (condition)
statement;

If (condition)
statement1;
else
statement2;

If (condition1)
statement1;
else If (condition2)
statement2;
else
statement 3;

If statement comprises a block of statements,


the block must be delimited by the begin-end pair.

Case Statement
The switch or case statement in Verilog
Uses the Pascal rather than the C language syntax
Unlike the C switch
Once a statement or block of statements is evaluated
Flow of control leaves the case
Rather than continuing through the remaining alternatives

Syntax
case (expression)
label0: statement0;
label1: statement1;
.
.
labeln-1: statementn-1;
default: defaultStatement;
endcase

If statement comprises a block of statements,


the block must be delimited by the begin-end pair

- 40 of 63 -
Verilog supports two variants on basic case or switch statement

Syntax
casez treats all z values in case labels or expressions as dont cares

casex treats all x and z values in case labels or expressions as dont cares

Loops
Verilog language supports the four common loop constructs.
while
repeat
for
forever
First three should be familiar
From the C or C++ languages
Forever is unique to Verilog
Syntax for each is given as

Syntax
while(test)
begin
loop body
end

repeat(repeatcount)
begin
loop body
end

for(init; test; action)


begin
loop body
end

init and action are usually assignments.

forever
begin
loop body
end

- 41 of 63 -
Sequential Logic
As noted earlier behavioural model
Builds design algorithmically
The following three code modules evolve the behavioural implementations of
Gated SR latch
Master-slave SR flip-flop
Two bit binary counter

// Behavioral Level Model // Build a synchronous two bit binary up counter


// Gated SR Latch // using master slave SR flip-flops

module gsrLatch(q, qnot, s, r, clr, enab); module TwoBitCntr(qA, qB, clr, clk);
input s, r, enab, clr; input clr, clk;
output q, qnot; output qA, qB;

reg q, qnot; reg sA, rA;

always@ (~clr or enab) wire qA, qAnot, qB;


begin
if(~clr) always@(posedge clk)
begin begin
q = 1'b0; sA = qAnot & qB;
qnot = 1'b1; rA = qA & qB;
end end

else srmsff FFB(qB, qBnot, qBnot, qB, clk, clr);


begin srmsff FFA(qA, qAnot, sA, rA, clk, clr);
if (s & ~r) endmodule
begin
q <= s;
qnot <= r; // Use two SR Latches in a master slave
end // configuration to build a flip-flop
else if (~s & r)
begin module srmsff(q, qnot, s, r, clk, clr);
q <= s; input s, r, clk, clr;
qnot <= r; output q, qnot;
end
end gsrLatch master(qm, qmnot, s, r, clr, clk);
gsrLatch slave(q, qnot, qm, qmnot, clr, ~clk);
end
endmodule endmodule

The next code module illustrates


More commonly used approach for behavioural modeling of
Counting, timing, or registered types of designs

- 42 of 63 -
Rather than working with individual flip-flops
As noted earlier
Design is approached algorithmically

// Build a synchronous two bit binary up counter

module TwoBitCntr(state, clr, clk);


input clr, clk;
output[1:0] state;

reg[1:0] state;

// Name the states


parameter state0 = 2'b00;
parameter state1 = 2'b01;
parameter state2 = 2'b10;
parameter state3 = 2'b11;

// Build a synchronous two bit binary up counter

always@(~clr or negedge clk)


begin
if(~clr)
begin
state = state0;
end

else case(state)
state0:
state = state1;
state1:
state = state2;
state2:
state = state3;
state3:
state = state0;
endcase

end
endmodule

Testing and Verifying the Circuit


Once the circuit is designed and modeled in Verilog
We move into the next phase
First
Need to verify that the model functions properly

Next step is to use it for its intended purpose


To that end we perform any necessary
Functional, parametric, and stress tests on the design
Confirm the design before committing to hardware

At this point
- 43 of 63 -
Will review general structure for
Test bench
Tester
We will illustrate the verification phase
Using the NandNor circuit
To do this we create a test bench

The Test Bench


Test bench models the electronics workbench
Electronics workbench
Comprises the measurement and stimulus instruments
Circuit to be tested
The UUT

Verilog test bench


Comprises modules used for stimulus and measurement
These go in a test module
System modeled in Verilog
The UUT
Following diagram gives schematic representation

Test Bench Wires

Stimulus Measurement
UUT

High level pseudocode model for the test bench


Has the following general structure
module MyTest bench;
parameter declarations
wires

circuit module declarations


test module declaration
endmodule

Test bench plays the same role as does

- 44 of 63 -
main() function
In C or C++ and t
Top level class
In Java
Acts as the outermost container in the program
Lets look at the pieces
The Unit Under Test
The unit under test or UUT
Is system, subsystem, module
That we are testing
This is our design
We will use the gate level NandNor circuit as the UUT
To be tested and verified

During different phases of development life cycle


Testing for different reasons
Formulating and executing
Different kinds of tests
At any stage
Must have complete and accurate specification

Early stages confirming


High level functionality
Overall behaviour of design

Middle stages testing


Data and control flow through system
Timing
Mainly high level but will examine
Critical low-level timing aspects

- 45 of 63 -
Later stages verifying
It performs according to specification
Normal operation
Boundary operation
Inside, at, and outside boundaries
Each path through the logic circuit is functional
Timing
All high and low-level timing constraints met

System Tasks and Functions


As we bring the tester together we find
Verilog language provides standard system tasks
To aid in performing routine operations
Lets look at several of these

Time
Verilog simulations executed with respect to simulation time
Value stored in special register data type
Time variable declared using keyword time data type
Value of time variable can be retrieved
Using system function $time
// declare variable to hold current time
time simTime;
initial
begin
simTime = $time;
end

Displaying Information
Given purpose of developing Verilog program
Model a design
To confirm that it conforms to specification
During test of module under design and when test complete
Want to be able to
Annotate results
Observe values of
Input and output signals
Intermediate and final values of internal variables

- 46 of 63 -
$display and $monitor statements
The $display and $monitor are standard system tasks
Enable one to see the states of certain signals in text form
Output is typically directed to the screen (or window)
Difference between the two statements is
$display
Only evaluated when the directive is encountered during execution
$monitor
Evaluated every time any of the signals being monitored changes state
Syntax for the two directives is given as
Syntax
$display (["formatrString"], variableList);
$monitor (["formatString"], variableList);

The formatString
Optional for both statements
Both follow the C printf
Is a text string containing format variables that are to be instantiated
From the values specified in variableList
More commonly used format variables given in following table.

Format Variable Display

%b Binary

%d Decimal

%o Octal

%h Hexadecimal

%c Character

By convention
Logic high is denoted as a 1
Logic low is denoted as a 0
Unknown state is denoted as an x

$display and $monitor output statements


Must be placed within an initial or always block

- 47 of 63 -
Stopping and Finishing
There are several system tasks
Can be used to terminate or temporarily suspend a simulation
These are the
$stop and $finish statements
As names suggest
Used to either stop or finish a simulation
$stop directs the simulation to the interactive mode
Used when the designer wishes to suspend the simulation prior to exit
To examine the state of signal values.
$finish terminates the simulation.
The syntax for the two directives is given as

Syntax
$stop;
$finish;

Time
Verilog simulations executed with respect to simulation time
Uses built in variable
Value stored in special register data type

Time variable declared using keyword time data type


Value of time variable can be retrieved
Using system function $time
Returns the current time
Syntax is given as,

Syntax
$time

Can be included in a $display or $monitor statement as

Syntax
$display ($time, ["formatString"], variableList);
$monitor ($time, ["formatString"], variableList);

// declare variable to hold current time


time simTime;
initial
begin
simTime = $time;
end
- 48 of 63 -
Simulated Time
Important to note
Simulated time is simulation of
Actual time required for design to run when implemented
Although value in simulation
Has direct relation to physical (in fabricated system)
Is not measured in seconds
Implemented as unitless integer
Common to map or interpret units as nanoseconds

When modeling design


Must think in terms of simulation time
Implication
Several Verilog statements may be executed
Without $time advancing

Sequence
Important to distinguish
Sequence and $time
Consider following code fragment

module SimTime0;

integer a,b;

initial
begin
a = 1;
$display("a is %d", a, $time);
end

initial
begin
b = 2;
$display("b is %d", b, $time);
end
endmodule

Assignments to both variables


Will occur at simulation time 0

- 49 of 63 -
Time Control - #
We used # symbol when modeling prop delay through part
Can also utilize to control when statements executed
Modifying above example
module SimTime1;

Code fragment will evaluate b prior to a integer a,b;


by one $time unit initial
begin
We have forced the unambiguous #4
evaluation order a = 1;
$display("a is %d at $time = %d", a, $time);
end
Event Control - @ initial
begin
We can utilize event specified by @ #3
symbol b = 2;
$display("b is %d at $time = %d ", b, $time);
To control when statements end
endmodule
executed
Examine two cases
Blocking
Non-blocking
Modifying above code fragment
To utilize blocking assignment
Will generate following output
a is 1 at $time = 5
b is 3 at $time = 15
c is 6 at $time = 25
d is 9 at $time = 35

If the assignment type in code fragment modified


To utilize non-blocking assignment
For current implementation
Initial block containing all assignments
Execute one time
All assignments to a..d respectively
Evaluated at $time == 0
Will obtain following output
a is x at $time = 0
b is x at $time = 0
c is x at $time = 0
d is x at $time = 0
- 50 of 63 -
module SimTime2;
integer a,b, c, d;
integer i;
reg sysClk;
parameter delay = 5;

initial
begin
sysClk = 0;
i = 0;
end

always
begin
#delay sysClk = ~sysClk;
i = i + 1;
end

// blocking assignment
initial
begin
a = @(posedge sysClk) i+1;
$display("a is %d at $time = %d", a, $time);

b = @(posedge sysClk) i+2;


$display("b is %d at $time = %d", b, $time);

c = @(posedge sysClk) i+3;


$display("c is %d at $time = %d", c, $time);

d = @(posedge sysClk) i+4;


$display("d is %d at $time = %d", d, $time);

#(40*sysClk)
$stop;
$finish;
end

endmodule

Test Module
Lets now move on to the tester or test module
This is most critical element in test process

Test module will have


Initialization sequence
To place UUT into known state
If start test from unknown state
Cannot make any statement about its behaviour

- 51 of 63 -
A set of inputs and a set of outputs
Inputs to the test module
Will be the outputs of the UUT
Will model the measurement equipment
Outputs from the test module
Will be the inputs of the UUT
These will model the stimulus equipment
Set of test vectors
These will be outputs of test module
Will be
Individual vectors
Sets of vectors
Provide known signals or patterns into UUT
Set of known responses
Will be outputs of UUT
Known responses to applied stimuli

Combinational Logic A First Look


The tester module for the NandNor combinational logic
Given in following code fragment
Opening lines of the test module
Identify the sets of inputs and outputs
These signals will
Come from the UUT
Send stimulus vector to the UUT
Following declaration of inputs and outputs
Find definition of reg type

- 52 of 63 -
module Tester (X, Y, XnandYin, XnorYin);
input XnandYin, XnorYin;
output X, Y;

reg X, Y;
parameter stimDelay = 10;

initial // set initial conditions


begin
x = 0; y = 0;
end

initial // Stimulus
begin
X = 1; Y = 1;
#stimDelay X = 0;
#stimDelay Y = 0;
#stimDelay X = 1;
end

initial
begin // Response
display("\t Time, \t \tX, \t Y, \t XnandYin, \t XnorYin");
monitor($time, "\t \t %b, \t %b, \t %b, \t \t%b", X, Y, XnandYin, XnorYin);
end
endmodule

There are two signal types in test bench


Used to drive and monitor signals
During the test of the UUT

These two types of signals are reg and wire types


The reg data type holds a value
Until a new value is driven onto it
In an initial or always block.
The reg type
Can only be assigned a value in an always or initial block
Is used to apply stimulus to the inputs of UUT

The wire data type is a passive data type


Holds value driven on it by
Port, assign statement or reg type
Wires can not be assigned values
Inside always and initial blocks
Wires not used in this design

- 53 of 63 -
Following reg declaration
Parameter stimDelay specifies
Delay between the applications of successive test vectors
Initial block declared next
Initial blocks start executing sequentially at simulation time 0
Starting with the first line between begin end pair
Each line executes from top to bottom
Until a delay is reached
When / if a delay is reached
Execution of this block waits
Until the delay time has passed and then picks up execution again.
Each initial and always block executes concurrently
So if a block is stalled
Other blocks in the design would execute
If always block included
An always block does not continuously execute
Instead only executes on change in items in the sensitivity list
For example posedge clock or negedge reset
Recall events discussed earlier
Means when there is a
low to high on the clock signal or
high to low on reset
always block will execute.

Next test vectors


Defined and appear as successive statements
Four different combinations of X and Y
Applied to the circuit input
Delay is specified between each stimulus application

Design of the NandNor circuit assumes ideal parts


Had the logic gates included a delay
The stimDelay between the applications of successive vectors
Would have provided time for the signal to propagate
Through the logic block.
Initialization and test vectors
- 54 of 63 -
Written as statements within initial blocks
Thus the test suite is applied one time during the simulation

The circuit output in response to the set of test vectors


Presented using the $display and $monitor system tasks

$display is used to print to a line and enter a carriage return at the end
Variables can also be added to the display
Format for the variables can be
Binary using %b
Hex using %h
Decimal using %d
Another common element used in $display is $time
which prints the current simulation time

To monitor specific variables or signals in a simulation


Every time one of the signals changes value
A $monitor can be used

Only one $monitor can be active at a time in a simulation


But it can prove to be a valuable debugging tool

Sequential Logic A First Look


Tester for the behavioral sequential two-bit binary counter module
Follows the same pattern with several additions
Presented in the code module in following figure
Tester designed to
Reset system
Apply 16 clock pulses to UUT

- 55 of 63 -
// Test module for two bit binary up counter
module tester(clr, clk, qA, qB);
input qA, qB;
output clr, clk;

reg clk, clr;

parameter stimDelay = 15;


parameter clkDelay = 5;

initial
begin
clk = 0;
clr = 0;
#stimDelay clr = ~clr;

repeat(16)
begin
#clkDelay clk = ~clk;
end
end

initial
begin
$display("\tTime, \t\tqA, \tqB, \tclr, \tclk");
$monitor($time,"\t\t%b, \t%b, \t%b, \t%b", qA, qB, clr, clk);
end

endmodule

Clocks and Resets


Synchronous sequential circuit will need
Strobe, enable, or clock in order to operate
As was seen in previous code fragment
Specific number of clock pulses supplied to UUT
Generally test does not have such restrictions

Good designs also include a reset or clear signal


To establish the initial state of the circuit
Typically these signals are supplied
By the tester with a block of code such as
Code fragment in accompanying figure reg clk, clr;

parameter stimDelay = 15;


parameter clkDelay = 5;

initial
begin
clk = 0;
clr = 0;
#stimDelay clr = ~clr;

always
#halfPeriod clk = ~clk;
end
- 56 of 63 -
The Test Bench
Now bring everything together with test bench
In the test bench we instantiate
One copy of the UUT
Here will be NandNor gate,

One copy of the Tester


These are the stimulus and monitoring instruments
Finally, we connect them together using wires
As illustrated in the code fragment in following figure

module MyTest bench;


wire XnandY, XnorY, X, Y;
NandNor aNandNor (XnandY, XnorY, X, Y);
Tester aTester (X, Y, XnandY, XnorY);
endmodule

Performing the Simulation


If the simulation is now run
Test vectors are successively applied to the input of the UUT
As the simulation executes
$monitor system task will display
State of the input and output signals
System time at which the samples were taken
These appear in following figure

Time, X, Y, XnandYin, XnorYin


0 1, 1, 0, 0
10 0, 1, 1, 0
20 0, 0, 1, 1
30 1, 0, 1, 0

If the behavioural results are satisfactory


Can move on to real work of confirming the design
We do this by utilizing dataflow or structural models
Incorporate real world affects and issues
Coding Style
9 Begin with some key high-level points
- 57 of 63 -
9 Move to examining good coding practices
9 Defining and examining synthesizable Verilog

High Level Points


Fundamental points
Make sure that your code is
Readable
Easy to modify
Reusable
Well documented
Good coding style helps to achieve better results
9 Modeling
9 Simulation
9 Synthesis

Not all Verilog constructs can be synthesized


Only a subset can be synthesized
Code containing only this subset can be synthesized

Good Coding Practices


Naming Restrictions
Identifiers
Give an object a name to allow later reference
Identifier may contain
Alphabetic characters
Numeric characters
Underscore
Dollar sign

Alphanumeric name followed by -numeric sometimes not allowed


myName-0

Must begin with alphabetic character or underscore


Can be up to 1024 characters in length

- 58 of 63 -
Naming Conventions and Styles
Several common formats for writing identifier name
addressBuss
address-buss
address_buss

All are legal choose one and stay with it


Dont mix formats within a program

Searching common operation when designing or debugging program


Searching for identifiers such as
i1, i2, i3 in large program
ModuleThatComputesTheSumofTwoNumbersandOutputsanInteger
Challenging at best

Use meaningful names


i1, i2, i3 valid identifier names but meaningless convey no information
Want code to be self-documenting
Conventions
Use uppercase letters for all
Constants

Use leading uppercase


User defined modules

Use leading lowercase letters for all


9 Signal names
9 Port names
9 Device names

Convey active state of signal in identifier name


Active low
nReset
reset_n
Active high
reset

- 59 of 63 -
Comments
Two forms of comment
// single line comment
Can appear as starting character on each line of block of commented text
/* */ multiple line comment
Can be used to mark single line comment
Comments should be
Meaningful informative suggestive of their intended purpose
Dont state the obvious
Vertically align left hand sides of all comments

Example

Bad
parameter halfPeriod = 100; // set halfPeriod to 100
Good
parameter halfPeriod = 100; // set halfPeriod to minimum legal value

Bad
parameter fullPeriod = 200; // set fullPeriod maximum legal value
parameter halfPeriod = 100; // set halfPeriod to minimum legal value
Good
parameter fullPeriod = 200; // set fullPeriod maximum legal value
parameter halfPeriod = 100; // set halfPeriod to minimum legal value

Formatting Conventions and Styles


The following are recommended formatting preferences
Goal is to enhance readability of code

Preferred - place each part of begin-end pairs on a line by itself


Vertically left align begin and end
Indent and align the body of compound statements from the opening and
closing delimiters
Declare each variable on a separate line (with a trailing comment)
Place a blank line before a declaration that follows executable code.
Place spaces on either side of a binary operator
No more than one statement per line
Maximum line length of 100 characters

- 60 of 63 -
Declarations, Definitions, and Modules.
Constants
Declare all parameter constants at the top of the module written in all upper case
letters.
Example
parameter HALFPERIOD = 100;
Modules
The first module should be the test bench or the top-level module
Followed by the remaining modules

Each module including the top-level


Should have a header listing
Name
Inputs
Outputs
Description
Author(s)
Date written
Date and description of each revision

Block Comments at Start of Files

//-----------------------------------------------------------
// File name:
// MyFile
//
// Description:
// Implements high-speed SerialIO system.
// Provides coms link between data collection system and
// remote peripheral devices.
// Data stream sent with Manchester Phase Encoded
Clock
//
// Author:
// Iman Engineer
//
//

- 61 of 63 -
Block Comments at the Start of modules

//-----------------------------------------------------------
// Module name:
// MyModule
//
// Description:
// Module implemented as part of high-speed SerialIO system.
// Counts number of characters transmitted
// Computes running parity
// Transmits parity and EOM
//
// Author:
// Youran Engineer
//
//-----------------------------------------------------------

Block Statements
Coding convention for all block statements shall be either of the following:

if( expression ) begin


statement1;
statement2;

if( expression ) begin


statement1a;
statement 2a;
end

end

else begin
statement3;
statement4;
end
end

or

- 62 of 63 -
Note:
Indentation of statements
Relative to "if" and "else" for each if-else statement

if( expression )
begin
statement1;
statement2;

if( expression )
begin
statement1a;
statement 2a;
end
end

else
begin
statement3;
statement4;
end

Choose one style on the other dont mix styles

- 63 of 63 -