Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views115 pages

Lecture 2 - Verilog

Uploaded by

galgureni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views115 pages

Lecture 2 - Verilog

Uploaded by

galgureni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

Digital VLSI Design

Lecture 2: Introduction to Verilog


HDL
Semester B 2025
Lecturer: Asi Sapir
24 March 2025

Disclaimer: This course was prepared, in its entirety, by Adam Teman. Many materials were copied from sources freely available on the internet. When
possible, these sources have been cited; however, some references may have been cited incorrectly or overlooked. If you feel that a picture, graph, or code
example has been copied from you and either needs to be cited or removed, please feel free to email [email protected] and I will address this as soon as
possible. 1
Outline
HDL Verilog
Synthesis Verilog tutorial
Synthesis coding guidelines
Verilog - Test bench
References

2
HDL Verilog
3
What is HDL?
Hardware Description Language
To describe the circuits by syntax and sentences
As opposed to circuit described by schematics

Widely used HDLs


Verilog – Similar to C
SystemVerilog – Similar to C++
VHDL – Similar to PASCAL

4
Verilog
Year Note
Verilog was developed by Gateway Design Automation as a proprietary
1984
language for logic simulation
1989 Gateway was acquired by Cadence
Verilog was made an open standard under the control of Open Verilog
1990
International
Verilog became an IEEE standard (IEEE STD 1364) and was updated in 2001
1995
and 2005

5
System Verilog
SystemVerilog is the industry's first unified hardware description and verification
language

Started with Superlog language to Accellera in 2002


Verification functionality (base on OpenVera language) came from Synopsys
In 2005 SystemVerilog was adopted as IEEE Standard (1800-2005). The current
version is 1800-2009

6
IEEE-1364 / IEEE-1800
Verilog 2005 (IEEE Standard 1364-2005)
consists of minor corrections, spec
clarifications, and a few new language
features

SystemVerilog is a superset of Verilog-


2005, with many new features and
capabilities to aid design-verification and
design-modeling

7
Types of Modeling
Architectural/Algorithmic
A system is described in terms of the algorithms it performs rst Counter
If (rst)
Behavioral cnt = 0;
cnt [0:3]
A system is described by the flow of data between its clk else
cnt = cnt+1;
functional blocks
Use of assignment statements, loops, if, else kind of
statements
Register Transfer Logic (RTL) or Functional
A system is described by the flow of data and control signals
within and between functional blocks
Schedule assignments at all clocks boundaries, at every
clock edge
Structural / Gate-Level
Describes the structure of hardware components
Interconnections of primitive gates (AND, OR, NAND, NOR
etc.) and
Switch
Components are modeled by the logic behavior of their
transistor circuits for maximum accuracy
8
Register Transfer Logic - Structural
module cter (input rst, clock, output reg [1:0] count);
always@(posedge clock)
if (rst) count = 0;
else count = count+1;
endmodule

module cter ( rst, clock, count );


output [1:0] count;
input rst, clock;

wire N5, n1, n4, n5, n6;


FD1 U0 (.D(N5), .CP(clock), .Q(count[0]), .QN(n6));
FD1 U1 (.D(n1), .CP(clock), .Q(count[1]), .QN(n5));
MUX21 U2 (.A(N5), .B(n4), .S(n5), .Z(n1));
NR2 U3 (.A(n6), .B(rst), .Z(n4));
NR2 U3 (.A(count[0]), .B(rst), .Z(N5));
endmodule
9
Simulation and Synthesis
Two major purposes of HDL
Logic simulation
During simulation, inputs are applied to a module, and the outputs are
checked to verify that the module operates correctly
Synthesis
During synthesis, the textual description of a module is transformed into
logic gates
Circuit descriptions in HDL resemble code in a programming language
Code is intended to represent hardware

10
Simulation and Synthesis
Not all Verilog commands can be synthesized into hardware
Our primary interest is to build hardware
Emphasize a synthesizable subset of the language
Will divide HDL code into synthesizable modules and a test bench
Synthesizable modules: Describe the hardware.
The test bench: Drive and monitor/check the hardware model
only for simulation and cannot be synthesized

11
SYNTHESIS VERILOG TUTORIAL

12
Outline
Lexical elements
Data type representation
Structures and Hierarchy
Operators
Blocks and Assignments
Control statements
Task and functions
Generate blocks

13
Lexical elements
Case sensitive - keywords are lower case
Semicolons (;) are line terminators
Comments:
One-line comments start with
// ...

Multi-line comments start with


/* and end with */

System tasks and functions start with a dollar sign

$display
$signed 14
Lexical elements
Variable names must start with an alphabetic character or underscore (_) followed
by alphanumeric or underscore characters
Escaped identifiers ()
Permit non alphanumeric characters in Verilog name
Escaped name includes all the characters following the backslash until the first
white space character

wire \fo+o=a ; // Declare the variable fo+o=a


wire \fo+o =a ; // Assign a to wire fo+o

15
Compiler Directives
Directives start with a grave accent (`) followed by some keyword

`define Text-Macro Substitution `include “file1.v”


// Used as `WORD_SIZE in code
`ifdef Conditional compilation `define WORD_SIZE 32

`ifndef module test ();


`ifdef TEST
`else // A implementation
`else
`endif // B implementation
`endif
`include File Inclusion assign out = `WORD_SIZE{1’b1};
endmodule

16
Reserved keywords

always and assign automatic begin buf bufif0 bufif1

case casex casez cell cmos config deassign default

defparam design disable edge else end endcase endconfig

endfunction endgenerate endmodule endprimitive endspecify endtable endtask event

for force forever fork function generate genvar highz0

highz1 if ifnone incdir include initial inout input

instance integer join large liblist library localparam macromodule

medium module nand negedge nmos nor noshowcancelled not

notif0 notif1 or output parameter pmos posedge primitive

pull0 pull1 pulldown pullup pulsestyle_onevent pulsestyle_ondetect rcmos real

realtime reg release repeat rnmos rpmos rtran rtranif0

rtranif1 scalared showcancelled signed small specify specparam strong0

strong1 supply0 supply1 table task time tran tranif0

tranif1 tri tri0 tri1 triand trior trireg unsigned

use uwire vectored wait wand weak0 weak1 while

wire wor xnor xor 17


Outline
Lexical elements
Data type representation
Structures and Hierarchy
Operators
Blocks and Assignments
Control statements
Task and functions
Generate blocks

18
Logical Values
A bit can have any of these values
0 representing logic low (false)
1 representing logic high (true)
X representing either 0, 1, or Z
Z representing high impedance for tri-state (unconnected inputs are set to Z)

19
Logical Values
Logic with multilevel (0,1,X,Z) logic values
Nand anything with 0 is 1
Nand two X get an X
True tables define the how outputs are compute

& 0 1 X Z | 0 1 X Z
0 0 0 0 0 0 0 1 X X
1 0 1 X X 1 1 1 1 1
X 0 X X X X X 1 X X
Z 0 X X X Z X 1 X X
20
Number Representation
<size>'<base format><number>

size:
number of bits (optional)
base format:
It is a single character ' followed by one of the following characters b, d, o and
h, which stand for binary, decimal, octal and hex, respectively.
number:
Contains digits which are legal for the base format
‘_’ underscore can be use for readability

21
Number Representation
Negative numbers are store as 2’s complement
Extended number
If MSB is 0, X or Z number is extended to fill MSBs with 0, X, Z respectively
3’b01=3’b001 3’bx1=3’bxx1 3’bz=3’bzz

If MSB is 1 number is extended to fill MSBs with 0/1, depending on the sign
3’b1=3’b001 -3’b1=-3’b01=3’b111

22
Number Representation
Unsized numbers (at least 32 bit)

549 // decimal number


'h8F_F // hex number
'o765 // octal number

Size numbers

4'b11 // 4-bit binary number 0011


3'b10x // 3-bit binary number, LSM but unknown
8'hz // 8-bit hex high-impedance number
4'hz1 // 4-bit hex 4'bzzz1
5'd3 // 5-bit decimal number

Signed numbers

-8'd6 // 8-bit two's complement of 6 (-6)


4'shF // 4-bit number ‘1111’ to be interpreted as
// 2’s complement number 23
Data Types (Reg)
A reg ( reg ) stores its value from one assignment to the next
Model data storage elements
Don’t confuse reg with register
Default value is X
Default range is one bit
Default type is unsigned, but can be declare signed, using keyword signed

24
Data Types (Nets)
Nets ( wire ) correspond to physical wires that connect instances
Nets do not store values
Must be continuously driven
Default range is one bit
Default type is unsigned
wire declaration is used most frequently, other net types are wand/triand ,
wor/trior , tri , etc.

25
Other Data Types
Integer ( integer )
Convenient for counting purposes
At least 32-bit wide
Useful for loop
Real ( real ) simulation only
Can be specified in decimal and scientific notation

26
Verilog Vectors (BUS)

Declare by a range following the type

<data type> [left range : right range] <Variable name>

Single element that is n-bits wide

reg [0:7] A, B; //Two 8-bit reg with MSB as the 0th bit
wire [3:0] Data; //4-bit wide wire MSB as the 4th bit

Vector part select (access)

A[5] // bit # 5 of vector A


Data[2:0] // Three LSB of vector Data

Vector operation

B = 32 + A; 27
Verilog Arrays

Array: Range follows the name

<data type> <array name> [<array indices>]

reg B [15:0]; // array of 16 reg elements

Array of vectors

<data type> [<vector indices>]<array name>[<array indices>]

reg [15:0] C [1023:0]; // array of vectors

Memory access

<var name>[<array indices>] [<vector indices>]

28
Data Storage and Verilog Arrays
Simple RAM Model
model RAM (output [7:0] Obus,
input [7:0] Ibus,
input [3:0] Adr,
input Clk, Read);

reg [7:0] Storage [15:0];


reg [7:0] ObusReg;

assign Obus = ObusReg;

always @(posedge Clk)


if (Read==1’b0) Storage[Adr] = Ibus;
else ObusReg = Storage[Adr];

endmodule 29
Data Storage and Verilog Arrays
Counter
module cter (input rst, clock, jmp,
input [7:0] jump,
output reg [7:0] count);

always@(posedge clock)
begin
if (rst) count = 0;
else if (jmp) count = jump + count;
else count = count + 1;
end
endmodule

30
Outline
Lexical elements
Data type representation
Structures and Hierarchy
Operators
Blocks and Assignments
Control statements
Task and functions
Generate blocks

31
Structures and Hierarchies
Hierarchical HDL structures are achieved by defining modules
and instantiating modules
TOP module TOP (…port_list…);
U1
ALU U1 (…port connection…);
ALU S1 MEM U2 (…port connection…);
endmodule
FIFO
module ALU (…port_list…);
FIFO S1 (…port connection…);
U2 endmodule
MEM module FIFO (…port_list…);
//...
endmodule

32
Module Declaration
module example #(parameter S=1) (input i1, output o2); module <module name> #(<param list>) (<port list>);
wire tmp; <Declarations>
sub U1 (i1, tmp); <Instantiations>
assign o2 = ~i2; <Data flow statements>
always@ * <Behavioral blocks>
begin <Task and functions>
if (rst) cnt = 1’b0; endmodule
end
task sum (input a, output b);
// ...
endtask
endmodule

33
Module Header
Start with module keyword, contains the I/O ports
Port declarations begins with output , input or inout follow by bus indices
Each directions are followed by one or more I/O names
Each declaration is separated by comma (,)

module ALU (output [15:0] res,


output cout,
input [15:0] A, B,
input clock, ena);

34
Port Declaration
input and inout are declared as wire

output porta can be declared wire as reg (holds a value)

2 flavors for port declaration:

module S1 (a, b, c, d, e); module S2 (input [1:0] a, b,


input [1:0] a, b; input c; input c,
output reg [1:0] d; output reg [1:0] d,
output e; output e);

//Verilog 1995 Style //ANSI C Style


endmodule endmodule

35
Parameters
Parameters are means of giving names to constant values
Values can be overridden when the design is compiled
Parameters cannot be used as variables

Syntax:
parameter <name> = <constant expression>;

36
Parameter Declaration
Default value need to be set at declaration time
32 bit wide by default, but may be declared of any width

parameter [2:0] IDLE = 3’d0;

Two Declaration Flavors

Inside a Module In Module Header


module test (... I/O’s ...); module test
parameter ASIZE = 32, BSIZE =16; #(parameter ASIZE = 32, BSIZE =16)
//... (... I/O’s ...);
reg [ASIZE -1:0] Abus, Zbus; //...
wire [BSIZE-1:0] Bwire; reg [ASIZE -1:0] Abus, Zbus;
//... wire [BSIZE-1:0] Bwire;
endmodule //...
37
Example
A[N-1:0]
Adder S[N-1:0]
B[N-1:0]
N-bits
(8 by default) Cout
Cin
reg-ouputs
Clk

module Adder (A, B, Cin, S, Cout, Clk); module Adder #(parameter N=8)
parameter N=8; (input [N-1:0]A, B,
input [N-1:0]A, B; input Cin,
input Cin; input Clk,
input Clk; output reg [N-1:0] S,
output [N-1:0] S; output reg Cout
output Cout; );
reg [N-1:0] S; //module internals
reg Cout;
//module internals endmodule
endmodule

38
Structures and Hierarchy
Instance of a module
Instantiation is the process of “calling” a module
Create objects from a module template

<module name> #(<parameter list>) <instance name> (<port list>);

Where:
<module name> Module to be instantiated

<parameter list> Parameters values passed to the instance

<instance name> Identifies the instance of the module

<port list> Port list connection

39
Structures and Hierarchy
Port list connections
Provide interface by which a module can communicate with the environment
Port declarations ( input , output , inout )

reg o net net reg o net net

input output
net inout

net
40
Port Connections/Parameter Overwrite
Named Connection
Explicitly linking two names for each side of the conn
my_mod #(.W(1), .N(4)) U1 (.in1(a), .in2(b), .out(c));

Order Connection
Expression shall be listed in the same order as the port declaration
my_mod #(1,4) U2 (a, b, c);

41
Example
module TOP (input t1, t2, t3, output t4, t5, t6);
wire w1, w2, w3; TOP
ALU #(.S(2)) U1 (.a1(t1), .a2(t2), .a3(t3), a4(w1), a5(w2), a6(w3));
MEM U2 (w1, w2, w3, t4, t5, t6); U1
endmodule

module ALU (input a1, a2, a3, output a4, a5, a6);
parameter S=4;
ALU S1
reg rsl;

FIFO
wire sig;
FIFO S1 (.f1(rsl), .f3(sig));
//...
endmodule

module FIFO #(parameter F=2)

U2
(input f1, output reg f2);
//...
endmodule

MEM

42
Outline
Lexical elements
Data type representation
Structures and Hierarchy
Operators
Blocks and Assignments
Control statements
Task and functions
Generate blocks

43
Relational Operators
Mainly use in expression (e.g., if sentences)
Returns a logical value (1/true 0/false)
If there are any X or Z bit returns X (false on an expression)

< a<b is a less than b?


> a>b is a greater than b?
>= a >= b is a greater than or equal to b?
<= a <= b is a less than or equal to b?

44
Arithmetic Operators
Binary operators
Takes 2 operators
Unary operators (+/-)
Specify operand sign
Negative numbers are represented as 2’s complement

* c = a * b; Multiply a with b
/ c = a / b; Integer divide a by b
+ sum = a + b; add a and b
- diff = a - b; substract b from a
% mod = a % b; a mod(b) 45
Logical Operators
Logical operators evaluate to a 1-bit value

&& a && b Is a and b true? Returns 1-bit true/false

|| a || b Is a or b true? Returns 1-bit true/false

! if (!a) c = b If a is not true assign b to c

- If an operant is not zero is treat as logical 1


A=3; B=0;
A&&B //Evaluates to 0 same to (logical-1 && logical-0)
!B //Evaluates to 1 same to (!logical-0)

If an operant is Z or X treat as X (false)

A=2’b0x; B=2’b10;
A&&B //Evaluates to X same to (x && logical-0)

46
Equality and Identity operators
== c == a Is c equal to a ? Returns 1-bit true/false
!= c != a Is c not equal to a ? Returns 1-bit true/false
=== a === b Is a identical to b (includes 0,1,x, z)
!== a !== b Is a not identical to b

Using X or Z operans returens always false 47


Bitwise and Reduction operations
& b = &b And all bits of a (reduction)
| b = |a Or all bits of a (reduction)
^ b = ^a Exclusive Or all bit of a (reduction)
~&, ~|, ~^ c = ~&b Nand, Nor, Ex-Nor, all bits together
~, &, |, ^ b = ~a; e = b | a; Bit-wise Not, And, Or, Ex-Or
~&, ~|, ~^ e = a ~^ b Bit-wise Nand, Nor, Ex-Nor

48
Shift and other operators
<< a << 1 Shift left by 1 fill with 0
>> a >> 1 Shift right by 1 fill with 0
<<< b <<< 1 Arithmetic shift left by 1 fill with 0
>>> b >>> 1 Arithmetic shift right by 1 fill with sign
?: c = sel ? a : b If sel assign a to c else assign b
{} {co, sum} = a + b + ci Concatenation, overflow to co results to sum
{{}} b = {3{a}} Replicate a 3 times, {a,a,a}

49
Operator precedence
Unary, Multiply, Divide, Modulus +, -, !, ~, *, /, %

Operator precedence
Add, Subtract, Shift +, -, <<, >>
Relational Equality <, >, <=, >=, =, ==, !=, ===, !==
Reduction Logical &, ~&, ^, ~^, |, ~|, &&, ||
Conditional ?:

50
Outline
Lexical elements
Data type representation
Structures and Hierarchy
Operators
Blocks and Assignments
Control statements
Task and functions
Generate blocks

51
Concurrent Blocks
Blocks of code with no well-defined order relative to one another
Module instance
module AND (input A, B, output C);
wire w;
NAND U1 (A, B, w);
NAND U2 (w, w, C);
endmodule

Continuous assignments
Procedural blocks

52
Continuous Assignments
Continuous assignments imply that whenever any change on the RHS of the
assignment occurs, it is evaluated and assigned to the LHS
Continuous assignments always implement combinational logic
Continuous assignments drive wire variables

wire A;
assign A = (B|C)&D;

53
Example
module NAND (A, B, C); module AND (A, B, C);
input A, B; input A, B; output C; wire w;
output C; // 2 NAND instantiations
// Continuous assignments NAND U1 (A, B, w);
assign C = ~(A&B); endmodule NAND U2 (w, w, C);
endmodule

A A
C C

B B

U1 U2

54
Procedural Blocks
Each procedural block represent a separate activity flow in Verilog
Procedural blocks
always blocks
Model a block of activity that is repeated continuously
initial blocks simulation only
Model a block of activity that is executed at the beginning
Multiple behavioral statements can be grouped using keywords begin and end

55
Procedural Assignments
Procedural assignment changes the state of a reg
Used for both combinational and sequential logic inference
All procedural statements must be within always (or initial ) block

56
Always Block – Event Control (@)
Always blocks model an activity that is repeated continuously
@ can control the execution

posdege or negedge make sensitive to edge

@* / @(*) , are sensitive to any signal that may be read in the statement group

Use “,” / or for multiple signals

57
Always Block – Event Control (@)
module M1 (input B, C, clk, rst, output reg X, Y,Z);
// controlled by any value change in B or C
always @ (B or C)
X = B & C;

// Controlled by positive edge of clk


always @(posedge clk)
Y = B & C;

// Controlled by negative edge of clk or rst


always @(negedge clk, negedge rst)
if (!rst) Z = 1’b0;
else Z = B | C;
endmodule

58
Example
module FFD (input Clk, R, D, module LD (G, D, Q);
output reg Q); input G, D;
always @ (posedge Clk) begin output Q;
if (R) reg Q;
Q = 1'b0; always @ (G or D) if (G)
else Q = D;
Q = D; endmodule
end
endmodule

D Q D Q

R G
59
Blocking / Non-Blocking Assignment
Blocking Assignment always @(posedge Clk)
Acts much like in traditional programming begin
//blocking procedural assignment
languages = C = C + 1;
A = C + 1;
Whole statement done before control end
passes on to the next statement.
always @(posedge Clk) begin
Non-Blocking Assignment //non-blocking procedural assignment
D <= D + 1;
Evaluates all the right-hand sides for the
B <= D + 1;
current time unit and assigns the left-hand end
sides at the end of the time unit <=

During every clock cycle

A is ahead of C by 1

B is same as D

60
Blocking / Non-Blocking Example
module t (input clk, A, module t (input clk, A,
output reg B, C); output reg B, C);
always @(posedge clk) begin always @(posedge clk) begin
B <= A; B = A;
C <= B; C = B;
end end
endmodule endmodule

B
B

A D Q D Q C

DFF DFF A D Q

CLK
DFF C

CLK

61
Procedural Blocks (Summary)
Blocks of code within a procedural block are read (simulated, executed) in order
Procedural blocks may contain:
Blocking assignments
Non-blocking assignments
Procedural control statements ( if , for , case )
function , or task calls

Event control ( @ )
Nested procedural blocks enclosed in begin … end

62
Outline
Lexical elements
Data type representation
Structures and Hierarchy
Operators
Blocks and Assignments
Control statements
Task and functions
Generate blocks

63
Conditional Statements ( if … else )
Statement occurs if the expressions
controlling the if statement evaluates
always @ (WRITE or STATUS)
to true begin
True: 1 or non-zero value if (!WRITE)
begin
False: 0 or ambiguous ( X ) out = oldvalue;
end
Explicit priority else if (!STATUS)
begin
if (<expression>) q = newstatus;
// statement1 end
else if (<expression>) end
// statement2
else
// statement3
64
Conditional Statements ( case )
case , casex , casez : case statements are used for switching between multiple
selections
If there are multiple matches only the first is evaluated
Breaks automatically
casez treats Z as don’t care

casex treats Z and X as don’t care

case (<expression>)
<item1> :<statement1>;
<item2> :<statement2>;
default: <default statement>;
endcase

65
Conditional Statements ( case )
always @(s, a, b, c, d) always @*
case (s) casex (state)
2'b00: out = a; /*
2'b01: out = b; during comparison :
2'b10: out = c; 3'b01z, 3'b01x, 3b'011 ...
2'b11: out = d; match case 3'b01x
endcase */
3'b01x: fsm = 0;
3'b0xx: fsm = 1;
always @* default: fsm = 1;
casez (state) endcase
// 3'b11z, 3'b1zz,... 3'b1??
3'b1??: fsm = 0;
3'b01?: fsm = 1;
endcase

66
Example
module mux(a, b, c, d, s, out); a
input [7:0] a,b,c,d;
input [1:0] s; b
output reg [7:0] out;
// used in procedural statement
8-bit out
c 4-to-1
always @ (s or a or b or c or d)
case (s) mul plexer
2'b00: out = a; d
2'b01: out = b;
2'b10: out = c;
2'b11: out = d;
endcase
endmodule
s[0] s[1]

67
Latches / Muxes (Comb Logic)
Assuming only level sensitivity on an always block:
A variable or signal when is fully specified (it is assigned under all possible
conditions) a mux or combinational logic
If a variable or signal is not fully specified a latch will be inferred

MUX LATCH COMB Logic

always @ (a,b,sel) always @ (DATA, GATE) always @ (DATA,GATE)


if (sel==1’b1) if (GATE) begin
z=a; Q =DATA; Q = 0;
else if (GATE)
z=b; Q = DATA;
end

68
Loop Statements ( for )
Works the same ways as C
Unary increment/decrement is not allowed

for (<loop var init>; <loop var reentry expr>; <loop var update>)
<statement>;

// General purpose loop


interger i;
always @*
for (i=0 ; i<=7 ; i=i+1)
memory[i] = 0;

69
Loop Statements ( while )
Loop execute until the expression is not true

always @*
while(delay)
// Multiple statement groups with begin-end
begin
ldlang = oldldlang;
delay = delay – 1;
end

70
Loop Statements ( repeat )
Repeat statement a specified number of times
Number is evaluated only at the beginning

always @*
repeat(`BIT-WIDTH)
begin
if (a[0])
out = b + out;
a = a << 1;
end

71
Outline
Lexical elements
Data type representation
Structures and Hierarchy
Operators
Blocks and Assignments
Control statements
Task and functions
Generate blocks

72
Tasks and Functions
Task and function serve the same purpose on Verilog as
subroutines do in C

Task Function
Declare with task and endtask Declare with function and
May have zero arguments or more endfunction

arguments of type input , output , Must have at lease one input


inout Always return a single value (cannot
Do not return with a value, can pass have output or inout arguments)
values through output and inout
arguments 73
Tasks and Functions - Example

module top (input a1, a2, output reg [1:0] b1, b2);
always @ (a1, a2)
begin
b1 = out (a1, a2); // Function calling
out_task (a1, a2, b2); // Task calling
end

function [1:0] out (input in1, in2);


begin
if (in1)
out = {in2,in1};
else
out = {in1,in2};
end
endfunction

task out_task (input in1, in2, output [1:0] out);


begin
if (in1)
out = {in2,in1};
else
out = {in1,in2};
end
endtask
endmodule

74
Tasks and Functions
Functions are simpler
Function Task
Can call other function Can call other function or task
Can modify only one value Can modify multiple values

Data Sharing
Functions and task could be declared as automatic
A static function retains the value of all it's internal variables between calls. An
automatic function re-initializes them each call

75
Outline
Lexical elements
Data type representation
Structures and Hierarchy
Operators
Blocks and Assignments
Control statements
Task and functions
Generate blocks

76
Generate Blocks
Allow to generate Verilog code dynamically at elaboration time
Facilitated the parameterized model generation
Required the keywords generate – endgenerate
Generate instantiations can be
Module instantiations
Continuous assignments
initial / always blocks

Typically used are generate loop and conditional generate

77
Generate Loop
module top( input [0:3] in1, genblk1[0].U1
in1 out1
output [0:3] out1); sub
// genvar control the loop
genvar I;
generate in1 genblk1[1].U1 out1
for(I=0; I<=3; I=I+1 ) sub
begin
sub U1 (in1[I], out1[I]); end
endgenerate in1 genblk1[2].U1 out1
sub
endmodule

in1 genblk1[3].U1 out1


sub

in1 out1

78
Conditional Generate
module top #(parameter POS=0)
(input in, clk, output reg out);
generate
if(POS==1)
always @ (posedge clk)
out = in;
else
always @ (negedge clk)
out = in;
endgenerate

endmodule

79
Synthesis Coding Guidelines

80
Synthesis Coding Guidelines
Inferring Three-State Drivers
Never use high-impedance values in a conditional expression (Evaluates
expressions compared to high-impedance values as false)
module synTriState (output reg bus, input in, driveEnable);
always @(*)
if (driveEnable) bus = in;
else bus = 1'bz;
endmodule

Sensitivity Lists
You should completely specify the sensitivity list for each always block.
Incomplete sensitivity lists can result in simulation mismatches
always @ (A)
C <= A | B; 81
Synthesis Coding Guidelines
Value Assignments
Hardware generated by blocking assignments (=) is dependent on the
ordering of the assignments
Hardware generated by non-blocking assignments (<=) is independent of the
ordering of the assignments
For correct simulation results, Use non-blocking assignments within sequential
Verilog always blocks

82
Synthesis Coding Guidelines
Value Assignments
Do not mix blocking and non-blocking assignments in the same always block
Do not make assignments to the same variable from more than one always
block. It is a Verilog race condition, even when using non-blocking
assignments

83
Synthesis Coding Guidelines
If Statements
When an if statement used in a Verilog always block as part of a continuous
assignment does not include an else clause, synthesis tool may create a latch.
Case Statements
If your if statement contains more than three conditions, consider using the
case statement to improve the parallelism of your design and the clarity of
your code
An incomplete case statement results in the creation of a latch

84
Just For Fun
85
Question 1

Can the bit reversal be done by


applying the next assignment?
input [7:0] data;
output [7:0] data_reversed;

data_reversed = data[0:7];

86
Question 1
data_reversed =
Can the bit reversal be done by {data[0], data[1], data[2],
applying the next assignment? data[3], data[4], data[5],
data[6], data[7]};

input [7:0] data;


output [7:0] data_reversed;
input [127:0] data;
data_reversed = data[0:7]; output [127:0] data_reversed;

for (i = 127; i >= 0; i = i - 1)


data_deversed[i] = data[127 - i];

87
Question 2

How we can assign 1'b1 to each


bit?
parameter WIDTH = 4;
output [WIDTH - 1 : 0] data;

88
Question 2
assign data = {WIDTH{1'b1}};
How we can assign 1'b1 to each
bit? assign data = (1 << WIDTH) – 1;

parameter WIDTH = 4;
output [WIDTH - 1 : 0] data;

89
Question 3
Which is the correct macro usage?
`define TEST `define TEST `define TEST
`define SIZE 32 `define SIZE 32 `define SIZE 32

module test (); module test (); module test ();


`ifdef TEST `ifdef TEST `ifdef `TEST
assign out = SIZE{1’b1}; assign out = `SIZE{1’b1}; assign out = `SIZE{1’b1};
`else `else `else
assign out = SIZE{1’b0}; assign out = `SIZE{1’b0}; assign out = `SIZE{1’b0};
`endif `endif `endif
endmodule endmodule endmodule

90
Question 3
Which is the correct macro usage?
`define TEST
`define SIZE 32

module test ();


`ifdef TEST
assign out = `SIZE{1’b1};
`else
assign out = `SIZE{1’b0};
`endif
endmodule

91
Question 4
Which code infer an asynchronous reset FF?
module FFD (input Clk, R, D, module FFD (input Clk, R, D,
output reg Q); output reg Q);
always @ (posedge Clk, posedge R) always @ (posedge Clk)
begin begin
if (R) if (R)
Q <= 1'b0; Q <= 1'b0;
else else
Q <= D; Q <= D;
end end
endmodule endmodule

92
Question 4
Which code infer an asynchronous reset FF?
module FFD (input Clk, R, D,
output reg Q);
always @ (posedge Clk, posedge R)
begin
if (R)
Q <= 1'b0;
else
Q <= D;
end
endmodule

93
Question 5
Is the next module header, correct?
module Adder(input [N-1:0]A, B,
input Cin,
input Clk,
output reg [N-1:0] S,
output reg Cout);
parameter N=8;
//module internals
endmodule

94
Question 5
Is the next module header, correct?
module Adder(input [N-1:0]A, B,
input Cin, No, Parameter is used before it's
input Clk, declration!
output reg [N-1:0] S,
output reg Cout); module Adder #(parameter N=8)
parameter N=8; (input [N-1:0]A, B,
//module internals input Cin,
endmodule input Clk,
output reg [N-1:0] S,
output reg Cout
);
//module internals
endmodule

95
Question 6
What does X mean in synthesis and simulation?

96
Question 6
What does X mean in synthesis and simulation?

Synthesis (Don't Care) Simulation (Unknown)


Assigning X to a wire or reg is highly Be aware, when assigning X ’s they may
encouraged for synthesis: it specifies a propagate throughout your design under
don’t care condition, letting the synthesis simulation.
tool do further optimization.

97
Verilog Testbench

98
Writing Test Bench
Test bench specifies a sequence of inputs to be applied by the simulator to Verilog-
based design
Test bench uses an initial block, delay statements and procedural statement
Verilog has advanced “behavioral” commands to facilitate this:
Delay for n units of time
Full high-level constructs: if, while sequential assignment
Input/output: file I/O, output to display, etc.

99
Test Bench
`timescale 10ns/1ps module DUT (in1, in2, clk, out1);
module test_bench;
// Interface to communicate with the DUT reg a, b, clk; input in1, in2;
wire c; input clk; output reg out1;
// Device under test instantiation
DUT U1 (.in1(a), .in2(b), .clk(clk), .out1(c)); always @(posedge clk)
initial out1 = in1^in2;
begin // Test program
test1 (); endmodule
$finish;
end initial begin
clk = 0;
forever #5 clk = end task test1 ();
initial begin
begin // Monitor the simulation
$dumpvars; a = 0; b = 0;
$display (" clk | in1 | in2 | out1 |"); #10 a = 0; b = 1;
$monitor (" %b | %b | %b | %b |",clk, a, b, c);
end
#10 a = 1; b = 1;
endmodule #10 a = 1; b = 0;
end
endtask

100
Simulation Results

101
Precision Macro
`timescale
Defines the time units and simulation precision (smallest increment)
`timescale Time_Unit/Precision_Unit
Time : 1 10 100
Units: ms us ns ps fs
Precision unit must be less than or equal to the time unit
Example:
`timescale 10ns/1ps

102
Initial Block
Contains a statements or block of statements which is executed only once, stating
at the beginning of the simulation

Each block is executed concurrently before simulation time 0 (ignore by synthesis)

No sensitivity list

initial begin
X = 1’b0;
end

103
Forever Block
Cause one or more statements to be executed in an infinite loop
Example: clock signal generation
initial begin
clk = 0;
forever #5 clk = ~clk;
end

104
Delay
Inter-assignment Delays
#<delay> <LHS> = <RHS>;

Statement is executed after the delay expires (most used).


Specifies the delay in time units.
Intra-assignment Delays
<LHS> = #<delay> <RHS>;

Evaluates all signals on RHS.


Assignment to LHS only after delay expires.
Zero Delay
#0

Ensure that statements are executed at the end of current simulation time. 105
Delay Example
parameter sim_cycle = 6; initial
begin
x = 0;
#10 y = 1; //assignment is delayed 10 time units
#(sim_cycle/3) x = 2; //delay number defined from a parameter value
end
initial begin
p = 0; q = 0;
r = #5 p+q; //Take the value of p and q at time 0, evaluate
//p+q and wait 5 time units to assign value to r
end
initial
begin
#0 x = 1; //x=0,p=0;q=0,x=1 are executed a time 0 but x=1 is
//executed at the end
end

106
Task
Task helps to simplify the test bench
Can include timing control
Inputs
Delays ( # ) and regular event control ( @ )

task load (input [7:0] data, task reset;


input enable); begin
begin rst_n = 1'b0;
#2 rst_n = 1’b0; repeat(3) @(negedge clk);
#10 data_in = data; rst_n = 1'b1;
#2 read_ena = enab; end
end
endtask

107
Hierarchical Names
Hierarchical name references allows us to denote every identifier in the design with
a unique name
Hierarchical name is a list of identifier separated by dots (“.”)

TB (U1) module TB ();


//...
SUB1 $monitor (“%b”, TB.U1.U1.mem);
(U1)
$monitor (“%b”, TB.U1.U2.data);
SUB2.1
reg mem; endmodule

(U2)
SUB2.2
wire data;

Syn
108
System Tasks and Functions
System task are tool specific tasks and functions.
$display, $write, $monitor // utilities to display information
$time, $realtime // current simulation time
$finish // exit the simulator
$stop // stop the simulator
$timeformat // format for printing simulation
$random // random number generation
$dumpvars // dump signals to file

109
$display - $strobe - $monitor
Print message to a simulator (similar to C printf)

$display (format, args)

Display information before RHS evaluation (before non-blocking assignments)

$strobe (format, args)

Display information after RHS evaluation (after non- blocking assignments)

$monitor (format, args)

Print-on-change after RHS and non-blocking assignments whenever one argument


change
110
Verilog String and Messages
initial
begin
$display (“Results\n”);
$monitor (“\n Time=%t X=%b”, $time , X);
end

Useful format specifiers:


%h hex integer %t simulation time
%d decimal integer %u 2-value data
%b binary %z 4-value data
%c single ASCII character %m module instance name
%s character string
111
$random
Random number generation
Returns as 32-bit signed integer

reg [31:0] rand1, rand2, rand3;

rand1 = $random; // generates random numbers


rand2 = $random %60; // random numbers between -59 and 59
rand3 = {$random} %60; // random positive values between 0 and 59

112
$dumpvars
Verilog $dumpvars command is used to generate a value change dump (VCD)
VCD is an ASCII file that contains information about simulation, time, scope and
signal definition, and signal value changes
VCD files can be read on graphical wave from displays

initial
begin // Monitor the simulation
$dumpfile ("myfile.dump");
$dumpvars;
end

113
Test Bench
`timescale 10ns/1ps module DUT (in1, in2, clk, out1);
module test_bench;
// Interface to communicate with the DUT reg a, b, clk; input in1, in2;
wire c; input clk; output reg out1;
// Device under test instantiation
DUT U1 (.in1(a), .in2(b), .clk(clk), .out1(c)); always @(posedge clk)
initial out1 = in1^in2;
begin // Test program
test1 (); endmodule
$finish;
end initial begin
clk = 0;
forever #5 clk = end task test1 ();
initial begin
begin // Monitor the simulation
$dumpvars; a = 0; b = 0;
$display (" clk | in1 | in2 | out1 |"); #10 a = 0; b = 1;
$monitor (" %b | %b | %b | %b |",clk, a, b, c);
end
#10 a = 1; b = 1;
endmodule #10 a = 1; b = 0;
end
endtask

114
References
Verilog HDL – Samir Palnitkar
HDL Compiler™ (Verilog) Reference Manual – Synopsys ®
The Fundamentals of Efficient Synthesizable Finite State Machine Design using NC-
Verilog and Build Gates – Clifford E. Cummings
Verilog: Frequently Asked Questions, Springer Science
Verilog: Frequently Asked Questions: Language, Applications and Extensions -
Shivakumar S. Chonnad, Needamangalam B. Balachander
ECE 369 - Fundamentals of Computer Architecture
http://www2.engr.arizona.edu/~ece372_spr04/e ce369_spr05
Madhavan, R., Quick Reference for Verilog HDL
http://www.stanford.edu/class/ee183/handouts. shtml 115

You might also like