You are on page 1of 183

dce

2006

Introduction to Verilog HDL


Dr. Anh-Vu Dinh-Duc http://www.cse.hcmut.edu.vn/~anhvu

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

dce

2007

Remember: to design is to represent


How do we represent digital designs?
You can read it again later Someone else can read and understand it It can be simulated and verified Even software people may read it! It can be synthesized into specific gates It can be built and shipped and make money

Components
Logic symbol, truth table Storage symbol, timing diagram

Connections
Schematics

Human readable or machine readable ???


Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 3

dce

2007

Netlist
A key data structure (or representation) in the design process is the netlist:
Network List
Alternative format: n1 g1.in1 n2 g1.in2 n3 g2.in1 n4 g2.in2 n5 g1.out g3.in1 n6 g2.out g3.in2 n7 g3.out g1 "and" g2 "and" g3 "or"

A netlist lists components and connects them with nodes:


Ex:
n1 n2 n3 n4

g1 g2

n5

g3
n6

n7

g1 "and" n1 n2 n5 g2 "and" n3 n4 n6 g3 "or" n5 n6 n7

Netlist is needed for simulation and implementation Could be at the transistor level, gate level, ... Could be hierarchical or flat How do we generate a netlist?
2007, Dr. Dinh Duc Anh Vu 4

Introduction to Verilog HDL

dce

2007

Digital Design Flow


Design Entry High-level Analysis
Design Specification Design Partition Design Entry: Verilog Behavioral Modeling Simulation/Functional Verification Design Integration and Verification Presynthesis Sign-Off Synthesize and Map Gate-Level Netlist Postsynthesis Design Validation Postsynthesis Timing Verification Test Generation and Fault Simulation Cell Placement, Scan Chain and Clock Tree Insertion, Cell Routing Verify Physical and Electrical Design Rules Extract Parasitic Design Sign-Off

Technology Mapping Low-level Analysis


Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

dce

2007

Digital Design Flow


Design Entry High-level Analysis Circuit is described and represented:
Graphically (Schematics) Textually (HDL)

Result of circuit specification (and compilation) is a netlist of:


generic primitives - logic gates, flip-flops, or technology specific primitives LUTs/CLBs, transistors, discrete gates, or higher level library elements adders, ALUs, register files, decoders, etc.

Technology Mapping Low-level Analysis


Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

dce

2007

Design Flow
Design Entry High-level Analysis High-level Analysis is used to verify
correct function rough
timing power cost

Common tools used are: Technology Mapping Low-level Analysis


Introduction to Verilog HDL

simulator - check functional correctness, and static timing analyzer


estimates circuit delays based on timing model and delay parameters for library elements (or primitives)

2007, Dr. Dinh Duc Anh Vu

dce

2007

Design Flow
Design Entry High-level Analysis Technology Mapping
Converts netlist to implementation technology dependent details
Expands library elements, performs:
partitioning, placement, routing

Low-level Analysis
Simulation and Analysis Tools perform low-level checks with:

Technology Mapping Low-level Analysis


Introduction to Verilog HDL

accurate timing models, wire delay

For FPGAs this step could also use the actual device

2007, Dr. Dinh Duc Anh Vu

dce

2007

Design Flow
Design Entry High-level Analysis

Netlist:
used between and internally for all steps

Technology Mapping Low-level Analysis


Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 9

dce

2007

Design Entry
Schematic entry/editing used to be the standard method in industry Schematics are intuitive. They match our use of gate-level or block diagrams. Somewhat physical. They imply a physical implementation. Require a special tool (editor). Unless hierarchy is carefully designed, schematics can be confusing and difficult to follow.

Hardware Description Languages (HDLs) are the new standard


except for PC board design, where schematics are still used.

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

10

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

11

dce

2007

What is a HDL?
Textual representation of a digital logic design
Can represent specific gates, like a netlist, or more abstract logic

HDLs are not programming languages


No, really. Even if they look like it, they are not. For many people, a difficult conceptual leap

Similar development chain


Compiler: source code assembly code binary machine code Synthesis tool: HDL source gate-level specification hardware
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 12

dce

2007

What is a HDL?
Basic Idea
Language constructs describe circuits with two basic forms:
Structural descriptions similar to hierarchical netlist Behavioral descriptions use higher-level constructs (similar to conventional programming) Structural example: Decoder (output x0,x1,x2,x3; inputs a,b) { wire abar, bbar; inv (bbar, b); inv (abar, a); nand (x0, abar, bbar); nand (x1, abar, b); nand (x2, a, bbar); nand (x3, a, b); } Behavioral example: Decoder (output x0,x1,x2,x3; inputs a,b) { case [a b] 00: [x0 x1 x2 x3] = 0x0; 01: [x0 x1 x2 x3] = 0x2; 10: [x0 x1 x2 x3] = 0x4; 11: [x0 x1 x2 x3] = 0x8; endcase; } 2007, Dr. Dinh Duc Anh Vu

Originally designed to help in abstraction and simulation


Now logic synthesis tools exist to automatically convert from behavioral descriptions to gate netlist. Greatly improves designer productivity However, this may lead you to falsely believe that hardware design can be reduced to writing programs!

Introduction to Verilog HDL

13

dce

2007

Why an HDL is not a Programming Language


In a program, we start at the beginning (e.g. main), and we proceed sequentially through the code as directed The program represents an algorithm, a step-by-step sequence of actions to solve some problem
for (i=0; i<10; i=i+1) { if (newPattern==oldPattern[i]) match=i; }

Hardware is all active at once; there is no starting point

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

14

dce

2007

Pitfalls of trying to program in Verilog


If you program sequentially, the synthesizer may add a lot of hardware to try to do what you say
In last example, need a priority encoder

If you program in parallel (multiple always blocks), you can get non-deterministic execution
Which always happens first?

You create lots of state that you didnt intend


if (x == 1) out = 0; if (y == 1) out = 1; // else out retains previous state? R-S latch!

You dont realize how much hardware youre specifying


x = x + 1 can be a LOT of hardware

Slight changes may suddenly make your code blow up


A chip that previously fit suddenly is too large or slow

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

15

dce

2007

Two Roles of HDL and Related Tools


#1: Specifying digital logic
Specify the logic that appears in final design Either
Translated automatically (called synthesis) or Optimized manually (automatically checked for equivalence)

#2: Simulating and testing a design


High-speed simulation is crucial for large designs Many HDL interpreters optimized for speed Testbench: code to test design, but not part of final design
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 16

dce

2007

HDL Design Methodology


Structure and Function (Behavior) of a Design

HDL Specification

Simulation
Verification: Design Behave as Required? Functional: I/O Behavior Register-Level (Architectural) Logic-Level (Gates) Transistor-Level (Electrical) Timing: Waveform Behavior

Synthesis
Generation: Map Specification to Implementation

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

17

dce

2007

Structural vs. Behavioral HDL Constructs


Structural constructs specify actual hardware structures
Low-level, direct correspondence to hardware
Primitive gates (e.g., and, or, not) Hierarchical structures via modules

Analogous to programming software in assembly

Behavioral constructs specify an operation on bits


High-level, more abstract
Specified via equations, e.g., out = (a & b) | c

Not all behavioral constructs are synthesizable


Weve already talked about the pitfalls of trying to program But even some combinational logic wont synthesize well out = a % b // modulo operation what does this synthesize to? We will not use: + - * / % > >= < <= >> <<

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

18

dce

2007

Synthesis vs. Simulation


HDLs have features for both synthesis and simulation
E.g., simulation-only operations for error messages, reading files Obviously, these can be simulated, but not synthesized into circuits Also has constructs such as for-loops, while-loops, etc.
These are either un-synthesizable or (worse) synthesize poorly

You need procedural code for testbench and only for testbench

Trends: a moving target


Good: better synthesis tools for higher-level constructs Bad: harder than ever to know what is synthesizable or not

Important distinction: What is a higher-level construct and what is procedural code?

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

19

dce

2007

HDL Design Methodology


HDL for Specification

HDL for Simulation

HDL for Synthesis

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

20

dce

2007

Why use an HDL?


Easy to write and edit Compact Dont have to follow a maze of lines Easy to analyze with various tools

Why not to use an HDL


You still need to visualize the flow of logic A schematic can be a work of art
But often isnt!
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 21

dce

2007

Quick History of HDLs


ISP (circa 1977) - research project at CMU
Simulation, but no synthesis

Abel (circa 1983) - developed by Data-I/O


Targeted to programmable logic devices Not good for much more than state machines

Verilog (circa 1985) - developed by Gateway (now Cadence)


Specification became open in 1985 Similar to Pascal and C programming language, originally developed for simulation Fairly efficient and easy to write 80s Berkeley develops synthesis tools IEEE standard
Verilog standardized (Verilog-1995 standard) Continued evolution (Verilog-2001 standard)

VHDL (circa 1987) - DoD sponsored standard


Based on VHSIC developed by DARPA Similar to Ada (emphasis on re-use and maintainability) Simulation semantics visible Very general but verbose IEEE standard
VHDL standardized (87 and 93)

Strict syntax
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 22

dce

2007

And the answer is


In general, digital logic is captured in an HDL For government / aerospace work, its VHDL For all else, its Verilog (This is, of course, a generalization)

Verilog is not perfect! But then, neither is the X86 instruction set. And its nowhere near that bad. In fact, its pretty good
If you know what to watch out for.
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 23

dce

2007

So, about Verilog HDL


Verilog is a (surprisingly) big language
Lots of features for synthesis and simulation of hardware Can represent low-level features, e.g. individual transistors Can act like a programming language, with for loops etc.

Simulation tools typically accept full set of Verilog language constructs


Some language constructs and their use in a Verilog description make simulation efficient and are ignored by synthesis tools

Synthesis tools typically accept only a subset of the full Verilog language constructs Were going to learn a focused subset of Verilog
We will use it at a level appropriate Focus on synthesizable constructs Focus on avoiding subtle synthesis errors Initially restrict some features just because they arent necessary Rule: if you havent seen it approved, you cant use it
2007, Dr. Dinh Duc Anh Vu 24

Introduction to Verilog HDL

dce

2007

References

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

25

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

26

dce

2007

Verilog HDL A Tutorial


The module concept
Basic design unit
Describes the communicating ports for external interfacing with other modules Describes the functionality or structure of a design

Module declaration
module module_name (port_list); Declarations: reg, wire, parameter, input, output, inout, function, task, Statements: Initial statement Always statement Module instantiation Gate instantiation UDP instantiation Continuous assignment endmodule

Declarations and statements can be interspersed within a module


A declaration must appear before its use For clarity and readability, it is best to put all declarations before any statements

Modules are:
Declared (defined) Instantiated

Modules declarations cannot be nested


Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 27

dce

2007

Three Module Components


New style (Verilog 2001)
module full_adder (input A, B, CI; output S, CO); module full_adder (A, B, CI, S, CO); input A, B, CI ; output S, CO ; wire N1, N2, N3; HA1 (A, B, N1, N2), HA2 (N1, CI, S, N3); P1 (CO, N3, N2);

Interface specification

Internal wires, also known as nets or signals

Declaration

half_adder or endmodule

Implementation
primitive and module instantiations

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

28

dce

2007

Module Declaration
Annotated example

Identifiers - must not be keywords! Type: defined by keywords Vector: e. g., A[1:0], A[0:1], D[3:0], and D[0:3] input Range is MSB to LSB output Can refer to partial ranges - D[2:1] inout (bi-directional)

/* module_keyword module_identifier (list of ports) */ module C_2_4_decoder_with_enable (A, E_n, D) ; input [1:0] A ; // input_declaration input E_n ; // input_declaration First example of signals output [3:0] D ; // output_declaration assign D = {4{~E_n}} & ((A == 2'b00) ? (A == 2'b01) ? (A == 2'b10) ? Scalar: e. g., E_n (A == 2'b11) ? 4'bxxxx) ; // endmodule
Introduction to Verilog HDL

4'b0001 : 4'b0010 : 4'b0100 : 4'b1000 : continuous_assign


2007, Dr. Dinh Duc Anh Vu 29

dce

2007

Module Instantiation
Example
module C_4_16_decoder_with_enable (A, E_n, D) ; input [3:0] A ; input E_n ; output [15:0] D ; wire [3:0] S; wire [3:0] S_n; C_2_4_decoder_with_enable not N0 (S_n, S); C_2_4_decoder_with_enable C_2_4_decoder_with_enable C_2_4_decoder_with_enable C_2_4_decoder_with_enable endmodule DE (A[3:2], E_n, S); D0 D1 D2 D3 (A[1:0], (A[1:0], (A[1:0], (A[1:0], S_n[0], S_n[1], S_n[2], S_n[3], D[3:0]); D[7:4]); D[11:8]); D[15:12]);

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

30

dce

2007

Module Instantiation
Hierarchy
Build up more complex modules using simpler modules

More Examples
Single module instantiation for five module instances
C_2_4_decoder_with_enable DE D0 D1 D2 D3 (A[3:2], (A[1:0], (A[1:0], (A[1:0], (A[1:0], E_n, S_n[0], S_n[1], S_n[2], S_n[3], S), D[3:0]), D[7:4]), D[11:8]), D[15:12]);

Named_port connection
C_2_4_decoder_with_enable DE (.E_n (E_n), .A (A[3:2]) .D (S)); // Note: order in list no longer important (E_n and A interchanged). // (but it is still poor practice to mix them up)
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 31

dce

2007

Module Description
Four styles to describe a design
Structural style
Instantiation of primitives and modules List of components and how they are connected
Explicit structure of the circuit

Just like schematics, but using text


A netlist

Tedious to write, hard to decode Essential without integrated design tools

Behavioral style
Procedural assignments Describe what a component does, not how it does it
Program describes input/output behavior of circuit

Synthesized into a circuit that has this behavior Result is only as good as the tools

RTL/Dataflow Verilog
Continuous assignments

Any mixed of above


Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 32

dce

2007

Delay
All delays are specified in terms of time units
assign #2 sum = A ^ B; 2 time units

A time unit is associated with the physical time by `timescale compiler directive
This directive is specified before a module declaration
`timescale 1ns / 100ps Time unit Time precision

If no compiler directive is specified, it depends on the Verilog simulator to default to a certain time unit (not specified by the IEEE standard)
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 33

dce

2007

Dataflow Style
Continuous assignment
assign [delay] LHS_net = RHS_expression;
`timescale 1ns/1ns module Decoder2x4 (A, B, EN, Z); input A, B, EN; output [0:3] Z; wire Abar, Bbar; assign #1 assign #1 assign #2 assign #2 assign #2 assign #2 endmodule Abar Bbar Z[0] Z[0] Z[0] Z[0] = = = = = = ~A; ~B; ~(Abar & Bbar & EN); ~(Abar & B & EN); ~(A & Bbar & EN); ~(A & B & EN);

V0

Abar

N0 N1

Z[0] Z[1] Z[2] Z[3]

B EN

V1

Bbar

N2 N3

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

34

dce

2007

Decoder2x4 Simulation Result


V0 Abar N0 N1 Bbar N2 N3 Z[0] Z[1] Z[2] Z[3]
`timescale 1ns/1ns module Decoder2x4 (A, B, EN, Z); input A, B, EN; output [0:3] Z; wire Abar, Bbar; assign #1 assign #1 assign #2 assign #2 assign #2 assign #2 endmodule Abar Bbar Z[0] Z[0] Z[0] Z[0] = = = = = = ~A; ~B; ~(Abar & Bbar & EN); ~(Abar & B & EN); ~(A & Bbar & EN); ~(A & B & EN);

B EN

V1

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

35

dce

2007

Dataflow Style Full Adder


module fa_rtl (A, B, Cin, Sum, Cout) ; input A, B, Cin; output Sum, Cout; assign Sum = A ^ B ^ Cin; assign Cout = A & B | A & Cin | B & Cin; endmodule

Cin A B

X1

X2

Sum

A1 A2 A3
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 36

O1

Cout

dce

2007

Behavioral Style
Procedural construct
initial statement: executes only once always statement: always executes in a loop (repeatedly)

Only a register data type can be assigned a value in these statements


Register data type retains its value until a new value is assigned All initial and always statements begin execution at time 0 concurrently module input output reg fa_bhv (A, B, Cin, Sum, Cout); A, B, Cin; Sum, Cout; Sum, Cout;

Register data type is required to hold values between events

Sequential block: consists of procedural assigments

always @(A or B or CI) begin Sum = A ^ B ^ Cin; Cout = A & B | A & Cin | B & Cin; end endmodule
2007, Dr. Dinh Duc Anh Vu 37

Introduction to Verilog HDL

dce

2007

Behavioral Style Procedural Assignment


A procedural assignment may optionally have a delay
Inter-statement delay: this is the delay by which a statements execution is delayed Intra-statement delay: this is the delay between computing the value of the RHS expression and its assignment to the LHS If no delays are specified, zero delay is the default
Assignment occurs instantaneously Intra-statement delay
Sum = #3 A ^ B ^ Cin; #4 Cout = A & B | A & Cin | B & Cin;

Inter-statement delay
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 38

dce

2007

Behavioral Style initial Statement


`timescale 1ns/1ns module Test (Pop, Pid); output Pop, Pid; reg Pop, Pid; initial begin Pop Pid Pop Pid Pop Pid end endmodule

= = = = = =

0; 0; #5 #3 #6 #2

1; 1; 0; 0;

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

39

dce

2007

Structural Style
Structure can be described using
Built-in gate primitives (gate-level) Switch-level primitives (transistor-level) User-defined primitives (gate-level) Module instances (to create hierarchy)
module input output wire xor fa_str (A, B, Cin, Sum, Cout); A, B, Cin; Sum, Cout; S1, T1, T2, T3;

Cin A B

Interconnections are specified by using nets

X1

S1 T3

X2

Sum

A1 A2 A3

X1 (S1, A, B); X2 (Sum, S1, Cin); and

T2 T1

O1

Cout
or

A1 (T3, A, B); A2 (T2, B, Cin); A3 (T1, A, Cin); O1 (Cout, T1, T2, T3); endmodule
2007, Dr. Dinh Duc Anh Vu 40

Introduction to Verilog HDL

dce

2007

Mixed-Design Style
A module can contain a mixture of gate instantiations, module instantiations, continuous assignments, always and initial statements
module input output reg wire fa_mix (A, B, Cin, Sum, Cout); A, B, Cin; Sum, Cout; Cout; S1;

gate instantiations

xor X1 (S1, A, B); always @(A or B or Cin) begin Cout = A & Cin | B & Cin | A & B; end assign Sum = S1 ^ Cin; endmodule

always statement

continuous statement

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

41

dce

2007

Modeling Style Another Example


module mux2to1 ( input S, A, B, output Out); wire S_, AnS_, BnS; not (S_, S); and (AnS_, A, S_); and (BnS, B, S); or (Out, AnS_, BnS); endmodule

Structural S A B Out

Behavioral
module mux2to1 ( input S, A, B, output Out); assign Out = (~S & A) | (S & B); endmodule
Introduction to Verilog HDL

Better
module mux2to1 ( input S, A, B, output Out); assign Out = S?B:A; endmodule
2007, Dr. Dinh Duc Anh Vu 42

dce

2007

Simulating a Design
Verilog is also used to model stimulus, control, storing responses and verification
Stimulus and control can be generated using initial statements Responses from the design under test can be saved as save on change or as strobed data Verification can be performed by automatically comparing with expected responses by writing appropriate statements in an initial statement

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

43

dce

2007

Simulating a Design
`timescale 1ns/1ns module Top; reg PA, PB, PCi; wire PCo, PSum; fa_rtl F1 (A, B, Cin, Sum, Cout); PA, PB, PCin = 000 => PCo, PSum = 00 PA, PB, PCin = 001 => PCo, PSum = 01 PA, PB, PCin = 010 => PCo, PSum = 01 PA, PB, PCin = 011 => PCo, PSum = 10 PA, PB, PCin = 100 => PCo, PSum = 01 PA, PB, PCin = 101 => PCo, PSum = 10 PA, PB, PCin = 110 => PCo, PSum = 10 PA, PB, PCin = 111 => PCo, PSum = 11

initial begin ONLY_ONCE reg [3:0] Pal; for (Pal=0; Pal<8; Pal=Pal+1) begin {Pa, PB, PCi} = Pal; #5 $display (PA, PB, PCin = %b%b%b , PA, PB, PCin, => PCo, PSum = %b%b, PCo, PSum); end end endmodule
Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

44

dce

2007

Simulating a Design
`timescale 10ns/1ns module RS_FF (Q, Qb, R, S); output Q, Qb; input R, S; initial nand #1 (Q, R, Qb); begin nand #1 (Qb, S, Q); TR endmodule TS #5 module Test; #5 reg TS, TR; TR wire TQ, TQb; #5 TR RS_FF MUT (.Q(TQ), .S(TS), #5 .R(TR), .Qb(TQb)); #5 end

= 0; = 0; TS = TS = = 1; TS = = 0; TS = TR =

At time 0, TR=0, TS=0, TQ=x, TQb=x At time 10, TR=0, TS=0, TQ=1,TQb=1 At time 50, TR=0, TS=1, TQ=1,TQb=1 At time 60, TR=0, TS=1, TQ=1,TQb=0 At time 100, TR=1, TS=0, TQ=1,TQb=0 At time 110, TR=1, TS=0, TQ=1,TQb=0 At time 120, TR=1, TS=0, TQ=0,TQb=1 1; 0; 1; 0; 1;

initial $monitor (At time %t, , $time, TR=%b, TS=%b, TQ=%b, TQb=%b, TR, TS, TQ, TQb); endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 45

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

46

dce

2007

Verilog Language Elements


Identifiers Comments Format Systems tasks and functions Compiler directives Value set Data types Parameter
2007, Dr. Dinh Duc Anh Vu 47

Introduction to Verilog HDL

dce

2007

Identifiers
Different names must be used for different items within the same scope Identifier alphabet
Upper and lower case alphabetical Decimal digits Underscore (_) $

Maximum of 1024 characters in identifier First character not a digit Case-sensitivity


Verilog is case-sensitive Some simulators are case-insensitive Advice: Dont use case-sensitive feature! Keywords are lower case
2007, Dr. Dinh Duc Anh Vu 48

Introduction to Verilog HDL

dce

2007

Comments
Two form of comments:
All characters after // in a line are treated as a comment
// First form: ends at the end of this line

Multi-line comments begin with /* and end with */


/* * * * Second form: can extend across many lines */

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

49

dce

2007

Format
Free format within statement except for within quotes
Constructs may be written across multiple lines or on one line White space (newline, tabulation and space characters) have no significance Strings enclosed in double quotes and must be on a single line

initial begin top = 3b001; #2 top = 3b110; end

initial begin top = 3b001; #2 top = 3b110; end

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

50

dce

2007

System Tasks and Functions


Built-in system tasks or functions begin with $
A task can return zero or more values A function is like a task except that it can return only one value A function executes in zero time (no delays are allowed) while a task can have delays
$display (Hi, you have reached LT today); /* the $display system task displays the specified message * to output with a newline character */ $time // this system function returns the current simulation time
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 51

dce

2007

Compiler Directives
Compiler directives start with the ` (backquote) character A compiler directive when compiled remains in effect through the entire compilation process (which could span multiple files) until a different compiler directive specifies otherwise Complete list of standard compiler directives
`define, `undef `ifdef, `else, `endif `default_nettype `include `resetall `timescale `unconnected_drive, `nounconnected_drive `celldefine, `endcelldefine

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

52

dce

2007

`define and `undef


`define is used for text substitution Like #define and #undef in the C language
`define MAX_BUS_SIZE 32 reg [`MAX_BUS_SIZE-1:0] address_register;

`define WORD 16 wire [`WORD-1:0] bus; `undef WORD /* the definition of WORD is no longer available * after this `undef directive */
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 53

dce

2007

`ifdef, `else and `endif


Used for conditional compilation `else directive is optional with the `ifdef directive

`ifdef WINDOWS parameter WORD_SIZE = 16; `else parameter WORD_SIZE = 32; `endif

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

54

dce

2007

`default_nettype
Used to specify the net type for implicit net declarations (i.e. for nets that are not declared)
`default_nettype wand

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

55

dce

2007

`include
Like #include in the C language Used to include the contents of any file in-line
The file can be specified either with a relative path name or with a full path name
`include ../../primitives.v

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

56

dce

2007

`resetall
Resets all compiler directives to their default value
E.g. causes the default net type to be wire

`resetall

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

57

dce

2007

`timescale

`timescale 1ns/100ps Used to specify the time unit module andfunc (Z, A, B); and time precision output Z; `timescale time_unit/time_precision input A, B; time_unit and time_precision is and #(5.22, 6.17) A1 (Z, A, B); endmodule made up of values from 1, 10

and 100 and units from s, ms, us, ns, ps and fs

`timescale 1ns/100ps

The `timescale directive affects all delays in modules that follow this directive in a compilation until another `timescale or `resetall directive is found The directive appears outside of a module declaration What happens?
Introduction to Verilog HDL

`timescale 10ns/1ns module testbench; reg PutA, PutB; wire GetO; andfunc AF1 (GetO, PutA, PutB); initial begin PutA = 0; PutB = 0; #5.21 PutB = 1; #10.4 PutA = 1; end endmodule
2007, Dr. Dinh Duc Anh Vu 58

dce

2007

`unconnected_drive and `nounconnected_drive


Any unconnected input ports in module instantiations that appear between these two directives are either pulled up or pulled down
`unconnected_drive pull1 /* all unconnected input ports between these two directives * are pulled up (connected to 1) */ `nounconnected_drive

`unconnected_drive pull0 /* all unconnected input ports between these two directives * are pulled down (connected to 0) */ `nounconnected_drive
Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

59

dce

2007

`celldefine and `endcelldefine


Used to mark a module as a cell module
Typically encompass a module definition

Cell modules are used by some PLI routines


`celldefine module andfunc (Z, A, B); output Z; input A, B; and #(5.22, 6.17) A1 (Z, A, B); endmodule `endcelldefine

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

60

dce

2007

Value Set
Four basic values
0 Logical 0 or FALSE 1 Logical 1 or TRUE x, X Unknown logic value z, Z High impedance condition (? can be used as an alternative)

Three types of constants


Integer Real String

Underscore character (_) can be used for reading clarity


It can not be the first character
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 61

dce

2007

Integer
Simple decimal
A sequence of digits with an optional + (unary) or (unary) operator An integer value represents a signed number: negative number is represented in 2s complement form 32 (10000 in a 5-bit binary and 010000 in 6-bit binary) 15 (10001 in 5-bit binary and 110001 in a 6-bit binary)

Base format <size><base_format><number>


<size> - decimal specification of number of bits
default is unsized and machine-dependent, but at least 32 bits

<base format> - ' followed by arithmetic base of number


<d> <D> - decimal - default base if no <base_format> given <h> <H> - hexadecimal Always represents <o> <O> - octal an unsigned number <b> <B> - binary

<number> - value given in base of <base_format>


If first character of sized, binary number is 0, 1, the value is 0-filled up to size. If x or z, value is extended using x or z, respectively An x or z in a hexadecimal value represents 4 bit of x or z
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 62

dce

2007

Integers Example
6b010_111 8'b0110 3b1110 4'bx01 16'H3AB 24 5'O36 16'Hx 8'hz 4'd-4 8 'h 2A (2+3)'d10 gives 010111 gives 00000110 gives 110 gives xx01 gives 0000001110101011 gives 00011000 gives 11100 gives xxxxxxxxxxxxxxxx gives zzzzzzzz not legal: value cannot be negative spaces are not allowed not legal: size cannot be an expression

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

63

dce

2007

Reals
Decimal notation
2.0 5.678 0.1 2. // not legal: must have a digit on either side of decimal

Scientific notation
25_3.1e2 = 25310.0 5E-4 = 0.0005

Implicit conversion to integer is define by the language


Real numbers are converted to integers by rounding to the nearest integer 42.446 42 -16.62 -17 -25.5 -26

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

64

dce

2007

Strings
A sequence of characters within double quotes
May not split across lines Internal Error

No explicit data type Must be stored in reg whose size is 8*(number of characters)
reg [255:0] buffer; //stores 32 characters

The \ (backslash) character can be used to escape certain special characters


\n \t \\ \ \206 newline tab the \ character itself the character character with octal value 206
2007, Dr. Dinh Duc Anh Vu 65

Introduction to Verilog HDL

dce

2007

Data Types
Two groups of data types
Net type
A net type represents a physical connection between structural elements. Its value is determined from the value of its drivers such as a continuous assignment or a gate output. If no driver is connected to a net, the net defaults to a value of z.

Register type
A register type represents an abstract data storage element. Is NOT necessarily a register in the circuit It is assigned values only within an always statement or an initial statement, and its value is saved from one assignment to the next. A register type has a default value of x.

Properties of Both
Informally called signals May be either scalar (one bit) or vector (multiple bits)
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 66

dce

2007

Data Types Nets


wire connectivity only; no logical tri same as wire, but indicates will be 3-stated in hardware wand multiple drivers - wired and wor multiple drivers - wired or triand same as wand, but 3-state trior same as wor but 3-state supply0 Global net GND supply1 Global Net VCC (VDD) tri0, tri1, trireg
net_kind [msb:lsb] net1, net2, , netN;
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 67

dce

2007

Net Examples
wire x; wire x, y; wire [15:0] data, address; wire vectored [1:7] control; wire address = offset + index; wor interrupt_1, interrupt_2; tri [31:0] data_bus, operand_bus; Value implicitly assigned by connection to primitive or module output
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 68

dce

2007

wire and tri Nets


If multiple drivers drive a wire (or a tri) net, the effective value of the net is determined by using the following table
wire / tri 0 1 x z 0 0 x x 0 1 x 1 x 1 x x x x x z 0 1 x z

wire [3:2] cla, pla, sla; assign cla = pla & sla; assign cla = pla ^ sla;
Introduction to Verilog HDL

01x x1x 11z


2007, Dr. Dinh Duc Anh Vu 69

dce

2007

wor and trior Nets


If multiple drivers drive this net, the effective value of the net is determined by using the following table
wor / trior 0 1 x z 0 0 1 x 0 1 1 1 1 1 x x 1 x x z 0 1 x z

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

70

dce

2007

wand and triand Nets


If multiple drivers drive this net, the effective value of the net is determined by using the following table
wand / triand 0 1 x z 0 0 0 0 0 1 0 1 x 1 x 0 x x x z 0 1 x z

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

71

dce

2007

tri0 and tri1 Nets


These nets also model wired-logic nets (a net with more than one driver) If no driver is driving tri0/tri1 net, its value is 0/1 If multiple drivers drive this net, the effective value of the net is determined by using the following table
tri0 / tri1 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

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

72

dce

2007

Initial Value & Undeclared Nets


Initial value of a net
At tsim = 0, initial value is x

Undeclared Nets Default type


Not explicitly declared default to wire `default_nettype compiler directive can specify others except for supply0 and supply1

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

73

dce

2007

vectored and scalared Nets


These keyword are optional If a net is declared with vectored, then bit-selects and part-selects of this vector net are not allowed
The entire net has to be assigned

The default is scalared


wire vectored [3:1] GRB; // bit-select GRB[2] and part-select GRB[3:2] // are not allowed wor scalared [4:0] best; // same as // wor [4:0] best; // bit-select best[0] and part-select best[3:1] // are allowed
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 74

dce

2007

Data Types Registers


reg stores a logic value integer stores values which are not to be stored in hardware
Defaults to simulation computer register length or 32 bits whichever is larger No ranges or arrays supported May yield excess hardware if value needs to be stored in hardware; in such a case, use sized reg.

time stores time 64-bit unsigned real stores values as real number realtime stores time values as real numbers
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 75

dce

2007

reg Register
reg [msb:lsb] reg1, reg2, , regN;
Value in a register is always interpreted as an unsigned number
reg [1:4] comb; comb = -2; // comb has 14 (2s complement of 2) comb = 5; // comb has 5

A memory is an array of registers

reg [msb:lsb] memory1[upper1:lower1], memory2[upper2:lower2];


Arrays with more than two dimensions are not allowed A single reg declaration can be used to declare both registers and memories
reg [1:WORDSIZE] Ram[ADDSIZE-1:0], // Ram is a memory DataReg; // DataReg is a WORDSIZE-bit register
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 76

dce

2007

Register Assignment
A register may be assigned value only within: a procedural statement a user-defined sequential primitive a task, or a function. A reg object may never by assigned value by: a primitive gate output or a continuous assignment A memory cannot be assigned a value in one assignment, but a register can.
To assign to a memory: assign a value to each word of a memory individually reg [1:4] dig; // dig is a 4-bit register dig = 4b1101; // OK reg bog[1:4]; // bog is a memory of four 1-bit registers dig = 4b1101; // no OK
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 77

dce

2007

Register Assignment (contd)


Assign values to a memory by using the system tasks
$readmemb load binary values $readmemh load hexadecimal values
reg [1:4] RomB[7:1]; $readmemb(ram.patt, RomB); ram.patt 1101 1100 1000 0111 0000 1001 1010

RomB[7] RomB[6] RomB[5] RomB[4] RomB[3] RomB[2] RomB[1]

= = = = = = =

1101 1100 1000 0111 0000 1001 1010

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

78

dce

2007

Register Assignment (contd)


$readmemb(ram.patt, RomB, 5, 3); // only part of the memory is loaded // RomB[5] = 1101 // RomB[4] = 1100 // RomB[3] = 1000 $readmemb(ram.patt, RomB, 3); // start reading from address 3 and continues until 1 // RomB[3] = 1101 // RomB[2] = 1100 $readmemb(ram.patt, RomB); // RomB[1] = 1000 ram.patt @5 1101 @3 1100 @6 1000 @1 0111 @2 0000 @7 1001 @4 1010
Introduction to Verilog HDL

RomB[5] RomB[3] RomB[6] RomB[1] RomB[2] RomB[7] RomB[4]

= = = = = = =

1101 1100 1000 0111 0000 1001 1010


79

2007, Dr. Dinh Duc Anh Vu

dce

2007

integer Register
Example of integer declarations
integer A, B, C; // 3 integer registers integer Hist[3:6]; // an array of four integers

integer integer1, integer2, , integerN[msb:lsb];

An integer register holds signed quantities

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

80

dce

2007

integer Register (contd)


An integer cannot be accessed as a bit-vector
reg [31:0] Breg; integer Bint; ... // Bint[5] and Bint[15:0] are not allowed Breg = Bint; /* at this point, Breg[5] abd Breg[15:0] are allowed and * give the corresponding bit-values from the integer Bint */

Type conversion is automatic


No special functions are necessary
reg [3:0] Bcq; integer J; J = 6; // J has the value 32b000...00110 Bcq = J; // Bcq has the value 4b0110 Bcq = 4b0101; J = Bcq; // J has the value 32b000...00101 J = -6; // J has the value 32b111...11010 Bcq = J; // Bcq has the value 4b1010
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 81

dce

2007

time, real and realtime Register


time integer1, integer2, , integerN[msb:lsb]; real real_reg1, real_reg2, , real_regN; realtime realtime_reg1, realtime_reg2, , realtime_regN;
time CurrentTime; // holds one time value (at least 64 bits) time events[0:31]; // array of time values real Temperature; realtime CurrTime;

The default value of real registers is 0 No range (bit range or word range) is allowed for declaring a real register. When assigning values x and z to a real register, these values are treated as a 0
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 82

dce

2007

Parameter
Constant Used to specify delays and widths of variables Assigned a value only once
parameter param1 = const_exp1, param2 = const_exp2, paramN = const_expN; parameter LINELENGTH = 132, ALL_X_S = 16bx; parameter BIT = 1, BYTE = 8, PI = 3.14;

Note: a parameter value can also be changed at compile time by using a defparam statement (more details later)
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 83

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

84

dce

2007

Verilog Expression Operands


An operand can be one of the following
Constant Parameter Net Register Bit-select Part-select Memory element Function call

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

85

dce

2007

Operand Constant
Some examples
256 4b1011 hFBA 90.006 JAMES // // // // // unsigned decimal numbers sized integer constant unsized integer constant real constant string constant

An integer value in an expression is interpreted as either a signed or an unsigned number


Decimal integer: as signed number Based integer: as unsigned number 12 // is 01100 in 5-bit vector form (signed) -12 // is 10100 in 5-bit vector form (signed) 5b01100 // is decimal 12 (unsigned) 5b10100 // is decimal 20 (unsigned) 4d12 // is decimal 12 (unsigned) A negative value of an integer is treated differently for an integer with or without a base integer cone; cone = -44/4; // result is -11 cone = -6o54/4; // result is 1073741813

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

86

dce

2007

Operands (contd)
Net
Both scalar nets (1-bit) and vector nets (multi-bit) A value in a net is interpreted as an unsigned value wire [0:3] Prt; // Prt is a 4-bit vector net wire Bbq; // Bbq is a scalar net assign Prt = -3; // Prt has the bit-vector 1101 assigned

Register
Scalar and vector registers A value in an integer register is interpreted as a signed twos complement number A value in a reg register or a time register is interpreted as an unsigned number Value in real and realtime registers are interpreted as signed floating point values

integer TemA, TemB; reg [1:5] State; time Que[1:5]; TemA = -10; TemA = b1011; State = -10; State = b1011;
Introduction to Verilog HDL

// // // //

TemA = 10110 (2s complement of 10) TemA has the decimal value 11 State has the bit-vector 10110 (decimal 22) State has the bit-vector 01011 (decimal 11)
2007, Dr. Dinh Duc Anh Vu 87

dce

2007

Operands (contd)
Bit-select
If the select expression evaluates to an x or z or if it is out of bounds, the value of the bit-select is an x
State[1] && State[4] // register bit-select Prt[0] | Bbq // net bit-select State[x] // returns an x

Part-select
If either of the range index is out of bounds or evaluates to an x or an z, the part-select value is an x
State[1:4] // register part-select Prt[1:3] // net part-select State[1:8] // returns an x
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 88

dce

2007

Operands (contd)
Memory element
A memory selects one word of a memory No part-select or bit-select of a memory is allowed
reg [1:8] Ack, DRAM[0:63]; DRAM[60][2] DRAM[60][1:3] // not allowed // not allowed

Ack = DRAM[60]; // 60th element of memory Ack[2] // OK Ack[1:3] // OK

Function call
System function call (start with the $ character) or a userdefined function call
$time + SumOfEvents(A, B) // $time is a system function // SumOfEvents is a user-defined function
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 89

dce

2007

Verilog Expression Operators


Operators [] () ! ~ & | ~& ~| ^ ~^ or ^~ + {} {{}} * / % + Name Bit-select or part-select parenthesis logical negation negation reduction AND reduction OR reduction NAND reduction NOR reduction XOR reduction XNOR unary (sign) plus unary (sign) minus concatenation replication multiply divide modulus binary plus binary minus Logical Bit-wise Reduction Reduction Reduction Reduction Reduction Reduction Arithmetic Arithmetic Concatenation Replication arithmetic arithmetic arithmetic arithmetic arithmetic Functional Group Operators << >> > >= < <= == != === !== & ^ ^~ or ~^ | && || ?: Name shift left shift right greater than greater than or equal to less than less than or equal to logical equality logical inequality case equality case inequality bit-wise AND bit-wise XOR bit-wise XNOR bit-wise OR logical AND logical OR conditional Functional Group shift shift relational relational relational relational equality equality equality equality bit-wise bit-wise bit-wise bit-wise logical logical conditional

P R E C E D E N C E

Introduction to Verilog HDL

All operators associate left to right 90 2007, Dr. Dinh Duc Anh to except for the conditional operator (right Vu left)

dce

2007

Arithmetic Operators
If any bit of an operand in an arithmetic operation is an x or a z, the entire result is an x. Result size
Size of the largest operand or size of the LHS target (in case of an assignment)

Unsigned and signed


Unsigned value: a net, a reg register and an integer in base format notation Signed value: an integer register and an integer in decimal form b10x1 + b01111 = bxxxxx reg [0:5] reg [1:5] reg [1:8] integer Bar, Arc; Cfg, Crt; Adt; Tab;

assign Adt = (Bar + Arc) + (Crt + Cfg); Bar = -4bd12; Tab = -4d12; -4d12 / 4 -12 /4
Introduction to Verilog HDL

// // // //

Bar has the decimal value 52 (110100) Tab has the value -12 (110100) result is 1073741821 result is -3
2007, Dr. Dinh Duc Anh Vu 91

dce

2007

Relational Operators
Result of a relational operator is true (value 1) or false (value 0) If any bit in either of the operands is an x or a z, result is an x If operands is not of the same size, the smaller operand is zero-filled on the most significant bit side.
23 > 45 // result if false (value 0) 52 < 8hxFF // result is x b1000 >= b01110 // equivalent to b01000 >= 4b01110

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

92

dce

2007

Equality Operators
Logical equality (== and !=)
Values x and z have their usual meaning Result may be unknown

Case equality (=== and !==)


Values x and z are compared strictly as values Result can never be an unknown

If operands is not of the same size, the smaller operand is zero-filled on the most significant bit side.
Data = 4b11x0; Addr = 4b11x0; Data == Addr // result is unknown (value x) Data === Addr // result is true (value 1)
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 93

dce

2007

Logical Operators
For vector operands, a non-zero vector is treated as a 1. If a bit in any of the operands is an x, the result is also an x.

ABus = 4b0110; BBus = 4b0100; ABus || BBus // result is 1 ABus && BBus // result is also 1 !ABus // is same as !BBus // and result is 0

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

94

dce

2007

Bit-wise Operators
& (and) 0 1 x z 0 0 0 0 0 1 0 1 x x x 0 x x x z 0 x x x | (or) 0 1 x z 0 0 1 x x 1 1 1 1 1 x x 1 x x z x 1 x x

^ (xor) 0 1 x z

0 0 1 x x

1 1 0 x x

x x x x x

z x x x x 0 1 1 0

^~ (xnor) 0 1 x z x x z x

0 1 0 x x

1 0 1 x x

x x x x x

z x x x x

~ (not)
Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

95

dce

2007

Reduction Operators
The reduction operators operate on all bits of a single operand and produce a 1-bit result
& (reduction and): if any bit is 0, the result is 0, else if any bit is an x or a z, the result is an x, else the result is a 1. ~& (reduction nand): invert of & reduction operator. | (reduction or): if any bit is 1, the result is 1, else if any bit is an x or a z, the result is an x, else the result is a 0. ~| (reduction nand): invert of | reduction operator. ^ (reduction xor): if any bit is an x or a z, the result is an x, else if there are even number of 1s in the operand, the result is 0, else the result is a 1. ~^ (reduction xnor): invert of ^ reduction operator.
if (^MyReg === 1bx) $display (There is an unknown in the vector MyReg!);
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 96

dce

2007

Shift Operators
Shifts the left operand by the right operand number of times The vacated bits are filled with 0. If the right operand evaluates to an x or a z, the result of the shift operation is an z.
reg [0:7] Qreg; Qreg = 4b0111; Qreg >> 2 // is 8b0000_0001

A 2-to-4 decoder can be modeled using a shift operator


wire [0:3] DecoderOut = 4d1 << Address[0:1];

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

97

dce

2007

Conditional Operators
Cond_expr ? Expr1 : Expr2

If Cond_expr is an x or a z, the result is a bit-wise operation on Expr1 and Expr2 with the following logic
0 with 0 gives 0 1 with 1 give 1 Rest are x
always #5 Ctr = (Ctr != 25) ? (Ctr+1) : 5;

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

98

dce

2007

Concatenation/Replication Operators
Concatenation
{expr1, expr2, , exprN} Concatenation of unsized constant numbers is not allowed.
wire [7:0] Dbus; wire [11:0] Abus; assign Dbus[7:4] = {Dbus[0], Dbus[1], Dbus[2], Dbus[3]}; // assign lower four bits in reverse order to upper four bits assign Dbus = {Dbus[3:0], Dbus[7:4]}; // swap lower and upper four bits {Dbus, 5} // not allowed

Replication {repetition_number {expr1, expr2, , exprN}}


Abus = {3{4b1011}}; // 12b1011_1011_1011 Abus = {{4{Dbus[7]}}, Dbus}; // signed extension {3{1b1}} // is 111 {3{Ack}} // is same as {Ack, Ack, Ack}
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 99

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

100

dce

2007

Gate-level Modeling
The built-in Primitive Gates Multiple-input Gates Multiple-output Gates Tristate Gates Pull Gates MOS Switches Bidirectional Switches Gate Delays Array of Instances Implicit Nets Some examples
2007, Dr. Dinh Duc Anh Vu 101

Introduction to Verilog HDL

dce

2007

Built-in Primitive Gates


Gate Level
Multiple-input gates: and, nand, or, nor, xor, xnor Multiple-output gates: buf , not Tristate gates: bufif0, bufif1, notif0, notif1 Pull gates: pullup, pulldown

Switch Level
*mos
where * is n, p, c, rn, rp, rc;

*tran+
where * is (null), r where + (null), if0, if1 both * and + not (null)
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 102

dce

2007

Built-in Primitive Gates


No declaration; can only be instantiated All output ports appear in list before any input ports
Restriction does not apply to modules

Optional drive strength, delay, name of instance


(Z, (Z, (X, /*Usually better debugging*/ or and N25 and #10 A, A, C, to B, C); // instance name B, X); // delay D, E); // delay provide instance name for

N30 (SET, Q1, AB, N5), N41 (N25, ABC, R1); and #10 N33(Z, A, B, X); // name + delay
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 103

dce

2007

Multiple-input Gates
and 0 1 x z 0 0 0 0 0 1 0 1 x x x 0 x x x z 0 x x x or 0 1 x z 0 0 1 x x 1 1 1 1 1 x x 1 x x z x 1 x x

xor 0 1 x z

0 0 1 x x

1 1 0 x x

x x x x x

z x x x x

A value z at an input is handled like an x The output of a multipleinput gate can never be a z

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

104

dce

2007

Multiple-output Gates
Output1 Output2 not output 0 1 1 0 x x z x

InputA

not

OutputN Output1 Output2

InputA

buf output

0 0

1 1

x x

z x

buf

OutputN

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

105

dce

2007

Tristate Gates
Tristate gates model three-state drivers
One output, one input and one control

tristate_gate [instance_name] (OutputA, InputB, ControlC); notif1


InputB ControlC Data OutputA notif1 0 1 x z Control 0 z z z z 0 1 0 x x 1 1 0 x x 1 z z z z x 1/z 0/z x x x 1/z 0/z x x z 1/z 0/z x x z 1/z 0/z x x

Output is at z if control is at 0 Else output is the invert of the input data Output is at z if control is at 1 Else output is the invert of the input data
2007, Dr. Dinh Duc Anh Vu 106

notif0
InputB ControlC OutputA

notif0 0 Data 1 x z

Control

Introduction to Verilog HDL

dce

2007

Tristate Gates
bufif1
notif1 OutputA Data 0 1 x z Control 0 z z z z 1 0 1 x x x 0/z 1/z x x z 0/z 1/z x x

InputB ControlC

Output is at z if control is at 0 Else data is transferred to output

bufif0
InputB ControlC OutputA

notif0 0 Data 1 x z

Control 0 0 1 x x 1 z z z z x 0/z 1/z x x z 0/z 1/z x x

Output is at z if control is at 1 Else data is transferred to output

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

107

dce

2007

Pull Gates
Have only one output with no input A pullup gate places a 1 on its output A pulldown gate places a 0 on its output
pull_gate [instance_name] (OutputA);

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

108

dce

2007

MOS Switches
Unidirectional switches One output, one input and one control input Data flow can be turned off by appropriately setting the control inputs

gate_type [instance_name] (OutputA, InputB, ControlC); (r)cmos [instance_name] (OutputA, InputB, NControl, PControl);
pmos switch InputB ControlC pmos rpmos 0 Data 1 x z Control 0 0 1 x z 1 z z z z x 0/z 1/z x z z 0/z 1/z x z Data nmos rnmos 0 1 x z OutputA nmos switch InputB ControlC InputB Control 0 z z z z 1 0 1 x z x 0/z 1/z x z z 0/z 1/z x z
2007, Dr. Dinh Duc Anh Vu 109

cmos switch PControl

OutputA

OutputA

NControl

Introduction to Verilog HDL

dce

2007

Bidirectional Switches
tran rtran tranif0 rtranif0 tranif1 rtranif1 Data flows both ways No propagation delay tranif0 rtranif0 tranif1 rtranif1 switches can be turned off by setting a control signal appropriately
gate_type [instance_name] (SignalA, SignalB, SignalC); For tranif0 and rtranif0, if ControlC is 1, the bidirectional data flow is disabled For tranif1 and rtranif1, if ControlC is 0, the bidirectional data flow is disabled

tran and rtran switches cannot be turned off


(r)tran [instance_name] (SignalA, SignalB);

The strength of the signal reduces when it passes through resistive switches
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 110

dce

2007

Gate Delays
Gate delay is the propagation delay from any gate input to the output
No gate delay, the default delay is zero

Gate delay comprised of up to three values


Rise delay Fall delay Turn-off delay The transition to x delay (To_x) cannot be explicitly specified, but is determined from the other values

Multiple-input gates (and, or) and multiple-output gates (not, buf) can have only up to 2 delays specified (since output never goes to z) gate_type [delay] [instance_name] (terminal_list);
Delay No delay 0 0 0 0 1 value (d) d d d d 2 values (d1, d2) d1 d2 min(d1, d2) 3 values (d1, d2, d3) d1 d2 d3
111

not N1 (Qb, Q); nor #2 N2 (o, i1, i2); and #(3, 5) (o, i1, i2, i3); notif1 #(2, 8, 6) (o, i1, i2);

Rise Fall To_x Turn-off

min(d1, d2) min(d1, d2, d3)

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

dce

2007

min:typ:max Delay Form


A delay for a gate can also be specified in a min:typ:max form
minimum:typical:maximum

The minimum, typical and maximum values must be constant expressions


nand #(2:3:4, 5:6:7) (out, in1, in2, in3);

The selection of which delay to use is usually made as an option during s simulation run
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 112

dce

2007

Array of Instances
A range specification can optionally be specified in a gate instantiation when repetitive instances are required
Can also be applied in a module instantiation

gate_type [delay] [instance_name] [leftbound:rightbound] (terminal_list);

Note that the instance name is not optional when specifying an array of instances
wire [3:0] Out, InA, InB; nand NInst [3:0] (Out, InA, InB); nand NInst3 NInst2 NInst1 NInst0
Introduction to Verilog HDL

(Out[3], (Out[2], (Out[1], (Out[0],

InA[3], InA[2], InA[1], InA[0],

InB[3]); InB[2]); InB[1]); InB[0]);


113

2007, Dr. Dinh Duc Anh Vu

dce

2007

Implicit Nets
Array of Instances Example
module input input output output wire add_array (A, B, CIN, S, COUT); [7:0] A, B; CIN; [7:0] S; COUT; [7:1] carry;

full_add FA[7:0] (A, B, {carry, CIN}, S, {COUT, carry}); // instantiates eight full_add modules endmodule

An undeclared net by default is implicitly declared as a 1-bit wire `default_nettype compiler directive can be used to override the default net type
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 114

dce

2007

Gate-level Modeling An Example


module Mux41 (Z, D0, D1, D2, D3, S0, S1); output Z; input D0, D1, D2, D3, S0, S1; not (S0bar, S0), (S1bar, S1); and (T0, D0, S0bar, S1bar), (T1, D1, S0, S1bar), (T2, D2, S0bar, S1), (T3, D3, S0, S1); or (Z, T0, T1, T2, T3); endmodule

An instance name cannot be the same as a net name within one module

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

115

dce

2007

2-to-4 Decoder

module Decoder24 (I, Enable, Z); output [3:0] Z; input [1:0] I; input Enable; not #(1, 2) V0 (I0bar, V1 (I1bar, nand #(4, 3) N0 (Z[0], N1 (Z[1], N2 (Z[2], N3 (Z[3], endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 116

I[0]), I[1]); Enable, Enable, Enable, Enable, I0bar, I1bar), I[0], I1bar), I0bar, I[1]), I[0], I[1]);

dce

2007

Master-Slave Flip-flop
module MS_DFF (D, C, Q, Qbar); output Q, Qbar; input D, C; not NT1 (NotD, D), NT2 (NotC, C), NT3 (NotY, Y); nand ND1 (D1, D, C), ND2 (D2, C, NotD), ND3 (Y, D1, Ybar), ND4 (Ybar, Y, D2), ND5 (Y1, Y, NotC), ND6 (Y2, NotY, NotC), ND7 (Q, Qbar, Y1), ND8 (Qbar, Y2, Q); endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 117

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

118

dce

2007

User-Defined Primitives (UDP)


Defining a UDP Combinational UDP Sequential UDP

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

119

dce

2007

Defining a UDP
primitive UDP_name (OutputName, ListOfInputs); output_declaration list_of_input_declarations [reg_declaration] [initial_statement] table list_of_table_entries endtable endptimitive

An UDP definition does not depend on a module definition


Appear outside of a module definition

An UDP can have only one output and may have one or more inputs
The first port must be the output port The output can have the value 0, 1 or x (z is not allowed) Value z on inputs is treated as an x
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 120

dce

2007

Combinational UDP
The table specifies the various input combination and their corresponding output values
The order of the input ports must match the order of entries in the table The ? character represents a dont-care value (0, 1 or x) Any combination that is not specified is an x for the output
primitive Mux21 (Z, In1, In0, Sel); output Z; input In0, In1, Sel; table // In1 In0 0 ? 1 ? ? 0 ? 1 0 0 1 1 endtable endptimitive
Introduction to Verilog HDL

Sel 1 1 0 0 x x

: : : : : : :

Z 0 1 0 1 0 1

Note: this line is only a comment ; ; ; ; ; ;

2007, Dr. Dinh Duc Anh Vu

121

dce

2007

Sequential UDP
The internal state is described using a 1-bit register
The value of this register is the output of the sequential UDP

2 kinds of sequential UDP


Level-sensitive behavior Edge-sensitive behavior

A sequential UDP uses the current value of the register and the input values to determine the next value of the register Initializing the state register
initial reg_name = 0, 1 or x;

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

122

dce

2007

Level-sensitive Sequential UDP


D-type latch: as long as the clock is 0, data passes from the input to the output, else the value remains latched
primitive D_Latch (Q, Clk, D); output Q; reg Q; input Clk, D; table // Clk D 0 1 0 0 1 ? endtable endptimitive Q(state) : ? : ? : ? Q(next) : 1; : 0; : -;

The character implies a no change


Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 123

dce

2007

Edge-triggered Sequential UDP


primitive D_Edge_FF (Q, Clk, D); output Q; reg Q; input Clk, D; initial Q = 0; table // Clk D Q(state) Q(next) (01) 0 : ? : 0; (01) 1 : ? : 1; (0x) 1 : 1 : 1; (0x) 0 : 0 : 0; // ignore negative edge of clock (?0) ? : ? : -; // ignore data changes on steady clock ? (??) : ? : -; endtable (01) indicates a transition from 0 to 1 endptimitive

(??) indicates any transition


Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 124

dce

2007

Mixed Sequential UDP


primitive D_Async_FF (Q, Clk, Clr, D); output Q; reg Q; input Clk, Clr, D; table // Clk Clr D Q(state) Q(next) (01) 0 0 : ? : 0; (01) 0 1 : ? : 1; (0x) 0 1 : 1 : 1; (0x) 0 0 : 0 : 0; // ignore negative edge of clock (?0) 0 ? : ? : -; (??) 1 ? : ? : 0; ? 1 ? : ? : 0; endtable endptimitive

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

125

dce

2007

3-bit Majority Circuit


primitive Majority3 (Z, A, B, C); output Z; Symbol input A, B, C; 0 table 1 // A B C : Z 0 0 ? : 0; x 0 ? 0 : 0; ? ? 0 0 : 0; b 1 1 ? : 1; 1 ? 1 : 1; ? 1 1 : 1; (AB) endtable * endptimitive r f p n
Introduction to Verilog HDL

Meaning Logic 0 Logic 1 Unknown Any of 0, 1 or x Any of 0 or 1 No change Value change from A to B Same as (??) Same as (01) Same as (10) Any of (01), (0x) or (x1) Any of (10), (1x) or (x0)
2007, Dr. Dinh Duc Anh Vu 126

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

127

dce

2007

Dataflow Modeling
Continuous Assignment Net Declaration Assignment Delays Net Delays

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

128

dce

2007

Continuous Assignment
A continuous assignment assigns a value to a net
Not to a register

assign [delay] LHS_net = RHS_expression; Whenever an event occurs on an operand used in the RHS_expression, the expression is evaluated and if the result value is different, it is assigned to the LHS target The target in a continuous assignment can be one of
Scalar net Vector net Constant bit-select of a vector Constant part-select of a vector Concatenation of any of above wire [3:0] Sum, A, B; wire Cout, Cin; assign Cin = Preset & Clear; assign {Cout, Sum} = A + B + Cin; assign Mux Mux Mux Mux = = = = (S==0) (S==1) (S==2) (S==3) ? ? ? ? A: B: C: D: bz; bz; bz; bz;
129

assign assign assign assign

Mux Mux Mux Mux

= = = =

(S==0) (S==1) (S==2) (S==3)

? ? ? ?

A: B: C: D:

bz; bz; bz; bz;

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

dce

2007

Net Declaration Assignment


A continuous assignment can appear as part of a net declaration
Net declaration assignment
wire [3:0] Sum = 4b0; wire Cout = 1b0, Cin = b1; wire A_GT_A = A > B, B_GT_A = B > A;

It is a convenient form of declaring a net and then writing a continuous assignment


wire Clear = b1; wire Clear; assign Clear = b1;

Multiple net declaration assignments on the same net are not allowed
wire Clear = b1; wire Clear = Signal_From_Button;
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 130

dce

2007

Delays
assign #(rise, fall, turn-off) LHS_target = RHS_expression;
Quiet Late Ask
10 20

assign #6 Ask = Quiet || Late;

5 6 11

15 6 26

assign #4 Ask = Late;

Late Ask

The latest value change is applied

13 4

18 20

26 4

For a vector net target,

17

26

if the RHS value goes from a non-zero value to a zero vector, fall delay is used if RHS value goes to z, turn-off delay is used else rise delay is used
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 131

dce

2007

Net Delays
A delay can also be specified in a net declaration
Net delay
wire #5 Ask;

Driver 1 Assign delay RHS expression Assign delay Driver 2

Net target

Net delay

assign #2 Ask = Quiet || Late; wire #5 Ask = Quiet || Late;

Quiet Late Ask

20

40

10 7

30 7 17 47

Assignment delay
Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

132

dce

2007

Dataflow Modeling Examples

module MagnitudeComparator (A, B, AgtB, AeqB, AltB); parameter BUS = 8; parameter EQ_DELAY = 5; module MS_DFF_RTL (D, C, Q, Qbar); parameter LT_DELAY = 8; output Q, Qbar; parameter GT_DELAY = 8; input D, C; output AgtB, AeqB, AltB; assign NotD = ~D; input [1:BUS] A, B; assign NotC = ~C; assign #GT_DELAY AgtB = A > B; assign NotY = ~Y; assign #EQ_DELAY AeqB = A == B; assign #LT_DELAY AltB = A < B; assign D1 = ~(D & C); assign D2 = ~(C & NotD); endmodule assign Y = ~(D1 & Ybar); assign Ybar = ~(Y & D2); assign Y1 = ~(Y & NotC); assign Y2 = ~(NotY & NotC); assign Q = ~(Qbar & Y1); assign Qbar = ~(Y2, Q); endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 133

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

134

dce

2007

Behavioral Modeling
Procedural Constructs Timing Controls Block Statement Procedural Assignments Conditional Statement Case Statement Loop Statement Procedural Continuous Assignment
2007, Dr. Dinh Duc Anh Vu 135

Introduction to Verilog HDL

dce

2007

Procedural Constructs
Two statements:
initial statement
mainly used for initialization and waveform generation executes only once starts execution at time 0

always statement
executes repeatedly start execution at time 0

Concurrent execution
Order of statements in a module is not important
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 136

dce

2007

initial Statement
initial [timing_control] procedural_statement

procedural_statement
procedural_assignment (blocking or non-blocking) procedural_continuous_assignment conditional_statement case_statement loop_statement wait_statement disable_statement event_trigger sequential_block parallel_block task_enable (user or system)
2007, Dr. Dinh Duc Anh Vu 137

Introduction to Verilog HDL

dce

2007

initial Statement Example


reg A; reg B; initial A = b0; initial #2 B = b1; parameter SIZE=1024; reg [7:0] RAM[0:SIZE-1]; reg RibReg; initial begin: Seq_Blk_A integer index; RibReg = 0; for (index=0; index<SIZE; index=index+1) RAM[index] = 0; end

// waveform generation parameter DELAY=5; reg [7:0] Port_A; initial begin Port_A #DELAY #DELAY #DELAY end

Port_A
= hF2; Port_A = hF2; Port_A = h41; Port_A = h0A;

h20
0 5

hF2
10

h41
15

h0A

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

138

dce

2007

always Statement
always [timing_control] procedural_statement
always #5 Clk = ~Clk; // waveform on Clk of period 10 reg [3:0] Accum; reg [0:5] InstrReg; wire ExecuteCycle; always @(ExecuteCycle) begin case (InstrReg[0:1]) 2b00: Store(Accum, InstrReg[2:5]); 2b01: Load(Accum, InstrReg[2:5]); 2b10: Jump(InstrReg[2:5]); 2b11: ; endcase end // Store, Load and Jump are user-defined tasks
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 139

dce

2007

always Statement Example


module input output reg DFF (Clk, D, Set, Q, Qbar); Clk, D, Set; Q, Qbar; Q, Qbar;

always wait (Set==1) begin #3 Q = 1; #2 Qbar = 0; wait (Set==0); end always @(negedge Clk) begin if (Set != 1) begin #5 Q = D; #2 Qbar = ~Q; end end endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 140

dce

2007

Procedural Constructs Example


module TestXorBehavior; reg Sa, Sb, Zeus; initial begin Sa = 0; Sb = 0; #5 Sb = 1; #5 Sa = 1; #5 Sb = 0; end always @(Sa or Sb) Zeus = Sa ^ Sb; Sa Sb Zeus

10

15

At time 5, Sa = 0, Sb = 1, Zeus = 1 At time 10, Sa = 1, Sb = 1, Zeus = 0 At time 15, Sa = 1, Sb = 0, Zeus = 1

always @(Zeus) $display (At time %t, Sa = %d, Sb = %d, Zeus = %b, $time, Sa, Sb, Zeus); endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 141

dce

2007

Timing Controls
Timing control is of two forms
Delay control
specifies the time duration from the time the statement is initially encountered to the time the statement executes (wait for delay before executing the statement)

Event control
Statement executes based on events two kinds of event control
Edge-triggered event control Level-sensitive event control

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

142

dce

2007

Delay Control
#delay procedural_statement
initial begin #3 wave = b0111; #6 wave = b1100; #7 wave = b0000; end

#delay;

parameter ON_DELAY=3, OFF_DELAY=5; always begin #ON_DELAY; // wait for ON_DELAY RefClk = 0; #OFF_DELAY; // wait for OFF_DELAY RefClk = 1; end

The delay in the delay control can be an arbitrary expression


Explicit zero delay: the value of the delay expression is 0

#Strobe compare = Tx ^ Mask; #(PERIOD / 2) Clock = ~Clock;

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

143

dce

2007

Edge-triggered Event Control


@event procedural_statement
@(posedge Clock) Curr_State = Next_State;

@event ;
time RiseEdge, OnDelay;

@(posedge Clear or negedge Reset) Count = 0; @Cla Zoo = Foo;


posedge negedge 1x 1z 10 x0 z0

0x initial begin 0z // wait until positive edge on clock occurs 01 @(posedge ClockA); x1 RiseEdge = $time; z1 // wait until negative edge on clock occurs @(negedge ClockA); OnDelay = $time - RiseEdge; $display(The on-period of clock is %t, OnDelay); end
Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

144

dce

2007

Level-sensitive Event Control


wait (condition) procedural_statement
wait (Sum > 22) Sum = 0; wait (DataReady) Data = Bus; wait (Preset);

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

145

dce

2007

Block Statement
Mechanism to group two or more statements to act syntactically like a single statement
Sequential block (begin end): statements are executed sequentially in the given order Parallel block (fork join): statements execute concurrently

A block can be labeled optionally


If so labeled, registers can be declared locally within the block Block label provides a way to uniquely identify registers

A block can also be referenced


It can be disabled using disable statement
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 146

dce

2007

Sequential Block
begin [:block_id {declaration}] procedural_statement(s) end
begin Pat = Mask | Mat; @ (negedge Clk) FF = & Pat; end begin: SEQ_BLK reg [0:3] Sat; Sat = Mask & Data; FF = ^ Pat; end
Introduction to Verilog HDL

A delay value in each statement is relative to the simulation time of the execution of the previous statement
// waveform begin #2 Stream #5 Stream #3 Stream #4 Stream end generation = = = = 1; 0; 1; 0;

assume the sequential block get executed at time 10

Stream
10 12 17 20 24

2007, Dr. Dinh Duc Anh Vu

147

dce

2007

Parallel Block
fork [:block_id {declaration}] procedural_statement(s) join always
begin: SEQ_A #4 Dry = 5; fork: PAR_A #6 Cun = 7; begin: SEQ_B Exe = Box; #5 Jap = Exe; end #2 Dop = 3; #4 Gos = 2; #8 Pas = 4; join #8 Bax = 1; #6 $stop end
Introduction to Verilog HDL

All statements within the parallel block must complete execution before control passes out of the block
// waveform begin #2 Stream #5 Stream #3 Stream #4 Stream end generation = = = = 1; 0; 1; 0;

assume the sequential block get executed at time 10

Stream
10 12 14

2007, Dr. Dinh Duc Anh Vu

148

dce

2007

Procedural Assignments
Procedural assignment is an assignment within an initial statement or an always statement
used to assign to only a register data type executes sequentially with respect to other statements that appear around it always @(A or B or C or D)
begin: AOI reg Temp1, Temp2; Temp1 = A & B; Temp2 = C & D; Temp1 = Temp1 | Temp2; Z = ~ Temp1; end

2 kinds of procedural assignment


blocking non-blocking
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 149

dce

2007

Intra-statement Delay
RHS_target = #delay RHS_expression;

The RHS expression is evaluated before the delay, then the wait occurs and then the value is assigned to the LHS target
Done = #5 b1; // intra-statement delay control begin Temp = b1; #5 Done = Temp; // inter-statement delay control end

Q = @(posedge Clk) D; // intra-statement event control begin Temp = D; @(posedge Clk) // inter-statement event control Q = Temp; end
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 150

dce

2007

Blocking Procedural Assignment

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

151

dce

2007

Non-Blocking Procedural Assignment

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

152

dce

2007

Continuous Assignment vs. Procedural Assignment


Procedural Assignment Occurs inside an always statement or an initial statement Execution is with respect to other statements surrounding it Drives registers Uses = or <= assignment symbol No assign keyword (except in a procedural continuous assignment) Continuous Assignment Occurs within a module Executes concurrently with other statements Executes whenever there is a change of value in an operand on its RHS Drives nets Uses = assignment symbol Uses assign keyword

module Procedural; reg A, B, Z; always @(B) begin Z = A; A = B; end endmodule


Introduction to Verilog HDL

module Continuous; wire A, B, Z; assign Z = A; assign A = B; endmodule

2007, Dr. Dinh Duc Anh Vu

153

dce

2007

Conditional Statement if
if (condition_1) procedural_statement_1 {else if (condition_2) procedural_statement_2 } [else procedural_statement_3 ] Note that the condition expression must always be within parenthesis

Simple 4-1 multiplexer

module mux41 (sel, A, B, C, D, Y); input [1:0] sel; // 2-bit control signal input A, B, C, D; output Y; reg Y; // target of assignment always @(sel or A or B or C or D) if (sel == 2b00) Y = A; else if (sel == 2b01) Y = B; else if (sel == 2b10) Y = C; else if (sel == 2b11) Y = D; endmodule

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

154

dce

2007

if Statement Example
Simple 4-1 multiplexer
module mux41 (sel, A, B, C, D, Y); input [1:0] sel; // 2-bit control signal input A, B, C, D; output Y; reg Y; // target of assignment always @(sel or A or if (sel[0] == 0) if (sel[1] == 0) else else if (sel[1] == 0) else endmodule B or C or D) Y = A; Y = B; Y = C; Y = D;

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

155

dce

2007

case Statement
case (case_expr) case_item_expr {, case_item_expr}: procedural_statement ... [default: procedural_statement ] endcase

The case expression is evaluated first The case item expressions are evaluated and compared in the order given (sequential execution) Only first case that matches is executed (no break) Multiple case item expressions need not be mutuallyexclusive The x and z values are compared as their literal values
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 156

dce

2007

case Statement Examples


module ALU (A, B, OpCode, Z); input [3:0] A, B; input [1:2] OpCode; output [7:0] Z; reg [7:0] Z; parameter ADD_INSTR = 2b10, SUB_INSTR = 2b00, MUL_INSTR = 2b01, DIV_INSTR = 2b11; OpCode) A A A A + * / B; B; B; B;

module mux41 (sel, A, B, C, D, Y); input [1:0] sel; input A, B, C, D; output Y; reg Y; always @(sel case (sel) 2b00: Y 2b01: Y 2b10: Y 2b11: Y endcase endmodule or A or B or C or D) = = = = A; B; C; D; Conditions tested in top to bottom order

always @(A or B or case (OpCode) ADD_INSTR: Z = case (3b101 << 2) SUB_INSTR: Z = 3b100: $display(First branch taken); MUL_INSTR: Z = 4b0100: $display(Second branch taken); DIV_INSTR: Z = 5b10100: $display(Third branch taken); endcase default: $display(Default branch taken); endcase endmodule
Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

157

dce

2007

case Statement Examples


// Simple binary encoder (input is 1-hot) module encode (A, Y); input [7:0] A; // 8-bit input vector output [2:0] Y; // 3-bit encoded output reg [2:0] Y; // target of assignment always @(A) case (A) 8b00000001: 8b00000010: 8b00000100: 8b00001000: 8b00010000: 8b00100000: 8b01000000: 8b10000000: default: endcase endmodule
Introduction to Verilog HDL

Y Y Y Y Y Y Y Y Y

= = = = = = = = =

0; Without the default case, this 1; example would create a latch for Y 2; Assigning X to a variable means 3; synthesis is free to assign any value 4; 5; 6; 7; 3bX;// Dont care when input is not 1-hot

2007, Dr. Dinh Duc Anh Vu

158

dce

2007

case Statement Examples


// Simple encoder (input is 1-hot) module encode (A, Y); input [7:0] A; // 8-bit input vector output [2:0] Y; // 3-bit encoded output reg [2:0] Y; // target of assignment always @(A) case (1b1) // synthesis parallel-case A[0]: Y = 0; A[1]: Y = 1; A[2]: Y = 2; A priority encoder is more A[3]: Y = 3; expensive than a simple encoder A[4]: Y = 4; A[5]: Y = 5; A[6]: Y = 6; A[7]: Y = 7; default: Y = 3bX;// Dont care when input is not 1-hot endcase endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 159

dce

2007

Dont-cares in case
Different interpretation for x and z values
casez statement
Like case, but the value z in the case expression and in any case item expression is considered as a dont-case
i.e. that bit is ignored

casex statement
both the values x and z are considered as dont-cares

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

160

dce

2007

// Priority encoder module encoder (A, valid, Y); input [7:0] A; // 8-bit input vector output [2:0] Y; // 3-bit encoded output output valid; // Asserted when an input is not all 0s reg [2:0] Y; // target of assignment reg valid; always @(A) begin valid = 1; casex (A) 8bXXXXXXX1: Y = 0; 8bXXXXXX10: Y = 1; 8bXXXXX100: Y = 2; 8bXXXX1000: Y = 3; 8bXXX10000: Y = 4; 8bXX100000: Y = 5; 8bX1000000: Y = 6; 8b10000000: Y = 7; default: begin valid = 0; Y = 3bX; // Dont care when input is all 0s end endcase end // always endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 161

dce

2007

Loop Statement
4 kinds of loop statements
Forever loop Repeat loop While loop For loop

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

162

dce

2007

Forever-loop Statement
forever procedural_statement

This statement continuously executes the procedural statement To get out of such a loop, a disable statement may be used with the procedural statement Some form of timing controls must be used in the procedural statement
initial begin clock = 0; #5 forever #10 clock = ~clock; end
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 163

dce

2007

Repeat-loop Statement
repeat (loop_count) procedural_statement The procedural statement is executed the specified number of times If the loop count expression is an x or a z, the loop count is treated as a 0
repeat (num_of_times) @(negedge clk);
for count times, wait for positive edge of Clk and when this occurs, increment sum compute sum+1 first, then wait for count positive edges on Clk then assign to LHS
2007, Dr. Dinh Duc Anh Vu 164

repeat (count) sum = sum + 10; repeat (ShiftBy) P_Reg = P_Reg << 1;

repeat (count) // repeat-loop statement @(posedge Clk) sum sum + 1;

sum = repeat (count) @(posedge Clk) sum + 1; // repeat event control


Introduction to Verilog HDL

dce

2007

While-loop Statement
while (condition) procedural_statement

This loop executes the procedural statement until the specified condition becomes false. If the condition is an x or a z, it is treated as a 0 (false)
while (By > 0) begin Acc = Acc << 1; By = By -1; end

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

165

dce

2007

For-loop Statement
for (initial_assignment; condition; step_assignment) procedural_statement

This loop repeats the execution of the procedural statement a certain number of times.
integer K; for (K=0; K < MAX_RANGE; K = K + 1) begin if (ABus[K] == 0) ABus[K] = 1; else if (ABus[K] == 1) ABus[K] = 0; else $display(Abus[%d] is an x or a z, K); end

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

166

dce

2007

Procedural Continuous Assignment


Procedural continuous assignment is a procedural assignment
i.e. it can appear within an always statement or an initial statement But, it is not a continuous assignment

This assignment can override all other assignments to a net or a register


allows the expression in the assignment to be driven continuously into a register or a net

2 kinds of procedural continuous assignment


assign and deassign procedural statement: these assign to registers force and release procedural statement: these assign primarily to nets (though they can also be used for registers)

The assign and force statements are continuous in the sense that any change of operand in the RHS expression causes the assignment to be re-done while the assign or force is in effect Target cannot be a part-select or a bit-select of a register
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 167

dce

2007

assign deassign
An assign procedural statement overrides all procedural assignments to a register. The deassign procedural statement ends the continuous assignment to a register The value in the register is retained until assigned again.
DFF (D, Clr, Clk, Q); D, Clr, Clk; Q; Q;

module input output reg

If an assign is applied to an already assigned register, it is deassigned first before making the new procedural continuous assignment.
reg [3:0] Pest; ... Pest = 0; ... assign Pest = Hty ^ Mtu; ... assign Pest = 2; // will deassign Pest and then assign ... deassign Pest; // Pest continues to have value 2 ... assign Pest[2] = 1; // Error: ???
2007, Dr. Dinh Duc Anh Vu 168

always @(Clr) begin if (!Clr) assign Q = 0; // D has no effect on Q else deassign Q; end // always always @(negedge Clk) Q = D; endmodule
Introduction to Verilog HDL

dce

2007

force release
The force procedural statement on a net overrides all the drivers for the net until a release procedural statement is executed on that net. When applied to a register, the force statement causes the current value of the register to be overridden by the value of the force expression
When a release on a register is executed, the current value is held in the register unless a procedural continuous assignment was already in effect (at the time the force statement was executed) in which case, the continuous assignment establishes the new value of the register.

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

169

dce

2007

force release
reg [2:0] Colt; ... Colt = 2; force Colt = 1; ... release Colt; // Colt retains 1 ... assign Colt = 5; ... force Colt = 2; ... release Colt; // Colt gets the value 5 ... force Colt[1:0] = 3; // Error: ???

wire Prt; ... or #1 (Prt, Std, Dzx); initial begin force Prt = Dzx & Std; #5; release Prt; end

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

170

dce

2007

A Handshake Example
Registers can be used in interacting processes
It is not recommended to use registers declared within an always statement to pass information between always statement

Example: interacting of a Receiver and a Processor


Ready Serial_In Clk

Receiver

Data Ack

Processor

Parallel_Out

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

171

dce

2007

`timescale 1ns/100ps module Interacting (Serial_In, Clk, Parallel_Out); input Serial_In, Clk; output [0:7] Parallel_Out; reg [0:7 Parallel_Out; reg Ready, Ack; wire [0:7] Data; `include Read_Word.v // task Read_Word is defined in this file always begin: RX Read_Word(Serial_In, Clk, Data); // the task Read_Word reads the serial data on every clock cycle // and converts to a parallel data in signal Data. // It takes 10ns to do this Ready = 1; wait (Ack); Ready = 0; #40; end always begin: MP #25; Parallel_Out = Data; Ack = 1; #25 Ack = 0; wait (Ready); end endmodule
Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 172

dce

2007

A Handshake Example
always begin: RX Read_Word(Serial_In, Clk, Data); // It takes 10ns to do this Ready = 1; wait (Ack); Ready = 0; #40; end always begin: MP #25; Parallel_Out = Data; Ack = 1; #25 Ack = 0; wait (Ready); end

Receiver reading new serial data Ready


10 65 75 140 150

Ack
0 25 50 100 125 175 200

Data output by Processor


Introduction to Verilog HDL 2007, Dr. Dinh Duc Anh Vu 173

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

174

dce

2007

Structural Modeling
Module Ports Module Instantiation External Ports

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

175

dce

2007

Module

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

176

dce

2007

Ports

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

177

dce

2007

Module Instantiation

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

178

dce

2007

External Ports

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

179

dce

2007

Outline
Design flow What is a HDL? Verilog HDL A tutorial Language elements Verilog Expressions Gate-level modeling User-defined primitives Dataflow modeling Behavioral modeling Structural modeling Lots of examples Advanced topics

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

180

dce

2007

Advanced Topics
Tasks Functions Systems Tasks and Functions Disable Statement Named Events Mixed Structure with Behavior Hierarchical Path Name Sharing Tasks and Functions Value Change Dump (VCD) File Specify Block Strengths Race Conditions
2007, Dr. Dinh Duc Anh Vu 181

Introduction to Verilog HDL

dce

2007

Verification
Writing a testbench Waveform Generation Reading Vectors from a Text File Writing Vectors to a Text File

Introduction to Verilog HDL

2007, Dr. Dinh Duc Anh Vu

182

dce

2006

End slide

You might also like