Verilog HDL
Verilog HDL
Verilog HDL
Workshop Goal
2
Workshop Prerequisites
3
The Verilog® Language
4
Course Outline
Day 1
• Lexical Conventions
• Module anatomy
• Port declarations
• Module instances
• Data types
• Nets, registers, parameter
• Procedural blocks
• Timing
• controls, event queue
• Blocking/Non blocking Proc.
• Operators
Day 2
• Programming statements
• Task & Functions
• Verilog for Test
• X & Tri-State Buffers
• Gate-level Modeling
• Finite State machines
5
Day 1
What is a Hardware Description Language?
• Concurrency:
– The ability to do several things simultaneously
• i.e. different code-blocks can run concurrently
• Timing:
– Ability to represent the passing of time and sequence events
accordingly
A powerful feature of the Verilog HDL is that you can use the same
language for:
• Describing Design (RTL/Behavioral)
• DescribingTestbench
• Simulation
• Synthesis
• Netlist Output
7
Synthesize or Simulate?
8
Simulation Environment
control
commands
INPUT OUTPUT
Feedback
9
What is Synthesis?
Verilog code:
Generic
always @ (A or B or C) Translation Boolean
begin (& syntax-check)
case (1’b1) (GTECH)
A: result = 2’b00; netlist
B: result = 2’b01;
C: result = 2’b10;
default: result = 2’b00;
endcase
end Optimization
Constraints & Target Library
Mapping
Target
Synopsys Technology
HDL-synthesis
Toolset
Netlist
10
Basic Modeling Structure
11
An Example
12
VCS
VCS stands for Verilog Compiled Simulator
13
Running the Simulator - VCS
vcs -help lists compile options, runtime options, environment variables
Basic invocation:
vcs file1.v file2.v file3.v … fileN.v
simv Verilog executable generated by VCS
14
LEXICAL CONVENTIONS
15
White Space
White space is used to separate words and to enhance readability:
• Verilog is a free format language
• White space characters are spaces, tabs, carriage returns, etc
• Verilog ignores these characters except when they separate language
tokens
input a,b,c;
input a, b, c;
input a, b,
c;
c=a;
c=b;
16
Comments
Single line comments:
• Begin with "//" and end with a carriage return
• May begin anywhere on the line
Multiple line comments:
• Begin with "/*" and end with a "*/"
• May begin and end anywhere on the line
• Everything in between is commented out
module pound_one;
reg [7:0] a,a$b,b,c; // register declarations
reg clk;
initial
begin
clk=0; // initialize the clock
c = 1;
forever #25 clk = !clk;
end Coding style tip - Use single
/* This section of code implements line comments for comments.
a pipeline */ Reserve multi-line comments
always @ (posedge clk)
begin for commenting out a section
a = b; of code.
b = c;
end
endmodule
17
Strings
• Strings are enclosed in double quotes and are specified on one line
• Verilog recognizes normal C escape Characters (\t, \n, \\, \",%%).
(prints: tab, new line, \ , “ , %)
Examples:
“String”
19
Escaped Identifiers
Examples
\ab#~*this=or=that
\5-6
\bus_a[0]
\bus_a[1]
20
Case Sensitivity
Examples
module // keyword
Module // unique identifier but not keyword
MODULE // unique identifier but not keyword
Silly example:
module MoDule (mODULE, modulE); //terrifying, but legal J
input mODULE;
output modulE…
...
endmodule
21
Logic values
22
Integers & Real Numbers (1/2)
• Verilog numbers may be integers or real numbers
• Integers may be sized or unsized:
Syntax: <size>'<base><value>
where:
<size> is the number of bits
<base is b or B (binary), o or O (octal), d or D (decimal), h or H (hex)
<value> is 0-9 a-f A-F x X z Z ? _
Examples: 2'b01, 6'o243, 78, 4'ha,
• Default radix is decimal:
1 32'd1
• underscores ( _ ) are ignored (use them as you would commas):
836_234_408_566_343
• a "?" is interpreted as Z (high impedance):
2'b?? 2'bzz
• When <size> is less than <value> - the upper bits are truncated:
2'b101 2'b01, 4'hfcba 4'ha
23
Integers & Real Numbers (2/2)
• When <size> is greater than <value>, and the left-most bit of <value> is 0 or 1, then
zero's are extended to <size> bits:
4'b01 4'b0001, 16'h0 16'h0000
4'b11 4'b0011, 16'h1 16'h0001
• When <size> is greater than <value>, and the left-most bit of <value> is an x then the
x value is extended to <size> bits:
4'bx1 4'bxxx1, 16'hx 16'hxxxx
• When <size> is greater than <value>, and the left-most bit of <value> is a z then the z
value is extended to <size> bits:
4'bz1 4'bzzz1, 16'hz 16'hzzzz
24
Integers & Real Numbers Examples
25
System tasks & functions Ignored
Specific tasks and functions may be defined by EDA vendors and users to be
used as part of the simulator:
• Begin with the dollar sign ( $ )
• The Verilog standard has a number of standard $ defined
• Users may define their own built in tasks using the Programming
Language Interface (PLI)
26
MODULE
module name (port_names);
procedural blocks
continuous assignments
primitive instances
module instances
specify blocks
endmodule
27
Verilog Module
module name (port_names);
continuous assignments
endmodule
module COUNTER (cout, clk, rst) ;
…
…
…
endmodule
28
Module Port Declarations
Scalar (1bit) port declarations:
port_direction port_name, port_name ... ;
29
Module Instances
Synthesizes
• A module may be instantiated within another module
• There may be multiple instances of the same module
TOP
• Ports are either by order or by name
• Use by order unless there are lots of ports
• Use by name for libraries and other peoples code (may A A
change)
• Cannot mix the two syntax's in one instantiation
B
30
Example: Module Instances
module half_adder (sum, a, b); module register (data_out, data_in, clk, resetn);
output [8:0] sum; output [8:0] data_out;
input [8:0] a,b; input [8:0] data_in;
input clk,resetn;
assign
sum=a+b; reg [8:0] data_out;
endmodule
always @(posedge clk or negedge resetn)
if (!resetn) out<=0;
else out<=in;
endmodule
32
Exercise
33
Answer
endmodule
34
Data Types
syntax:
data_type identifier, identifier... ;
or
data_type [msb:lsb] identifier, identifier ... ;
35
Nets
• Connect devices
• Are continuously driven by the device that drives them
• New values are propagated automatically when the driver changes
Examples
wire a,b; // scalar wires
wor [7:0] in_bus; // wired-OR bus
wand [8:31] out_bus; // wired and bus
36
Registers
• Variables in Verilog
• Represents storage devices
• Not necessarily represents flip-flop or latches
Equivalent to:
reg [3:0] status;
initial status = 4’b0;
37
Memories
syntax:
reg [msb:lsb] identifier [first_addr:last_addr] ;
where
msb:lsb determine the width (word size) of the memory
first_addr:last_addr determine the depth (address range) of the
memory
mem
255
reg [15:0] mem [0:255]; // 256x16 memory
reg [0:31] mem_a [1023:0]; //1kx32 memory
0
15 0
38
Accessing Memories
Prior to Verilog 2001 a bit or subrange of a location in the array could not
be accessed directly, a temporary variable had to be used.
temp = mem[33]; // data_reg gets data at addr 33
3_bit_reg = temp[8:6]; //get three bits of addr 33
mem
255
temp 3_bit_reg
8 6 2 0
8 6
33
0
15 0
Verilog 2001 finally corrects this: 3_bit_reg = mem[33][8:6];
“address”
dimensions “data”
first (in order) dimensions
(slicing) last
39
Memories – Any-dimension Remember “ +v2k ” at invocation.
“address”
Addressing Multi-dim arrays: dimensions
first (in order)
reg [15:0] D3 [1023:1020] [15:8] [7:3] [2:0]; // 4x8x5x3 array of 16-bit reg’s
initial begin
D3 [1023] [15] [7] [2] = 16’hFFFF; // store: ffff
D3 [1023] [15] [7] [2] = D3 [1023] [15] [7] [2] –1; // decrement: fffe
$display(“%h”, D3 [1023] [15] [7] [2] [7:0] ); // print: fe
end
“data”
dimensions
(slicing) last
40
Indexed vector part-selects
Bit-selects in verilog expressions may use variables:
reg [63:0] data;
reg data_bit;
reg [7:0] data_byte;
integer bit_sel;
initial begin
data = 32;
bit_sel = 5;
data_bit = data[bit_sel];
New Syntax
41
parameters Synthesizes
Parameters:
• Run-time constant
• Used anywhere a literal may be used
• For synthesis, must be defined before being used
• Size [msb:lsb] is finally supported by Verilog 2001
syntax:
parameter <[msb:lsb]> identifier = value <, identifier = value ...> ;
examples:
parameter [2:0] a = 1; // 3-bit
parameter // default 32-bit
depth = 32,
width = 8;
42
Parameter redefinition
In-Line explicit:
module_name # (.parameter_name(value)) instance_name (signals);
43
Explicit Redefinition example
module fifo (d_in, d_out, write, read, full, empty); //module definition
. . .
parameter depth = 32; //parameter. set default depth of 32
. . .
endmodule
fifo_64 fifo_128
44
Redefinition example (inline-explicit)
module fifo (d_in, d_out, write, read, full, empty); //module definition
. . .
parameter depth = 32; //parameter. set default depth of 32
. . .
endmodule
top
fifo_64 fifo_128
45
Exercise
46
Answer
parameter width = 4;
endmodule
47
Using the ports of a module Synthesizes
go
clk out out
rst
48
Port Connection Rules
module
reg
reg -or- net
net
-or- net
net tri tri
Inputs:
• Internally must be of net data type (e.g. wire)
• Externally the inputs may be connected to a reg or net data type
Outputs:
• Internally may be of net or reg data type
• Externally must be connected to a net data type
Inouts:
• Internally must be of net data type (tri recommended)
• Externally must be connected to a net data type (tri recommended)
49
Combined port/type declarations
50
ANSI style port declarations
Port declarations can also be made within the parentheses of the module declaration.
Throughout the rest of this class we will mix ANSI/non-ANSI for illustration.
51
Exercise
52
PROCEDURAL BLOCKS
53
Procedural Blocks
54
Sequential Blocks
n Sequential Blocks
l Statements in a sequential block are processed in the
order they are specified
l A statement is executed only after its preceding statement
completes execution (except for non-blocking
assignments)
l If delay or event control is specified it is relative to the
simulation time, i.e. execution of the previous statement
55
Parallel Blocks
n Parallel Blocks
l Statements in a parallel block are executed concurrently
l Ordering of statements is controlled by the delay or event
control assigned to each statement
l If delay or event control is specified, it is relative to the
time the block was entered
56
Comparison of Sequential & Parallel Blocks
57
initial Statement
• initial block starts at time 0, executes exactly once during a simulation,
and then does not execute again
• In case of multiple initial blocks, each block starts to execute concurrently
at time 0
• Each block finishes execution independently from other blocks
module stimulus;
reg x,a,b;
initial
begin
#5 a = 1'b1; //multiple statements; need to be grouped
#25 b = 1'b0;
end
endmodule
58
always Statement
• always statement starts at time 0 and executes the statements in the
always block continuously in a looping fashion
• This statement is used to model a block of activity that is repeated
continuously
• An example is a clock generator module that toggles the clock signal
every half cycle
endmodule
59
Fork-Join Statements Synthesizes
reg x, y;
reg [1:0] z, w;
initial
fork
x = 1'b0; x completes at simulation time 0
#5 y = 1'b1; y completes at simulation time 5
#10 z = {x, y}; z completes at simulation time 10
#20 w = {y, x};
join w completes at simulation time 20
60
Procedural statement groups
When there is more than one statement within a
procedural block the statements must be grouped.
61
Timing Controls (procedural delays)
#5 reg_a = reg_b;
Synthesizes
@ (edge signal) - edge-triggered timing control:
Delays execution until a transition on signal occurs.
edge is optional and can be specified as either posedge or negedge.
Several signal arguments can be specified using the keyword or.
62
Simulation Time & Event Queues
t+1
t+2
t+3
63
Zero time loops
t+1
64
"Deadlocks"
65
Procedural assignments Synthesizes
66
Blocking Assignments Synthesizes
initial Time
begin
a = b; a<-b(t) t
Event Queues c<-d(t) t’ t
c = d;
e = f; e<-f(t) t’’
end t+1
t+2
t+3
<-- Execution order
67
Delayed Blocking assignments
68
Delayed Blocking assignments
69
Blocking Intra-procedural delayed assignment
71
Quiz
Assume b = 3 and c = 5
After the first @ (posedge clk)
what is the value of a?
72
Quiz
73
Non-blocking Assignments Synthesizes
74
Race solved!
75
Swap Accomplished!
76
Mixed Blocking and Non-blocking
Synthesizes
initial
begin Event Queues Time
a = b; c<-d(t) c<-f(t) a<-b(t) t
c <= d; t+1
c = f;
end t+2
t+3
DON’T DO!! <-- Execution order
Synthesis Tip!
The mixing of blocking and non-blocking assignments in a
procedural block is not allowed for synthesis.
77
Delayed Non-blocking Assignments
78
Non-blocking Intra-procedural delayed
Assignments
79
Non-blocking Intra-procedural delayed Assignments
initial
begin
a <= #1 b; Event Queues Time
c <= #1 d;
e <= #1 f; t
end e<-f(t) c<-d(t) a<-b(t) t+1
t+2
t+3
<-- Execution order
80
Procedural blocks Synthesis Tips!
Synthesis Tip!
Use blocking assignments for combinational always blocks
and do not use delays...
Example
always @(dat)
i_dat = ~dat;
#5 a = `FALSE; #5 a= b;
#5 b = 42;
#5 c = c+1; // inc/decrement of values
82
Quiz
83
Rules of Thumb - 2
Synthesis Tip!
Use non-blocking assignments exclusively for sequential always blocks.
Adding a RHS delay, produces an ‘intuitive’ transport delay in simulation
and makes waveforms easier to read.
Example
always @(posedge CLK)
Q <= #1 D;
Examples #5 a <= b;
a <= #5 b; // where b is a register
c <= #5 d; // where d is a wire
The procedural delay (#) on the RHS best models propagation delay as an
engineer understands it.
84
Event Control
85
Assignments and Synthesis (1) Synthesis Tip!
86
Assignments and Synthesis (2) Synthesis Tip!
87
OPERATORS
88
Lexical Conventions: Operators
n Operators
l Unary operators
u stand before the operand
l Binary operators
u stand between two operands
l Ternary operators
u have two separate operators that separate three operands
89
Operators
Arithmetic +,-,*
Other arithmetic /,% Synthesizes
HDLC 2000+
Verilog 2001
Power **
Synthesizes
Presto 2000+
Bitwise ~, &,|,^,~^
Unary reduction &,~&,|,~|,^,~^
Logical !,&&,||
Equality ==,!= (0,1)
Identity ===,!== (0,1,x,z) Synthesizes
Relational <,>,<=,>=
Logical shift <<,>>
Conditional ?:
Concatenate {}
Replicate {{}}
90
Examples of Operators
reg [3:0] r1, r2, r3;
reg aa, bb;
initial begin
r1 = 4'b0101;
r2 = 4'b1100;
end
// Bitwise operators:
r3 = r1 & r2; // AND each bit of r1 with r2 (4'b0100)
r3 = r1 ^ r2; // Excl-OR each bit of r1 with r2 (4'b1001)
// Note: hi-impedance (z) bits are treated as if they were unknown (x)
// Logical operators: ‘0’ if all bits are zero, ‘1’ if any bits are non-zero
aa = r1 && r2; // 1-bit result of AND’ing logical values (1 or true)
bb = ! r2; // 1-bit result, the invert of logical r2 (0 or false)
91
Examples of Operators (cont’d)
{aa, bb, r1} = { { 2 { 1’b0 }}, r2 >> 2 }; // Replicate, right-shift & concatenate
// left / right shift zero fills
// ( aa == 0, bb == 0, r1 == 0011 )
92
Examples of Operators (cont’d)
reg [3:0] r1, r2, r3, r4, r5;
reg aa, bb, gate ;
Conditional:
r1 = gate ? r2 : r3; // gate selects between r2 or r3
// syntax: LHS = sel ? (sel == true) : (sel == false);
// synthesizes into MUX logic
Nested Conditional:
r1 = (aa == 0 ) ? ( (bb == 0) ? r2 : r3) : r4;
or
r1 = {aa,bb} == 0 ? r2 :
aa bb one
{aa,bb} == 1 ? r3 :
0 0 r2
{aa,bb} == 2 ? r4 : r4; 3:1 0 1 r3
1 0 r4 4:1
1 1 r5
QUIZ: Convert this 3:1 MUX to a 4:1 MUX (see table)
93
Signed Arithmetic
Synthesizes
94
Bit lengths resulting from expressions
reg[3:0] A,B;
reg[2:0] C;
95
Operator Precedence
96
Example: Putting it all together
ADDER
16
in_1
+
16
add_out
16
in_2
endmodule
97
Day 2
Rules Of Thumb
R.O.T #1
Example
always @(a) a b
b = a;
R.O.T #2
99
Rules of Thumb - 0
• Be Consistent!
100
PROGRAMMING STATEMENTS
101
Programming Statements
102
if and if-else Synthesizes
syntax:
if(expression) statement
If the expression evaluates to true then execute the statement (or
statement group).
if(expression) statement1
else statement2
If the expression evaluates to true then execute statement1,
if false, then execute statement2 (or corresponding statement groups).
103
Nested if-else-if
104
case Synthesizes
syntax:
case (expression)
case_item_1: statement or statement_group
case_item_2,
case_item_3: statement or statement_group Priority encoding
case_item_n: statement or statement_group
default: statement or statement_group
endcase
• Does an identity comparison (but only simulation will match x, z)
• Compares expression with each case_item_(n) in turn
• If none match, the default code is executed
• Default clause is ideal to catch unknown/unspecified values
reg [2:0] reg_a, reg_b;
always @ (posedge clk)
case (reg_a)
3'b000: begin
reg_b <= 0; Begin end needed around
reg_c <= 0; multiple sequential
end statements.
3'b001: reg_b <= 1;
3'b010, // this branch does reg_b <= 3;
3'b011: reg_b <= 3; Comma means OR
default: reg_b <= 5;
endcase
105
casez, casex
Synthesizes
• casez - special version of case that allows the Z logic value in the
case-items (z or ? treated as a don’t care).
Coding style tip - to save confusion use " ? " as the don't care indicator.
106
Understanding case - 1
107
Understanding case - 2
108
x’s in Synthesis
Remember: Simulation & Synthesis interpret “X” differently:
Simulation - unknown, Synthesis - don’t care.
case (a)
2'bxx: c = 3; // This branch won't occur in synthesis
default: c = 4;
endcase
109
‘case’ and Synthesis
• In Simulation, case (and if-else) statements are priority encoded
• You can affect the decision by embedding compiler directives in your code
(comments appearing after the case declaration)
Example:
NOT RECOMENDED case (reg_a) // synopsys full_case parallel_case
4’h0: b = c;
...
// synopsys full_case - All possible clauses have been coded. No default clause necessary
This is similar to (but not as good as) using a default clause.
- Because it is not Verilog compatible, use default instead.
// synopsys parallel_case - Do not produce priority encoded logic (and so save some gates).
110
Which to use: case or if-else?
Synthesis Tip!
111
Inferred Storage Device Report Synthesis Tip!
===============================================================
| Register name | Type | Width | Bus | AR | AS | SR | SS | ST |
===============================================================
| out | latch | 8| - | - | - | - | - | - |
===============================================================
112
Inferred latches in Synthesis
Synthesis Tip!
Latches can be accidentally inferred from Verilog RTL code.
An example:
When using if - else and case all possible “logic paths” must be specified or else storage
devices are inferred.
113
Avoiding Inferred latches
Synthesis Tip!
Specify all case/if structures thoroughly!:
• Every if has an else, every case has a default
• All output signals must be assigned in every branch
- OR -
always @(sel or a)
begin
out = 1’b1;
if(sel) // no else is no problem now!
out = a;
end
endmodule
114
Example: D Flip-flop
module FF (Q, CLK, RST, D); module FF (Q, CLK, RST, D);
output Q; output Q;
input CLK, RST, D; input CLK, RST, D;
reg Q; reg Q;
endmodule endmodule
115
forever Not recommended
for synthesis
syntax:
forever statement or statement_group
• statement or statement_group is continuously executed
• An infinite loop
• Make sure time advances, or zero-time loops will happen!
• In synthesis, make sure the loop contains an edge-triggered timing
control i.e. @(posedge clk) or @ (negedge clk)
module clock_gen;
reg clk;
initial
begin
clk = 0;
forever #25 clk = !clk; //50 time step clock
end
endmodule
116
repeat Synthesizes
syntax:
repeat (expression) statement or
statement_group
• statement or statement_group is executed expression number of times
117
while Synthesizes
syntax:
while (expression) statement or
statement_group module while_ex (input wire clk,
input [1:0] wire a,b,
output [1:0] reg c);
• statement or statement_group is
continuously executed as long as always
expression evaluates true (or non zero) begin
@ (posedge clk)
• Beware of zero-time loops! They can while (c < b)
occur if both time is not advancing and @ (posedge clk)
expression never goes false c = c + a;
end
endmodule
• In synthesis, the loop must contain an
edge-triggered timing control, i.e.
@(posedge clk) or @ (negedge clk)
118
for Synthesizes
syntax:
for (assignment_init; expression; assignment)
statement or statement_group
119
Ever see a hardware for? Synthesis Tip!
Design Compiler® simply unrolls the loop... module for_ex3(input wire start_cnt,
output reg [7:0] cnt);
module for_ex2(input wire start_cnt, integer i;
output reg [7:0] cnt); reg [7:0] vec;
unrolls
integer i; into
reg [7:0] vec; always @ (start_cnt)
this
begin
always @ (start_cnt) if (vec[0] == 1'b0)
for (i = 0; i <= 3; i = i+1) cnt = cnt + 1;
if (vec[i] == 1'b0) if (vec[1] == 1'b0)
cnt = cnt + 1; cnt = cnt + 1;
endmodule if (vec[2] == 1'b0)
cnt = cnt + 1;
if (vec[3] == 1'b0)
cnt = cnt + 1;
You can not re-assign the loop variable from end
within the for loop. It’s supposed to be a constant! endmodule
120
Naming Statement Groups Synthesizes
:group_name
always
begin :mikes_block // group_name
a = 1;
b = b + 1;
end
121
disable Synthesizes
syntax:
disable group_name
• Execution of the named group of statements is stopped and all
associated scheduled events are removed from the event queues
always
begin: do_stuff
forever @(posedge clk) For synthesis, it must be in the
begin same named block that it disables.
if (done) // is it done?
begin
$display($time,,"disabling block");
disable do_stuff; // stop doing it
end
#5 a = !a; // stuff to do
end
end
122
Sensitivity lists
• A sensitivity list allows you to monitor any change in the inputs for a procedural
block
• Procedural blocks with sensitivity lists can model combinational logic
• Beware of incomplete sensitivity lists
Synthesis Tip!
module sense_list_ex(b,c,d); Design Compiler derives it’s own sensitivity
input b,c,d; lists and issues a warning message if this
does not match your code:
reg a;
always @ (b or c or d) “Signal being used but not in timing control”
if (b) Warning!
a = c && d;
else if (c) If you don’t update/correct your RTL source,
a = d; this will cause your RTL and gate level
simulation results to mismatch!
endmodule
RULES:
Combinational sensitivity lists should include:
Quiz: 1) Any signal on right hand side of an assignment.
Why will this code infer a latch for "a" 2) Any signal in an “if” or “case” expression.
123
Sensitivity lists and Verilog 2001
reg a;
always @ // NOTE: no space after @ • Wildcard sensitivity lists
*
if (b)
a = c && d;
else
a = d;
endmodule
124
Continuous Assignments Synthesizes
Examples
wire a;
wire [7:0] c;
assign a = (c_state == `IDLE ) && (sig2 || sig1);
assign c = bus_valid ? d : 8'hz; // tri state bus
125
Implicit Continuous Assignments
Synthesizes
Examples
reg [7:0] d;
wire [7:0] e = d & 8'b00001111;
wire b = d; // what happens here?
126
Example: Adder
ADDER
16
in_1
+
16
add_out
16
in_2
endmodule
127
Transport Delay (Glitch Catcher) module glitch_catcher;
reg [3:0] a,b;
always @ (b)
a <= #3 b;
initial
begin
b = 0;
#4 b = 1;
#2 b = 2;
#2 b = 3;
#2 b = 4;
#10 $stop;
end
endmodule
a XXX 0 1 2 3 4
b 0 1 2 3 4
time
1 2 3 4 5 6 7 8 9 10 11 12 13
Coding style tip - The best way to model combinational logic with transport delay is with
an always block with a sensitivity list and non-blocking assignments as shown above.
128
Inertial Delay (Glitch Swallower) module glitch_swallow;
wire [3:0] a;
reg [3:0] b;
initial
begin
b = 0;
#4 b = 1;
#2 b = 2;
#2 b = 3;
1. Change on RHS #2 b = 4;
2. Delay #10 $stop;
end
3. Evaluate RHS & update LHS assign #3 a = b;
endmodule
a XXX 0 4
b 0 1 2 3 4
time 1 2 3 4 5 6 7 8 9 10 11 12 13
Coding style tip - The best way to model combinational logic with inertial delay is with
net data type and a continuous assignment as shown above.
129
TASK & FUNCTION
130
User Defined Tasks
Synthesizes
syntax:
task name_of_task;
input, inout, and output declarations
local variable declarations
statement or statement_group
endtask
131
Example Task & Call
module call_task;
reg [31:0] into, add, dat;
Task reg sel;
Definition // clk logic not shown
task write_wd;
input [31:0] addr, data;
output sel;
begin
into = {4'b0010,28'h0};
@ (posedge clk) #5 into = addr;
@ (posedge clk) #5 into = data;
sel = 0; // clear sel call_task
end into
endtask write_wd
add addr
initial dat data
begin sel sel
add = 100;
Example dat = 123;
task call sel = 1; clk
132
Example Test fixture - test_pipe.v
module test_pipe;
reg clk;
reg [7:0] d_in;
wire [7:0] d_out;
integer i; /*** module instantiation ***/
initial pipe pipe_1 (
begin d_in,
clk = 0; // init clk
d_in = 0; // init d_in d_out,
forever #20 clk = ~clk; // 40 time step clock clk
end );
task single; // send a single word through the pipe endmodule
input [7:0] data;
begin
d_in = data;
@ (negedge clk) d_in = 0; // clear the pipe
end
endtask
task burst; // send n words through the pipe
…
endtask
initial //testing sequence
begin
#10 // get clear of time=0
@ (negedge clk) single(4); // send one word through
repeat (4) @ (negedge clk); // wait to clear
burst(10); // send through 10
repeat (4) @ (negedge clk); // wait to clear
burst (3); // send through a partial burst Note: For clarity, some testbench code has
repeat (4) @ (negedge clk); // wait to clear been omitted from this slide.
for (i=1; i<9; i=i+1)
@ (negedge clk) // skip one clock
single (i); //send a word
#500 $stop; // wait to clear then stop
end
133
User-Defined Functions Synthesizes
syntax:
function <[ signed ][ size or type ]> name_of_function;
input declarations
local variable declarations
statement or statement_group
endfunction
• signed is optional and indicates returned value is 2’s compliment (signed) value
• size is optional and is of form [msb:lsb]
• type is optional and is either integer or real
• Returns the value assigned to the name of the function
• Functions may not contain timing controls (incl. non-blocking procedural assignments)
• Functions must have at least one input
• Looks local first then global to module for referenced variables
• Functions may be called:
– within a continuous assignment e.g. assign b = func(a);
– indirectly within an instantiation e.g. mod U1 (one, func (a, b) );
– nested within another function
134
Function - Example
`define FALSE 0
`define TRUE 1
module function_ex (clk);
input clk;
reg r1,r2,r3;
135
Functions in Synthesis Synthesis Tip!
136
VERILOG FOR TEST
137
System Task & Functions
Specific tasks and functions may be defined by EDA vendors and users to be
used as part of the simulator:
• Begin with the dollar sign ( $ )
• The Verilog standard has a number of standard $ defined
• Users may define their own built in tasks using the Programming
Language Interface (PLI)
138
$display, $monitor & $strobe
$display();
TIP: You can print your instance name as part of a message
$display ($time,“%m Out_reg = %b”, out_reg);
$monitor();
– outputs whenever a (non-$time) variable it references changes
– Note: only one $monitor can be active at a time
$monitor ($time,“Out_reg = %b”, out_reg);
$strobe();
– like $display, but waits until end of time step
139
$stop and $finish
initial initial
begin begin
a = 0; a = 0;
b = 1; b = 1;
… …
… …
#1000 $stop; #1000 $finish;
end end
endmodule endmodule
140
Compiler directives
`define tpd 5
module test_designA;
. . .
initial
#`tpd c = 0;
141
`timescale Compiler directive
Time scales establish the delay time base and precision in Verilog models.
time_unit base: sets the time unit for 1 time step i.e.. What a delay
of 1 means
time_precision base: sets the precision i.e. how to round delays
Example
`timescale 1 ns / 100 ps time unit is 1 ns and round to the nearest .1ns
142
Compiler directives example: `include
module A ( ); module B ( ); module C ( );
parameter parameter parameter
Width = 5, Width = 5, Width = 5,
Depth = 10, Depth = 10, Depth = 10,
Height = 20; Height = 20; Height = 20;
… … …
… … …
endmodule endmodule endmodule
param.inc
parameter module A ( ); module B ( ); module C ( );
Width = 5, `include param.inc; `include param.inc; `include param.inc;
Depth = 10, … … …
Height = 20; … … …
endmodule endmodule endmodule
143
“`define” and “`ifdef” for code modification
File: test_choices
`define TRUE 1
`define DISPLAY_ERRORS 0
`define FULL_CHECK `TRUE
`define RANDOM
File: testbench.v
if (`FULL_CHECK) do_all_tests;
`ifdef RANDOM
initial addr = $random(seed) * 43;
`else
initial addr = addr +1;
`endif
144
Options for (re)defining a text macro
Define
Text macros may be defined from the command line. The following invocation line defines the
text macro TRUE.
vcs -R my_module.v +define+TRUE=1+
This would be equivalent to having the statement
`define TRUE 1
in the module my_module in the file my_module.v
Redefine
`define directives within a module can be overridden from the command line
Given the following line of code was in the module my_module in the file my_module.v:
`define TRUE 1
The following invocation line overrides the value of 1 for TRUE with 0 for this simulation:
vcs -R my_module.v +define+TRUE=0+
145
Initializing Memories Synthesizes
Or they may be initialized with a file using built-in system tasks: $readmemb / $readmemh which
read ASCII text files specifying data in binary/hex representation.
syntax:
$readmem<base>("file_name",memory_name );
$readmem<base>("file_name",memory_name,<start_address>,<finish_address> );
// there is also a corresponding command for dumping the contents of a memory to a file
$writememh("hex.dat", mem); // write file hex.dat from memory mem
$writememh(“hex2.dat", mem1, 16, 0); // write file hex2.dat starting at address 16, down to 0
end
146
Memory Image Files Synthesizes
ab
ae File is read sequentially
af starting at left address in
memory declaration.
00
- OR -
ab
ae Hex addresses may be specified
af so that the file is still read
00 sequentially.
@1ff
ab - BUT -
ae starts loading at address 1ff.
af - AND THEN -
@2ab jumps to address 2ab etc... Note:
00
03 • Comments are allowed!
00 • Use hex addresses only
af • Uninitialized locations are left “X”
147
Scoping
instance names module name
top
instance names
b c d
mega
h
e f g
giga i
module flop
.... module names
reg float; // local register k
flop
....
endmodule
syntax:
force net_or_register = expression;
release net_or_register;
• On the release of a register data type the register retains its "forced
value" until it is over written
• On the release of a net data type the net immediately takes on the
value of its driver
149
force & release example
module test_force;
reg clk;
reg [7:0] d,q;
wire [7:0] w;
initial begin // generate a clock
clk = 0;
forever #25 clk = !clk;
end
initial
for(d = 0;d < 256;d=d+1) @ (negedge clk); //create incrementing value for d
always @ (posedge clk)
q <= d; // normal operation for q
assign w = d; // normal operation for w
initial
begin
#100 force q = 8'hff; // force to all 1's
$display ("%0d force applied to q",$time);
#200 release q; // release the force, q stays 8'ff until the next assignment to q is made
$display ("%0d release of q",$time);
#100 force w = 8'hff; // force to all 1's
$display ("%0d force applied to w",$time);
#200 release w; //release the force, w changes value immediately to the current value of d;
$display ("%0d release of w",$time);
#100 $finish;
end
initial $monitor ("%0d d = %h, q = %h, w = %h",$time,d,q,w);
endmodule
150
Uses of force & release
Note:
A force statement in the model itself is more efficient than
one entered at the command line and doesn’t need the +cli switch
151
Bus Monitor tasks
152
Simple Bus Monitor Example
CPU Memory IO
System Bus
bus_check.v
Bus always @ (posedge clock)
Check
if (arb[1] && idle && not_ready)
// error!
153
Writing to a file
154
Write to a file example
module dcm(clk,bus_error_flag,stat_var);
input clk,bus_error_flag,stat_var;
integer errfile;
initial
errfile = $fopen("error_output");
endmodule
155
X & TRI-STATE BUFFERS
156
z’s in Synthesis
reg [1:0] a;
case (a)
2’b01: c = 2;
2'bzz: c = 3; // This branch won't occur in synthesis
default: c = 4;
endcase
157
Tri-state buffer inference
endmodule
Remember to make sure sel1 and sel2 never happen at the same time.
158
Tri-state buffer on the output of a flip-flop
clk
endmodule
159
Tri-state buffer on the Output of a flip-flop
module bidir_ex4
(clock,enable,in,out); enable
input clock,enable,in;
output out; in tmp out
reg tmp;
tri out; clk
160
Bi-directional ports & tri-state buses
Test_bidir
bidir
!( en_a || en_b )
en_a
data data
out_stuff
data_a
combinational sequential
tri-state
en_b
Remember: Model these separately.
data_b
in_stuff
161
Bi-directional ports & tri-state buses
endmodule
162
GATE-LEVEL MODELING
163
Verilog RTL & Gate-Level Netlist Example
module counter ( clk, rst, en, load, cout );
input [7:0] load;
module counter (clk, rst, en, load, output [7:0] cout;
cout) ; input clk, rst, en;
wire N5, N6, N7, N8, N9, N10, N11, N12, n10, n11, n12, n13, n14, n15, n16,
n17, n18, n19, n20, n21, n22, n23, n24, n25, n26;
input clk, rst, en;
DFFRHQX1 cout_reg_7_ ( .D(n18), .CK(clk), .RN(rst), .Q(cout[7]) );
input [7:0] load; DFFRHQX1 cout_reg_3_ ( .D(n22), .CK(clk), .RN(rst), .Q(cout[3]) );
DFFRHQX1 cout_reg_4_ ( .D(n21), .CK(clk), .RN(rst), .Q(cout[4]) );
output [7:0] cout; DFFRHQX1 cout_reg_5_ ( .D(n20), .CK(clk), .RN(rst), .Q(cout[5]) );
reg [7:0] cout; DFFRHQX1 cout_reg_6_ ( .D(n19), .CK(clk), .RN(rst), .Q(cout[6]) );
DFFRHQX1 cout_reg_1_ ( .D(n24), .CK(clk), .RN(rst), .Q(cout[1]) );
DFFRHQX1 cout_reg_2_ ( .D(n23), .CK(clk), .RN(rst), .Q(cout[2]) );
always @(posedge clk or negedge DFFRHQX1 cout_reg_0_ ( .D(n25), .CK(clk), .RN(rst), .Q(cout[0]) );
INVX1 U20 ( .A(n10), .Y(n18) );
rst) AOI22X1 U21 ( .A0(N12), .A1(n26), .B0(load[7]), .B1(en), .Y(n10) );
INVX1 U22 ( .A(n11), .Y(n19) );
if (!rst) AOI22X1 U23 ( .A0(N11), .A1(n26), .B0(load[6]), .B1(en), .Y(n11) );
cout = 0; INVX1 U24 ( .A(n12), .Y(n20) );
AOI22X1 U25 ( .A0(N10), .A1(n26), .B0(load[5]), .B1(en), .Y(n12) );
else if (en) INVX1 U26 ( .A(n13), .Y(n21) );
cout = load; AOI22X1 U27 ( .A0(N9), .A1(n26), .B0(load[4]), .B1(en), .Y(n13) );
INVX1 U28 ( .A(n14), .Y(n22) );
else AOI22X1 U29 ( .A0(N8), .A1(n26), .B0(load[3]), .B1(en), .Y(n14) );
INVX1 U30 ( .A(n15), .Y(n23) );
cout = cout + 1; AOI22X1 U31 ( .A0(N7), .A1(n26), .B0(load[2]), .B1(en), .Y(n15) );
INVX1 U32 ( .A(n16), .Y(n24) );
AOI22X1 U33 ( .A0(N6), .A1(n26), .B0(load[1]), .B1(en), .Y(n16) );
endmodule INVX1 U34 ( .A(n17), .Y(n25) );
AOI22X1 U35 ( .A0(N5), .A1(n26), .B0(load[0]), .B1(en), .Y(n17) );
INVX1 U36 ( .A(en), .Y(n26) );
counter_DW01_inc_0 add_16 ( .A(cout), .SUM({N12, N11, N10, N9, N8, N7, N6,
N5}) );
endmodule
164
Using libraries - 1
165
Using Libraries - 2
PADINX1 U2 (clock, clkin); n Both option can be used with other VCS
PADOUTX1 U2 (b_in, out); compile-time option
...
...
endmodule
From IP Library
166
Timing Accuracy
• Pre Synthesis: Least Accurate
• RTL level
• Simple delay (#)
167
Pre-Synthesis
At the pre synthesis level (RTL) your timing accuracy for delays is only
as good as the simple delays you put into the code.
Example
Modeling propagation delay through the flip flops:
168
Post-Synthesis: specify blocks
syntax:
specify
specparam_declarations
simple_pin-to-pin_path_delay
edge-sensitive_pin-to-pin_path_delay
state-dependent_pin-to-pin_path_delay
timing_constraint checks
endspecify
169
Standard Delay Format (SDF)
syntax:
$sdf_annotate ("sdf_file", module_instance);
(CELL
(CELLTYPE "FD1")
(INSTANCE d_out_reg\[0\])
module testbench;
(DELAY …
(ABSOLUTE
(IOPATH (posedge CP) Q (1.147:1.147:1.147) (1.390:1.390:1.390))
(IOPATH (posedge CP) QN (1.590:1.590:1.590) (1.370:1.370:1.370)) top DUT ( …);
)
) …
(TIMINGCHECK
(SETUP D (posedge CP) (0.800:0.800:0.800))
initial
(HOLD D (posedge CP) (0.400:0.400:0.400)) $sdf_annotate (“top.sdf”, testbench.DUT);
)
Example endmodule
SDF file
170
Finite State Machines
FSM styles
• Embedded signals
• Separate signals
• One-hot
• Mealy / Moore
FSM types
Inputs Output
Next state Logic Outputs
logic cloud State cloud
Vector
clk
172
FSM style #1
(next-state and output logic combined)
• Sequential:
• Steps the state machine
• Combinational:
• A case statement, one state per branch
• State register is the case selector
• Next state assignments are explicit in each branch
• Outputs are assigned in each branch
173
Example 1
module example_a(input wire clk, rst, input_sig_1, input_sig_2,
output reg a, b);
Combinational: end
next_state = S0; S0
S1: begin
Next State and b = `TRUE;
Output a = `FALSE;
Logic if(input_sig_2 == `TRUE)
next_state = S2;
else
next_state = S0;
end
S2: begin
S1
b = `FALSE;
a = `FALSE;
next_state = S0;
end
default: begin S2
a = 1’bx;
b = 1’bx;
next_state = S0;
end
174
endcase
endmodule
FSM style #2
(separate next-state and output logic)
175
Example 2
module example_c(input wire clk, rst, input_sig_1, input_sig_2,
output wire a, b);
parameter[1:0]
S0 = 2’b00, S1 = 2’b01, S2 = 2’b10;
Combinational: reg [1:0] state, next_state;
Output
logic
assign a = (state == S0) && (input_sig_1 || input_sig_2);
assign b = (state == S1);
S2:
next_state = S0;
default:
next_state = S0;
endcase
endmodule
176
One-Hot Encoding
• Only one bit of the state vector is asserted for any given state
• n states require n flops to implement
• State decode is simplified with the following benefits:
– Typically faster logic
– Modifications are simple
– Easily synthesized
– Do not have to worry about finding “optimal” state encoding
• Disadvantages:
– Area penalty because of extra flops
177
Example 3: One-Hot, Synch. Reset
module example_d (input wire clk, rst, input_sig_1, input_sig_2,
output wire a, b);
parameter S0 = 3'b001, S1 = 3'b010, S2 = 3'b100;
reg [2:0] state, next_state;
179
Exercise
180