Verilog HDL
Outline
§ HDL Languages and Design Flow
§ Introduction to Verilog HDL
§ Basic Language Concepts
§ Connectivity in Verilog
§ Modeling using Verilog
§ Race conditions
§ UDPs
§ Coding FSMs in Verilog
Outline
§ Verilog Logic Synthesis
§ Verilog Coding Guidelines
§ Electrical Properties
§ Macros, Conditional Compilation & Naming Conventions
§ Verilog for Logic Simulation
§ Introduction to PLI
HDL Languages and Design Flow
HDLs – WHAT-WHY-HOW
§ WHAT is a HDL?
§ HDLs – A class of programming/computer languages used for
formal description of electronic circuits.
§ A Hardware Description Language is one that can describe
circuit’s operation, conceptual design & organization and can
test it by means of simulation.
§ Usually deal with the design of digital logic circuits and
systems.
HDLs – WHAT-WHY-HOW
§ WHY were HDLs required?
§ It is impractical to verify large circuits on breadboards or
large chips after manufacturing.
§ Highly important to find potential functional bugs in the
early stages of design.
§ These needs led to a the use of CAD techniques for digital
design.
§ The designers felt need for a flexible language that may help
the design process by giving a complete framework for design.
HDLs – WHAT-WHY-HOW
§ WHY were HDLs required? (contd..)
§ Software Programming languages – Sequential in nature. (C,
Pascal, FORTRAN, etc.)
§ Digital logic circuits involve Concurrency of operations.
§ Traditional programming languages lack the capability for
explicitly expressing time.
§ Using s/w programming languages to represent hardware is –
Inconvenient, Time consuming & Costlier.
HDLs – WHAT-WHY-HOW
§ HOW are HDLs advantageous?
§ Allows designer to talk about what the hardware should do
without actually designing the hardware itself.
§ Designers can develop an executable functional specification
that documents the exact behavior of all the components and
their interfaces.
§ Designers can make decisions about cost, performance, power,
and area earlier in the design process.
§ Designers can create tools which automatically manipulate
the design for verification, synthesis, and optimization.
Design Hierarchy
§ Design Specification & Requirements
§ Behavioral/Architectural Design
§ Register Transfer Level (RTL) Design
§ Logic Design
§ Circuit Design
§ Physical Design
§ Manufacturing
System Specification
Functional (Architectural
Design)
Behavioral Representation Functional Verification
Logic Design
Logic (Gate-level)
Representation Logic Verification
Circuit Design
Circuit Representation Circuit Verification
Physical Design
Layout Representation Layout Verification
Fabrication & Testing
Hardware Design Flow
System
Behavioral level
... CPU SubSystem
RTL
Gate level
Treansistor level
Implementation
Arith Reg. Mem.
Design
adder subtr
Hardware Design Flow
§ HDLs and CAD tools are used to describe hardware for:
§ Design & Modeling
§ Simulation
§ Synthesis
§ Testing
§ Documentation
Verilog HDL Introduction
Verilog HDL - History
§ Invented by Phil Moorby & Prabhu Goel at Gateway Design
Automation Systems in 1983/84.
§ Later , Cadence took full proprietary in 1990.
§ In 1995, Cadence published Verilog for public domain under OVI
(Open Verilog International).
§ Verilog-95 – IEEE Standard 1364-1995.
§ Verilog 2001 – IEEE Standard 1364-2001.
§ Verilog 2005 – IEEE Standard 1364-2005.
§ SystemVerilog – Extended from Verilog and C++.
How Verilog Is Used
§ It is a general purpose HDL with support for .
§ Allows different levels of abstraction to be mixed in the same
design.
§ “Synthesis subset”
§ Can be translated using Synopsys’ Design Compiler or others
into a netlist.
§ Design written in Verilog.
§ Simulated to check functionality.
§ Synthesized (netlist generated).
§ Static timing analysis.
Levels of Abstraction
§ Verilog supports a design at 4
different levels of abstraction. Behavioral
Highest Abstraction
Level
§ Behavioral Level
§ Dataflow Level Dataflow
§ Gate Level
§ Switch level Gate Level
§ Register Transfer Level (RTL)
Switch level Lowest Abstraction
§ A combination of both Level
Behavioral & Dataflow
constructs.
§ Acceptable to logic synthesis
tool.
Levels of Abstraction (Cont..)
§ Behavioral Level :- Used to model the behavior of a design
without describing its actual hardware structure.
§ Data Flow Level :- Describes the flow of data between registers
and how a design processes that data.
§ Gate Level :- Describes the logic gates and the connections
between logic gates in a design.
§ Switch Level :- Describes the transistors and storage nodes in a
device and the connections between :-describes them
Design Methodologies
§ There are 2 types of design methodologies:
§ Top-down design methodology, and
§ Bottom-up design methodology.
§ In a top-down design methodology, we define the top-level block
and identify the sub-blocks necessary to build the top-level block.
§ In a bottom-up design methodology, we first identify the building
blocks that are available to us. We build bigger cells, using these
building blocks.
Design Methodologies (Cont..)
Top-Level
Block
Sub- Sub- Sub-
block1 block2 block3
Leaf Leaf Leaf Leaf Leaf Leaf
Cell Cell Cell Cell Cell Cell
Top-Down Design Methodology
Design Methodologies (Cont..)
Top-Level
Block
Macro Macro Macro
Cell1 Cell 2 Cell 3
Leaf Leaf Leaf Leaf Leaf Leaf
Cell Cell Cell Cell Cell Cell
Bottom-Up Design Methodology
Modules
§ A module is the basic building block in Verilog.
§ Elements are grouped into modules to provide the common
functionality that is used at many places in the design.
§ A module provides the necessary functionality to the higher-level
block through its port interface (inputs and outputs).
§ In Verilog a module is declared by the keyword module.
§ A corresponding keyword endmodule must appear at the end of
the module definition.
Modules (Contd..)
§ Modules CANNOT be nested.
§ Rather, one module can instantiate another module.
§ Module instantiation is like creating actual objects (Instances)
from the common template (module definition).
§ Each instance of module has all the properties of that module.
§ Module instantiations are used for:
§ connecting different parts of the designs, and
§ connecting test bench to the design.
Design Hierarchy
§ One top level module
§ In which zero or more lower level modules can be
instantiated.
§ Each low level module can further instantiate still lower level
modules.
§ Verilog modules are like modules in schematics or classes in C++.
§ Use them to make your design more readable and manageable.
§ Debugging individual module is a lot easier than debugging the
whole system together.
Structure of module
module <mod name> (<port list>);
<declarations>; // input, output, inout
// wire, register, etc.
<statements>; // initial, begin, end, always
// dataflow statements
endmodule
Structure of module (Contd..)
§ The <module name> is an identifier that uniquely names the
module.
§ The <port list> is a list of input, inout and output ports which are
used to connect to other modules.
§ The <declares> section specifies data objects as registers,
memories and wires as wells as procedural constructs such as
functions and tasks.
§ The <statements> may be initial constructs, always constructs,
continuous assignments or instances of modules.
Basic Languages Concepts
Lexical Conventions
§ Keywords
§ In lower case
§ Case sensitive
§ Delimit tokens, space
§ String with double quotes
§ Identifier
§ A letter or _ can be followed by letters, digits, $ and _
§ Max 1024 characters
§ Numbers
§ [<sign>] [<size>] <base> <num>
§ e.g.- 549, ‘h8ff, ‘o765, 4’b11,3’b10x, -4’b11
Verilog Comments
Verilog supports 2 type of comment syntaxes
§ Single line comment start with //, and end with newline.
§ Block comment, start with /*, and end with */. Block comment
cannot be nested.
Example
/* Copyright Kacper Technologies Pvt Ltd, 2009
No unauthorized copying is allowed.
*/
input status; // 0:ready, 1:not ready
output data; // sync with clock mClock
Verilog Number Specifications
§ Two representations: sized & unsized
§ Format:<number of bits><base><number>
Bit length in decimal. This is an optional value
<number of bits> & if not specified, default is host machine word
size. (usually 32 bits)
<base> ‘b, ‘B, ‘d, ‘D, ‘o, ‘O, ‘h, ‘H. Default is ‘decimal’
<number> 0-9, a-f, A-F, X, Z, ?, _
Verilog Numbers Specifications (Contd..)
§ Negative numbers: put minus sign before size.
§ Format: -<size><base><number>
§ <size> field is always +ve.
§ Represented by 2’s complement internally.
§ Often _ (Underscore) is used in between digits of the number
for readability.
reg [5:0] Num;
Reg [31:0] data;
..
Num = -6; // Negative number
Num = -8’d4; // 8 bit –ve number
Num = ‘d-12; // Illegal !!
data = 32’h_1234_5678; // _ for readability
Verilog Numbers Specifications (Contd..)
§ Verilog numbers may have x or z as part of numbers.
§ x ? unknown value, z ? high impedance value
§ A question mark ‘?’ can also be used as an alternative to ‘z’.
reg [5:0] Num;
Reg [31:0] data;
..
Num = 6’b_100x; // Num = 6’b00100x
data = 32’bx; // 32 bit no with all x bits
Num = ‘bz01; // Num = 6’bzzzz01
Num = ‘b11??1; // Num = 6’b011zz1
data = 32‘h_x5f3_2693; // data = 32’hX5f32693
Verilog Numbers: Example
module Verilog_number;
reg [7:0] Num;
wire status;
…
Num = 16; // 8’b0001_0000
Num = -8’d4; // two’s complement of 4
Num = ‘bx; // 8’bxxxx_xxxx
Num = ‘b0x; // 8’b0000_000x
Num = ‘b10x; // 8’b0000_010x
if (status == 1) // status == 32’h0001
Num = 8’b1010_0101;
if (status == 1’b1) // status == 1’b1
…
endmodule
Data Types
§ reg: Register § Integer & Real Data Types
§ Declaration
§ wire: Wire/net integer i, k;
real r;
§ Possible Values: 0, 1, x, z
§ Use as registers (inside procedures)
i = 1;
§ Default: 1-bit (Scalar)
r = 2.9;
reg A, B, C;
k = r; // k is rounded to 3
§ Integers are not initialized in
§ Vector:
Verilog!!
Reg[0:7] A;
§ Reals are initialized to 0.0
Reg[7:0] B;
Nets
§ Nets represent the connections between hardware elements.
§ They are always driven by some source.
§ Default value for any net type variable is ‘z’.
§ Usually, declared by the keyword wire.
§ Different types: wire, wand, wor, tri, triand, trior, trireg, etc.
§ wire is the most common of all.
Registers
§ These correspond to variables in the C language.
§ Register data types always retain their value until another
value is placed on them.
§ DO NOT confuse with hardware registers built with flip-flops.
§ A reg type variable is the one that can hold a value.
§ Unlike nets, registers do not need any drivers.
Registers (Contd..)
§ In synthesis, the compiler will generate latches or flip-flops
for them. However, if it can be sure their output does not need
to be stored it will synthesize them into wires.
§ It can be sure they do not have to store if their outputs is
based only on their present inputs.
Rules for reg and wire
§ The common rule in Verilog:
“A variable on the Left Hand Side (LHS) of a procedural block
assignment is always declared as a register data type.”All other
variables are of net type.”
§ Verilog register data types: reg / time / integer / real / realtime
/ event (reg is the most common of all.)
§ So, reg is assigned within always or initial blocks.
§ A variable is declared of type wire if it appears on the left side
of an continuous assignment statement.
§ Structural code continuous assignment statements start with
the keyword assign.
Integers
§ A general purpose register data type with default value
having all x bits.
§ Declared with keyword integer.
§ Usually preferred for arithmetic manipulations over reg.
§ Default width: host machine word size (minimum 32 bits).
§ Differs from reg type as it stores signed quantities as opposed
to reg storing unsigned quantities.
Real Numbers
§ Real number constants declared with a keyword real.
§ Real constants have default value of 0.
§ Real numbers CANNOT have a range declaration.
§ Two notations: Decimal & Scientific notation.
§ When a real value is assigned to an integer, the real number
is rounded off to the nearest integer.
Time & Realtime Data types
§ time – A special register data type used mainly to store
simulation time.
§ time is an unsigned 64-bit by default. Usually, it is used to
store the simulation time.
§ realtime is similar to time except that it has initial value of 0.
§ Depending upon the timescale specified, realtime provides the
simulation time with the fractional part with given precision.
Logical Operators
Operator Operation Operator Operation
~& Reduction NAND ! Logical Negation
| Reduction OR && Logical AND
~| Reduction NOR || Logical OR
^ Reduction XOR ~ Bit-wise Negation
~^ or ^~ Reduction XNOR & Bit-wise AND
== or === Logical Inequality | Bit-wise OR
!= or !== Logical Inequality ^ Bit-wise Exclusive OR
> >= < <= Relational ^~ or ~^ Bit-wise Ex- NOR
?: Conditional & Reduction AND
Logical Operation Example
operand1 operand2
1 2 3 4 5 6 7 8 && A B C D E F G H
True (“1”), False (“0”) or Unknown (“X”)
Examples
1’b1 && 1’b0 0 1’b1 || 1’b0 1
2’b11 && 2’b10 0 2’b11 || 2’b10 1
2’b1X && 2’b11 X 2’b1X || 2’b11 1
Bitwise Operators
§ & → bitwise AND § ^ → bitwise XOR
§ | → bitwise OR § ~^ or ^~ → bitwise
XNOR
§ ~ → bitwise NOT
§ Operation on bit by bit
basis
1 2 3 4 5 6 7 8 & A B C D E F G H
1 2 3 4 5 6 7 8
& & & & & & & &
A B C D E F G H
Reduction operators
§ Key symbols: &, ~&, |, ~|, ^, ~^, ^~.
§ The reduction operators are and, nand, or, nor, xor, xnor and an
alternative xnor. They take one operand and perform a bit-by-
next-bit operation, starting with the two leftmost bits, giving a 1-
bit result.
initial begin
a = 4'b1111;
b = 4'b0101;
c = 4'b0011;
$displayb(& a); // bitwise and, (same as 1&1&1&1)
// evaluates to 1
$displayb(| b); // bitwise or (evaluates to 1)
end
Reduction operation
& 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
& & & &
& &
&
Shift operators
§ Key symbols: >>, <<.
§ The shift operators are shift left and shift right. The shift operator
takes a vector and a number indicating the shift.
§ The empty bits caused by shifting are filled with zeros.
module shiftTest;
reg [3:0] a;
initial begin
a = 4'b1010;
$displayb(a << 1); // shift left by 1, displays 0100
$displayb(a >> 2); //shift right by 2, displays 0010
end
endmodule // shiftTest
Conditional Operator
§ cond_expr ? true_expr : false_expr
§ A ternary operator
§ Acts like a 2-to-1 mux.
A
1
Y
Y = (sel)? A : B;
B 0
Y = A if sel is ‘1’
sel B if sel is 0
Concatenation Operator
§ {op1, op2, ..} → concatenates op1, op2, .. to single number.
§ Operands must be sized !!
…
reg a;
reg [2:0] b,c;
a = 1’b1,b = 3’b 010, c = 3’b 101;
catx = {a, b, c}; // catx = 1_010_101
caty = {b, 2’b11, a}; // caty = 010_11_1
catz = {b, 1}; // WRONG !!
…
Replication Operator
§ <no> { <variable/sized_number> }
§ <no> is an integer.
…
reg a;
reg [2:0] b,c;
a = 1’b1,b = 3’b 010, c = 3’b 101;
catr = {4{a}, b, 2{c}}; // catr = 1111_010_101101
…
Relational & Equality Operators
§ > → greater than
§ < → less than
§ >= → greater or equal than
§ <= → less or equal than
§ Result is one bit value: 0, 1 or x
§ == → logical equality
§ != → logical inequality Return 0, 1 or x
§ === → case equality
§ !== → case inequality Return 0 or 1
e.g. - 4’b1z0x == 4’b1z0x → x
4’b1z0x === 4’b1z0x → 1
Operator precedence
Operators Operator Symbols Precedence
Unary + - ! ~ Highest
Multiply, Divide, Modulus * / %
Add, Subtract + -
Shift >> <<
Relational < <= >= >
Equality == != === !==
Reduction & ~&
^ ^~
| ~|
Logical && ||
Conditional ?: Lowest
Vectors
§ Vectors have multiple bits and are often used to represent buses.
§ The left most number is an MSB (Most Significant Bit).
§ There are 2 representations for vectors:
§ A little-endian notation: [high# : low#]
§ A big-endian notation: [low# : high#]
wire [3:0] busA; // little-endian notation
reg [0:15] busC; // big-endian notation
reg [1:4] busB;
Vectors (Contd..)
§ Vector Part Select
data[15:8] = 8’h_12; // Accessing only bits 16 to 9 of data
inter_carry = carry[1:3];
§ Slice management
reg [63:0] out;
reg [3:0] dest_addr; dest_addr[0] = out[60];
initial begin dest_addr[1] = out[61];
= dest_addr[2] = out[62];
dest_addr = out[63:60];
end dest_addr[3] = out[63];
Vectors (Contd..)
§ Vector assignment (by position!!)
…
reg [2:0] bus_A;
reg [0:2] bus_B; bus_A[2] = bus_B[0];
initial begin = bus_A[1] = bus_B[1];
bus_A = bus_B; bus_A[0] = bus_B[2];
end
…
Vectors (Contd..)
§ Variable Vector Part Select
§ [<starting_bit>+ : <width>]
§ [<starting_bit>- : <width>]
reg [31:0] data1; reg [0:31] data2;
reg [7:0] byte1; reg [3:0] nibble1;
reg [0:7] byte2; reg [0:3] nibble2;
…
nibble1 = data1[31-:4]; // selects 4 bits from 31 to down, i.e. [31:28]
byte1 = data1[24-:8]; // selects data1[24:17]
byte2 = data2[10+:8]; // selects data2[10:17]
nibble2 = data2[28+:4]; // selects data2[28:31]
Strings
§ Implemented with regs.
§ Escaped chars:
\n for newline \\ for \ \” for “
\t for tab %% for % \ooo characters as octal
…
reg [8*13:1] string_val; // can hold up to 13 chars
...
string_val = “Hello Verilog”;
string_val = “hello”; // MS Bytes are filled with 0
string_val = “I am overflowed”; // “I ” is truncated
…
Arrays
§ Declaration: <type> <vector_size> <ary_name> <ary_size>;
§ <ary_size> is declared as a range.
§ Verilog supports multi-dimensional arrays.
§ Elements are accessed by: <ary_name> [<index>].
reg array1 [99:0]; // array1 is an array with 100 elements
// each element is of 1 bit.
integer ary1 [19:0]; // array of integers with 20 elements
wire [3:0] y [10:1]; // array of buses
reg [31:0] payload [34:0]; // array of vectors
time checkpoints [1:50]; // array of check-points
real results [39:0]; // array of real numbers
Arrays (Contd..)
//Multi-dimensional arrays
reg [7:0] sonet_frame [89:0][8:0];
// a 2-dimentional array representing the SONET frame.
reg [7:0] matrix3d [9:0] [24:0] [3:0];
// 3-dimentional array of integers
Memories
§ Declaration:
reg <vector_width> <ary_name> <no_of_locations>;
…
reg [7:0] string_val [99:0]; // a memory with 100 elements
// each of 1 byte
reg [7:0] ray2d [4:0] [49:0]; // 2-dimentional array
reg [31:0] mem32 [`DEPTH-1:0]; // 32-bit memory
…
Connectivity in Verilog
Port assignments
§ Modules contain functional descriptions and have input, output,
and inout (bidirectional ports) for interfaces.
§ The following are true of module interfaces:
§ An input or inout port is a wire type within its module.
§ An output port must be a wire if it is generated by a
submodule.
§ An output port must be a wire if it is generated declaratively.
§ An output port must be
§ a reg if it is assigned to procedurally.
§ A wire if it is assigned through continuous assignment.
§ Bidirectional ports cannot be assigned to procedurally.
Module Instantiations
§ As we saw earlier, module instantiation is used to make
connections between different parts of the design.
§ There are two methods of making connections between signals
specified in the modules and their input/output ports.
§ Port ordered instantiation lists signal connections in the same
order as the port list in the module definition. Unconnected ports
are designated by two commas with no signal listed.
§ Port named instantiation lists the port name and signal
connected to it, in any order.
Module Instantiations (Contd..)
§ Connections by Ordered List
<module_name> <instance_name> [instance_array_range]
( signal, signal, ... );
§ Connections by Named List
<module_name> <instance_name> [instance_array_range]
( .port_name(signal), .port_name(signal), ... );
Module Instantiations (Contd..)
§ A module can be seen as a template which allows any other
modules to incorporate its functionality without writing the same
logic repeatedly.
§ Modules allow instances & hierarchy.
§ When a module instance is created in higher level module, the
instance will have all the properties of the lower level module.
§ Instantiations are used for connecting different modules
together.
Hierarchical Naming
§ As modules instantiate one another, there forms a hierarchy of
them. And them and their internal variables, etc. can be
accessed from higher levels using hierarchical naming.
TB_TOP
dff
nand1 nand2
Hierarchical Naming (Contd..)
TB_TOP
dff1
Q, QB
nand1 nand2 D (Signals)
§ Signals of the dff may be accessed using hierarchical naming as
shown below:
TB_TOP TB_TOP.nand1.o1
TB_TOP.dff1.Q TB_TOP.dff1.QB
TB_TOP.nand1
Modeling using Verilog
Gate Level Modeling
§ Verilog has built in primitives like gates, transmission gates, and
switches.
§ These are rarely used for in design work, but are used in post
synthesis world for modeling the ASIC/FPGA cells. These cells are
then used for gate level simulation or what is called as SDF
simulation.
§ Ex:- and, or, nand, nor, xor, xnor
not, buf
bufif1, notif1, bufif0, notif0
Gate Level Modeling (Contd..)
§ The gates have one scalar output and multiple scalar
inputs.
§ The first terminal in the list of gate terminals is an output
and the other terminals are inputs.
§ Gate instance name is optional.
nand n1(z, a, b); // 2 input NAND gate
xor x1(z, a, b, c, d); // 4 input XOR gate
and x2(z, a, b, c); // 3 input AND gate
or(z, a, b); // Instance name is optional
buf b1(out, in); // Buffer
not n1(out, in); // Inverter
bufif0 U1( data_bus, data_drive, data_enable_low );
Gate Delays
§ Rise Delay: associated with a gate output transition to 1 from
another value.
§ Fall Delay: associated with a gate output transition to 0 from
another value.
§ Turn-off Delay: associated with a gate output transition to z from
another value.
§ If the output of gate changes to ‘x’, the minimum of the three
delays is considered.
Gate Delays (Contd..)
§ Min / Max / Typ delay values: They represent the minimum,
maximum and typical delay value that a designer expects the
gate to have.
§ Min, typ or max values can be chosen at runtime by options
provided in the simulator.
§ The gate delay cam be specified as follows:
<gate_primitive> #(rise_time, fall_time, turnoff_delay)
§ The gate delay can be specified with only one delay time or rise
and fall times or with all 3 delay values.
Gate Delays (Contd..)
// rise, fall & turnoff delays
and #(10) a1( and_out, in1, in2 ); // delay time
or #(14,16) OR( op, i1, i2, i3 ); // rise & fall times
xor #(1, 3, 5) xg( o, a, b ); // rise, fall and turnoff delays
// For transition to x, the delay is taken as min(1, 3, 5)
// examples for #(min : typ : max) values
not #(2:3:5) inv(out, in); // min delay=2
// typ delay = 3
// max delay = 5
Gate Delays (Contd..)
nor #( 2:3:5, 1:4:7 ) inv( out, in1, in2 );
// min rise delay=2, typ rise delay=3, max rise delay=5
// min fall delay=1, typ fall delay=4, max fall delay=5
buf #( 2:3:5, 1:4:7, 0:1:3 ) inv( out, in );
/* min rise delay=2, typ rise delay=3, max rise delay=5
min fall delay=2, typ fall delay=3, max fall delay=5
min turnoff delay=0, typ turnoff delay=1,max turnoff delay=3
*/
Gate Level Modeling Examples
// 1-bit Half Adder
module ha( sum, carry, a, b );
output sum, carry;
input a, b;
xor #5 x1( sum, a, b );
// rise, fall and turnoff delay
and #(1,2,3) a1( carry, a, b );
endmodule
Gate Level Modeling Examples (Contd..)
module dff ( Q, Q_BAR, D, CLK );
output Q,Q_BAR;
input D,CLK;
// Four Instantiations of nand gates
nand U1 (X,D,CLK) ;
nand U2 (Y,X,CLK) ;
nand U3 (Q,Q_BAR,X);
nand U4 (Q_BAR,Q,Y);
endmodule
Dataflow Modeling
§ The data flow between registers and the way that data gets
processes is modeled using dataflow modeling.
§ Dataflow modeling involves continuous assignments, that is
driving values to the net.
§ assign is used to drive value on the net by continuos assignment.
§ Syntax:
assign <drive_strength> #<delay> <list_of_assignments>;
Dataflow Modeling (Cont..)
// Regular continuous assignment
wire out;
assign out = var1 & var2;
// Same effect is achieved by an implicit continuous assignment
wire out = var1 & var2;
Delays
§ A delay control expression specifies the time duration between
initially encountering the statement and when the statement
actually executes.
e.g.-
#10 A = A + 1;
§ The delay is represented using #. A number followed by # shows
the delay value.
§ In real circuits , logic gates have delays associated with them.
Verilog provides the mechanism to associate delays with gates.
§ There are different ways to specify delays in continuous
assignments.
Delays (Cont..)
§ Regular Assignment Delay:
§ This is the most commonly used method.
§ e.g.-
assign #10 q = x + y;
§ Implicit Continuous Assignment Delay:
§ Similar to implicit assignment statement with delay added.
§ e.g. –
wire #10 q = a ^ b;
// which is equivalent to the following:
// wire out;
// assign #10 out = a ^ b;
Delays (Cont..)
§ Net Declaration Delay:
§ The delay can be put on the net in declaration itself.
§ e.g. –
wire #10 out;
assign out = a & b;
// which is equivalent to the following:
// wire out;
// assign #10 out = a & b;
Dataflow Modeling Examples
// All basic logic gates
module gates( invo, ao, oo, nao, noo, xoo, xno, a, b );
input a, b;
output ao, oo, nao, noo, xoo, xno;
assign invo = ~a;
assign ao = a & b;
#10 assign oo = a | b;
assign #1 nao = a ~& b;
assign noo = #3 a ~| b;
assign xoo = a ^ b;
assign xno = a ~^ b;
endmodule
Dataflow Modeling Examples (Contd..)
// 2:1 Multiplexer
module mux21(op, a, b, sel );
input [3:0] a, b;
input sel;
output op;
assign op = sel ? a : b;
endmodule
Behavioral Modeling
§ In RTL and Gate level implementation, the details of the
handshake mechanism between different processes are implied.
The states are cycle-to-cycle accurate.
input data received data
data ready request data
overflow
acknowledge data
Behavioral Modeling (Contd..)
§ The behavioral model provides the ability to describe design
functionality in an algorithmic manner or in higher level of
modeling where behavior of logic is modeled.
§ In behavioral modeling, you can use events for synchronizing. The
details of implementation is based on the application.
input data received data
data ready request data
Behavioral Modeling (Contd..)
§ Most of the programming languages (e.g. C, Basic) are sequential
in natural, or only one active process at any one time. However,
hardware circuitry is concurrent in nature. All the circuitries are
active in parallel.
§ Verilog supports parallelism by allowing any number of “always”
and “initial” blocks. Each “always” and “initial” block run
concurrently.
§ always and initial blocks are called procedural blocks. Assignment
inside procedural blocks are called procedural assignment.
Procedural Blocks
§ Procedural blocks are the basic components for behavioral
modeling.
initial always
begin begin
… imperative statements … … imperative statements …
end end
§ Runs when simulation starts
§ Runs when simulation starts
§ Terminates when control § Restarts when control
reaches the end
reaches the end
§ Good for providing stimulus § Good for modeling /
specifying hardware
Procedural Blocks (Contd..)
§ Run until they encounter a delay.
initial begin
#10 a = 1; b = 0;
#10 a = 0; b = 1;
end
§ or a wait for an event
always @(posedge clk) q = d;
always begin wait(i); a = 0; wait(~i); a = 1; end
Procedural Blocks (Contd..)
§ Procedural blocks are like concurrent processes.
§ Statements in a block are executed sequentially, but all
within one unit of simulated time. (unless delay is
specified)
§ All blocks execute in parallel.
§ initial block
§ Executes only once.
§ always block
§ Executes repeatedly. It must have timing control,
otherwise it become INFINITE LOOPS
Procedural Blocks (Contd..)
§ Syntax:
type_of_block @(sensitivity_list)
statement_group: group_name
local_variable_declarations
timing_control procedural_statements
end_of_statement_group
§ type_of_block is either initial or always.
§ initial procedural blocks process statements one time.
§ always procedural blocks process statements
repeatedly.
§ sensitivity_list (optional) is an event timing control that
controls when all statements in the procedural block
should be evaluated. The sensitivity list is used to model
combinational and sequential logic behavior.
Procedural Blocks (Contd..)
§ statement_group--end_of_statement_group is used to group two
or more procedural statements together and control the
execution order
§ begin--end groups two or more statements together sequentially,
so that statements are evaluated in the order they are listed.
§ Each timing control is relative to the previous statement.
§ fork & join are used to two or more statements together in
parallel, so that all statements evaluated concurrently.
§ Each timing control is absolute to when the group started.
Procedural Assignment
§ Procedural statements are statements inside a procedure. (they
execute sequentially)
§ This can be expressed in two types of blocks:
§ initial → they execute only once
§ always → they execute for ever
§ The RHS expression is evaluated and assigned to LHS variable
before next statement executes.
§ RHS expression may contain wires and regs
§ Two possible sources for data
§ LHS must be a reg (rooy) type data type.
§ Primitives or cont. assignment may set wire values
Blocking & Non-blocking Assignments
§ There are two types of assignment statements are there in Verilog:
§ Blocking statements
§ Non-blocking statements.
§ Blocking Assignment:- It is a way of blocking the further
statements until the current statement execution is completed.
§ A blocking assignment must evaluate the RHS arguments and
complete the assignment without interruption from any other
Verilog statement.
§ The assignment is said to "block" other assignments until the
current assignment has completed.
Blocking & Non-blocking Assignments
§ Non Blocking assignments allow scheduling of assignments
without blocking execution of the statements that follow in a
sequential block.
§ Execution of non-blocking assignments can be viewed as a two-step
process:
§ Evaluate the RHS of non-blocking statements at the beginning
of the time step.
§ Update the LHS of non-blocking statements at the end of the
time step.
Blocking Assignments
§ The blocking assignment operator is an equal sign (=).
§ The blocking assignment with timing delays on the RHS of the
blocking operator, which is considered to be a poor coding style.
§ A problem with blocking assignments occurs when
§ the RHS variable of one assignment in one procedural block is
also the LHS variable of another assignment in another
procedural block, and
§ both equations are scheduled to execute in the same
simulation time step, such as on the same clock edge.
Blocking Assignments (Contd..)
§ If blocking assignments are not properly ordered, a race
condition can occur.
§ When blocking assignments are scheduled to execute in the same
time step, the order execution is unknown.
§ Evaluate the RHS (right-hand side equation) and update the
LHS (left-hand side expression) of the blocking assignment
without interruption from any other Verilog statement.
Blocking Assignments Example
module fbosc1 ( y1, y2, clk, rst );
output y1, y2;
input clk, rst;
reg y1, y2;
always @(posedge clk or posedge rst )
if (rst) y1 = 0; // reset
else y1 = y2;
always @( posedge clk or posedge rst )
if (rst) y2 = 1; // preset
else y2 = y1;
endmodule
A Flawed Shift Register
§ The following code doesn’t work as one may expect:
module flawed_sr;
reg d1, d2, d3, d4;
always @(posedge clk) d2 = d1;
always @(posedge clk) d3 = d2;
always @(posedge clk) d4 = d3;
endmodule
§ Because of all blocking assignments in different always blocks,
the order of execution becomes tool-specific. So, the design won’t
behave like shift register!
Non-blocking Assignments
§ The non-blocking assignment operator is the same as the less-
than-or-equal-to operator ("<=").
§ They are called “non-blocking” because-
§ the assignment evaluates the RHS expression of a it at the
beginning of a time step, and
§ schedules the LHS update to take place at the end of the time
step.
§ Between evaluation of the RHS expression and update of the
LHS expression, other Verilog statements can be evaluated and
updated.
Non-blocking Assignments (Contd..)
§ Also, the RHS expression of other Verilog non-blocking
assignments can also be evaluated and LHS updates scheduled.
The non-blocking assignment does not block other.
§ Verilog statements from being evaluated. Execution of non-
blocking assignments can be viewed as a two-step process:
§ Evaluate the RHS of non-blocking statements at the
beginning of the time step.
§ Update the LHS of non-blocking statements at the end of the
time step.
Non-blocking Assignments (Contd..)
module fbosc2 ( y1, y2, clk, rst );
output y1, y2;
input clk, rst;
reg y1, y2;
always @( posedge clk or posedge rst )
if (rst) y1 <= 0; // reset
else y1 <= y2;
always @( posedge clk or posedge rst )
if (rst) y2 <= 1; // preset
else y2 <= y1;
endmodule
Non-blocking Assignments (Contd..)
Nonblocking rule:
RHS evaluated when
This version works: assignment runs
reg d1, d2, d3, d4;
always @(posedge clk) d2 <= d1;
always @(posedge clk) d3 <= d2;
always @(posedge clk) d4 <= d3;
LHS updated only after all
events for the current
instant have run
Non-blocking Looks Like Latches
a = 1;
b = a; “ 1
a b c ”
c = b;
1 a
a <= 1;
b <= a; “ b ”
c <= b;
c
Looping Flow Control
Verilog supports “for”, “while” and “repeat” and “forever” loop
// example of “for” loop
for( i=0; i<`MEMSIZE; i=i+1)
begin
mem[i] = 8’b0;
end
// example of “while” loop
i = 0;
while(i<`MEMSIZE)
begin
mem[i] = 8’b0;
end
// example of “repeat” loop
i = 0;
repeat (`MEMSIZE)
begin
mem[i] = 8’b0;
i = i + 1;
end
// example of “forever” loop
i = 0;
forever
begin : mem_init
mem[i] = 8’b0;
i = i + 1;
if (i == `MEMSIZE)
disable mem_init;
end
Task and Function
§ Verilog support encapsulation of a piece of code into a task or a
function.
§ Use task or function when:
§ A section of the code that is used more than once, with
possibility different inputs.
§ A code that is expected to be issued interactively.
§ Break long procedural blocks into smaller parts in order to
improve readability and maintenance of the code.
Difference between task and function
§ A task can have timing control constructs, whereas function
cannot. A function can only model combinatorial functionality.
§ The code that initiated a task has to wait for that task to
complete or disabled before continuing execution.
§ A task can have inputs and outputs, whereas function must have
at least one input and only one output. (which is the name of the
function itself)
Example of a task
task task_example;
input [1:0] in1, in2;
output [1:0] out1, out2;
#1 out1 = in1 & in2;
#1 out2 = in1 | in2;
endtask
Example of a function
function [1:0] function_example;
input [1:0] in1, in2;
function_example = in1 & in2;
endfunction
System Tasks
§ Verilog has some of the inbuilt task as part of the language itself.
§ $display : This system task is used to display the text and
formatted data on the screen. It inserts a newline at end of
display text automatically.
§ $monitor : It continuously monitors the changes in any of the
variable/signal specified in the parameter list. Whenever, any one
of them changes, it displays the formatted string specified within
double quotes.
§ $stop: It stops /suspends the simulation.
System Tasks (Contd..)
§ $finish: It terminates the simulation.
§ $write: It is similar to $display except that it does not insert a
newline at the end of the formatted output by default.
§ $strobe: It is used for strobing purpose. When one wants to
display the values of the variables which are assigned within
non-blocking statements, it is a good practice to display them
using $strobe.
§ $random: It generates a 32-bit signed integer randomly. It is used
mainly in test bench.
System Tasks (Contd..)
§ $time: It returns the current simulation time.
§ $realtime: Same as $time excepts it shows the fraction part as
well.
Compiler Directives
§ All compiler directives are preceded by a ‘back tick’ ( ` ).
§ `define : It is used to define a text macro in Verilog.
§ `include: It is used to include content of some other file inside a
Verilog code.
§ `timescale: It is used to specify the timescale for simulation. It
has two parts: reference time unit & time precision. First one
specifies the time unit and the later determines the minimum
unit that is considered for any round off.
`timescale <ref_time_unit>/<precision>
System Tasks & Compiler Directives Example
`timescale 10ns/1ns
`define A 10
module abc();
reg [3:0] a;
initial begin
a = 3;
$display(“Initializing….\nA = %d”, a);
monitor($time, “ \tA = %d”, a);
#300 $finish;
end
always #25 a = $random;
endmodule
Synchronization
Verilog support the following type of process synchronization
§ event
§ fork and join
§ disable
Synchronization - Event
§ # <expression>
suspends execution of the process for a fixed time period
§ @event-expression
suspends the execution of the process until the specified event
occurs
§ wait (expression)
suspends the execution of the process until the expression become
true
Synchronization (Contd..)
§ Verilog supports “event” data type.
module event_example;
event e1, e2;
…
endmodule
§ Trigger an event using “ ->event_variable”
§ Wait for an event using “@event_variable”
Synchronization – fork and join
module barrel_sync;
always begin
…
fork <statement 1> to <statement N>
<statement 1>; are executed in parallel
<statement 2>;
…
<statement N>;
join
<statement S>; <statement S> is executed only
end when <statement 1> to
<statement N> are completed
endmodule
Synchronization – disable
disable <block_name>
§ remove pending events from <block_name>
§ will not continue to execute the rest of the <block_name>
§ if <block_name> is in the always block, execution continues
from the start of the always block
…
always begin : write_block
if “write_through”is true,
<statement 1>;
all pending events (e.g.
…
out=#10 ram[index] from the
if ( write_through )
previous cycle) will be
disable write_block;
removed. Execution start from
out = #10 ram[index];
<statement 1>
end
…
Forever Statement
§ This loop executes continuously and never completes.
§ An infinite loop that continuously executes the statement or
statement group.
§ Infinite loops in Verilog use the keyword forever.
§ You must break up an infinite loop with an @(posedge clock) or
@(negedge clock).
§ expression to prevent combinational feedback, as shown in an
example:
§ Syntax; forever<execution statement>
initial
begin
clock=0;
forever #50 clock=~clock;
end
Generate Statements
§ Generate statements are used when the same operation or
module instance is repeated for multiple bits of vector.
§ Generate statements allow control over the declaration of
variables, functions and tasks as well as control over
instantiations.
§ All generate instantiations are coded with a module scope and
require keywords generate – endgenerate.
§ There are three methods to create generate statements:
§ Generate loop.
§ Generate conditional.
§ Generate case.
Generate Statements (Contd..)
§ Generate loop: It permits one or more of the following to be
instantiated multiple times using a for loop.
§ Generate conditional :It is like an if-else-if generate construct
that permits the following Verilog constructs to be conditionally
instantiated based on an expression.
Parameters
§ A parameter is defined by Verilog as a constant value declared
within the module structure. The value can be used to define a set
of attributes for the module which can characterize its behavior as
well as its physical representation.
parameter <identifier> = constant;
parameter byte_size = 8;
reg[byte_size-1:0] A;
§ Used to pass information globally.
Race Conditions
Race conditions in Verilog
§ A Verilog race condition occurs when two or more statements
that are scheduled to execute in the same simulation timestep.
§ It would give different results when the order of statement
execution is changed, as permitted by the Verilog Standard.
§ It can be eliminated by using non-blocking assignments instead
of blocking assignments.
Race Conditions & their Solutions
§ In this example, two parallel
module race; blocks have no guaranteed
reg a; ordering, so it is ambiguous
whether the $display statement
initial begin will be executed.
a=0;
#10 a=1; § The solution is to delay the
end; $display with a #0 delay:
initial begin
#10 if (a) initial begin
$display(“may not print”); #10 if (a)
end #0 $display ("may not print");
endmodule end
Flip-Flop Race Condition
module test( out, in, clk ); module dff( q, d, clk );
input in, clk; output q;
output out; input d, clk;
wire a; reg q;
dff dff0( a, in, clk ); always @(posedge clk)
q = d; // race!
dff dff1( out, a, clk );
endmodule
endmodule
§ It is very common to have race conditions near latches or flip-
flops.
§ The following is the example of it in which an intermediate node
a between two Flip-flops is set and sampled at the same time.
§ The solution for this is to use the non-blocking assignment in the
flip-flop to guarantee the ordering of assignment to the output of
the flip-flop and sampling of that output.
always @(posedge clk) always @(posedge clk)
q <= d; q = #1 d;
always @(posedge clk)
q <= #1 d;
UDPs
User Defined Primitives
§ Verilog provides a standard set of primitives, such as and, nand,
or, nor, and not, as a part of the language. These are also
commonly known as built-in primitives.
§ However, designers occasionally like to use their own custom-
built primitives when developing a design.
§ Verilog provides the ability to define User-Defined Primitives
(UDP).
User Defined Primitives (Contd..)
§ There are two types of UDPs:
§ Combinational UDPs
§ Sequential UDPs
§ Combinational UDPs are defined where the output is solely
determined by a logical combination of the inputs. A good
example is a 4-to-1 multiplexer.
§ Sequential UDPs take the value of the current inputs and the
current output to determine the value of the next output. The
value of the output is also the internal state of the UDP. Good
examples of sequential UDPs are latches and flip-flops.
Rules to Define UDP
§ UDPs can take only scalar input terminals (1 bit). Multiple input
terminals are permitted.
§ UDPs can have only one scalar output terminal (1 bit).
§ The terminal must always appear first in the terminal list.
Multiple output terminals are not allowed.
§ In the declarations section, the output terminal is declared with
the keyword output. Since sequential UDPs store state, the
output terminal must also be declared as a reg.
§ The inputs are declared with the keyword input.
Rules to Define UDP (Contd..)
§ The state in a sequential UDP can be initialized with an initial
statement. This statement is optional. A 1-bit value is assigned to
the output, which is declared as reg.
§ The state table entries can contain values 0, 1, or x. UDPs do not
handle z values. z values passed to a UDP are treated as x
values.
§ UDPs are defined at the same level as modules. UDPs cannot be
defined inside modules. They can be instantiated only inside
modules. UDPs are instantiated exactly like gate primitives.
§ UDPs do not support inout ports.
Combinational UDP-Example
primitive mux4_to_1 ( output out,
input i0, i1, i2, i3, s1, s0);
table // i0 i1 i2 i3, s1 s0 : out
1 ? ? ? 0 0 : 1; I0
I1 Out
0 ? ? ? 0 0 : 0;
? 1 ? ? 0 1 : 1; I2 Mux
I3
? 0 ? ? 0 1 : 0;
? ? 1 ? 1 0 : 1;
S0 S1
? ? 0 ? 1 0 : 0;
? ? ? 1 1 1 : 1;
? ? ? 0 1 1 : 0;
? ? ? ? x ? : x;
? ? ? ? ? x : x;
endtable
endprimitive
Sequential UDP - Examples
//Define level-sensitive latch by using UDP.
primitive latch(q, d, clock, clear);
output q;
reg q;
input d, clock, clear;
//sequential UDP initialization
//only one initial statement allowed
initial
q = 0; //initialize output to value 0
//state table
table
//d clock clear : q : q+ ;
? ? 1 : ? : 0 ; //clear condition,q+ is the new o/p value
1 1 0 : ? : 1 ; //latch q = data = 1
0 1 0 : ? : 0 ; //latch q = data = 0
? 0 0 : ? : - ; //retain original state if clock = 0
endtable
endprimitive
//Define an edge-sensitive sequential UDP;
primitive edge_dff(output reg q = 0, input d, clock, clear);
table
// d clock clear : q : q+ ;
? ? 1 : ? : 0 ; //output = 0 if clear = 1
? ? (10) : ? : - ; //ignore negative transition of clear
1 (10) 0 : ? : 1 ; //latch data on negative transition of
0 (10) 0 : ? : 0 ; //clock
? (1x) 0 : ? : - ; //hold q if clock transitions to unknown //state
? (0?) 0 : ? : - ; //ignore positive transitions of clock
? (x1) 0 : ? : - ; //ignore positive transitions of clock
(??) ? 0 : ? : - ; //ignore any change in d when clock //is steady
endtable
endprimitive (10) àNegative edge transition from 1 to 0
(1x) àTransition from 1 to unknown
(0?) àTransition from 0 to 0,1,x.potential +ve edge transition
(??) àTransition in signal value 0,1, or x to 0, 1, or x
Modelling FSMs in Verilog
FSM Classification
Mealy:
Output is a function of present state and inputs. Output may
change if inputs change during clock period, due to this the
outputs may have momentary false values because of the
delay encountered from the time the input change and the
time that the FF output change.
Next state Output Output
Input
Decoder Memory Decoder
Clock
FSM Classification
Moore:
Output is a function of present state only that are synchronized
with the clock.
Input
Next state Output Output
Decoder Memory Decoder
Clock
Input
Next state
Decoder Output
Memory
Clock
FSM encoding
Encoding the states is assigning unique binary numbers to
the states
State Binary Gray One-hot
Initial 000 000 00001
S1 001 001 00010
S2 010 011 00100
S3 011 010 01000
S4 100 110 10000
FSM encoding
§ Binary
The number of storage devices (Flip-flops) is minimum.
§ Gray
If it is gray encoded, there will be only one switching
between
adjacent states. This reduces glitches at the outputs due
to
unequal delays of storage devices.
FSM encoding
§ One-hot
§ only one of the state variables will be ‘1’ and all others
will be ‘0’s for a state.
§ Complexity of Next state Decoder and Output Decoder is
reduced
§ Due to reduced complexity of Decoders , the speed of the
FSM (Max.clock frequency) is not limited by the
combinational logic. Hence Faster FSM.
§ Use “casex” for output and next state decoder
Modeling Mealy FSM
§ always@(in or pres_state) //Next
//State Decoder
§ always@(posedge clock) //Memory
§ always@(in or pres_state) //Output
//Decoder
Ex: “101” Sequence detector
Modeling Moore FSM
§ always@(in or pres_state) //NS Dec
§ always@(posedge clock) //Memory
§ always@(pres_state) //Output Dec
Ex: 3-bit counter with output ‘1’ when count
is “111”
Verilog Logic Synthesis
RTL Synthesis
What is RTL
Register : storage element, like flip-flop, latches
Transfer : transfer between input, output and register
Level : level of abstraction
RTL Synthesis
synthesis
RTL
RTL Synthesis is a process to transform design description from RTL
abstraction to the gate abstraction.
RTL Synthesis
VHDL/Verilog
Gate level Optimization
RTL level Optimization
Cell from a technology
Structural representation, specific library.
Control-Data Flow Graph
Logic Level Optimization Netlist
Fixed Synchronous logic.
Boolean equation
representation of
combinational logic
Why is RTL synthesis important?
§ It is an important tool to improve designers’ productivity to
meet today’s design complexity.
§ If a designer can design 150 gates a day, it will take 6666
man’s day to design a 1 million gate design, or almost 2 years
for 10 designers. This is assuming a linear grow of complexity
when design get bigger.
Synthesis Process
Cell Library
RTL
Synthesis
§ Cell Name
Operating Condition § Cell Type
§ Cell Function
§ Cell Area
§ Cell Timing
Design Constraint § Cell Power
§ Cell Pin
§ Area § Cell Pin Loading
§ Timing § Cell design rule
§ Power § Wire Load Table
§ Design Rule Gate
§ DFT
Synthesis Process
§ Not all Verilog commands synthesize easily.
§ For example initial initializing variables is easy to do in a
program where all variables are stored.
§ However in hardware only variables stored in flip-flops are
easy to initialize. For this reason only a subset of Verilog is
synthesizable. These presentation will concentrate on that
subset.
Technology Library
§ A Technology Library contains a set of primitive cells which can
be used by synthesis tools to build a circuit.
§ Technology libraries are created by the silicon vendor. Not by
the synthesis tools.
§ A library may contain:
§ The timing and electrical characteristics of the cells
§ Net delay and net parasitic information
§ Definition of capacitance, time and resistance units.
§ Most libraries are compiled before delivery. They can be
understood by the tools, but are unreadable to you.
Verilog Procedure
§ initial is not synthesizable and is used for test benches.
§ always without @ condition, is normally only used in test
benches
§ Variables on the left-hand side should be of type reg in a
procedural code , or at least not of type wire. In a structural
code the LHS variable should be of type wire
Only Put Latches If Necessary
§ Many procedures do not need to store values. If all left-hand
values can be calculated from a single procedure entry, nothing
needs to be stored.
§ In example2 we have initialized the value before the if statement
so that it need not have to remember the value where as in
example1, since it has to remember the values when enable =0 ,it
will infer a latch.
Example 1 Example 2
Only Put Latches If Necessary
§ Every time one executes a procedure all of the variables
defined anywhere in the procedure must be calculated.
§ If the procedure has several paths, every path must evaluate all
outputs. Else synthesis will insert latches to hold the old value
of those unevaluated outputs.
Method 1:
Set all outputs to some value at the start of the procedure.
Later on different values can overwrite those values.
always @(. . .
begin
x=0; y=0; z=0;
if (a) x=2; elseif (b) y=3; else z=4;
end
Method 2
Be sure every branch of every if and case generate every output.
always @(. . .
begin
if (a)
begin
x=2; y=0; z=0;
end
elseif (b)
begin
x=0; y=3; z=0;
end
else
begin x=0; y=0; z=4; end
end
end
Procedural synthesis
Logic Inference
Deciding what logic to synthesize from code is called inference.
always @
Can infer: flip-flops, latches, and/or combinational logic.
always @(posedge Clk)
This is the statement that tells the logic compiler to generate flip
flops.
Latches and Combinational
always @(C or D) :- This may generate a latch. It may just result in
combinational logic.
Latch Inference
Inserting Latches With or Without Your Asking
Latches form if
//Latch Inference form if
reg Q;
always @(Clk or D)
begin
if (Clk) Q <= D;
end
//No Latch Inference from if
reg Z;
always @(Ck or D)
begin
Z<=1’b0; //Initialize
if (Ck) Z <= D;
end
RTL level Optimization
§ Code related processing is first performed when a model is
synthesized. Some of the steps are:
§ Expansion - subprograms are in-lie expanded.
§ Constant folding - eg. A + 3 + 2 becomes A + 5
§ Loop unrolling - loop statements are unrolled to a series of
individual statements.
§ Dead code removal - any unused code is discarded.
RTL level Optimization
§ Bit minimization - for example, VHDL state encoding, operator
bit width, or assignments of different widths in Verilog, etc.
§ Different implementations of arithmetic operators have different
area and timing characteristics. E.g. ‘+’ operator can be carry
look-forward (fastest), carry look-ahead or ripple carry (smallest).
§ Common sub-expression sharing.
§ Operator reordering.
§ Resource sharing, etc.
CDFG format
§ The control data flow graph is often used by synthesis tools for
highest internal representation.
If (S == 1’b0) begin SELECT
L <= A + B;
M <= L + L;
FORK N=A+C
N <= A - C; end;
L=A+B
else N=A-C
M=L+L
N <= A + C;
JOIN
end if;
MERGE
CDFG level optimization techniques will be used.
Logic level optimization
§ All registered elements are fixed, only combinational logic is
optimized.
§ Optimization at this level involves restructuring of equations
according to the rules of Boolean law.
§ The types of logic optimization include:
§ minimization
§ equation flattening
§ equation factorization
§ The algorithms used work on multiple equations and multiple
outputs.
Logic level optimization
L = A.B.C M=A.B
factorize
Y1=L+A.B.D L=M.C
Y2=A.B+C+D Y1=L+M.D
Y2=M+C+D
flatten
equations
M=A.B
Y1=A.B.C+A.B.D
N=C+D
Y2=A.B+C+D
Y1=M.N
factorize
Y2=M+N
Gate Level Optimization
§ Gate level optimization consists of
§ Combinational mapping
§ Sequential mapping
§ Gate level optimization is a process of looking at local area of
logic containing a few cells and trying to replace them by other
cells from the technology library that fit the constraints better.
§ It then looks at another local area with an overlap with the first
local area. If the optimization effort is increased then the
optimizer will look at a slightly larger area each time.
Mapped circuit
before gate level
optimization.
After gate level optimization
3 cells
14 transistors
3.5 equivalent gates
Verilog Coding Guidelines
Verilog Coding Guidelines
Guideline #1: When modeling sequential logic, use nonblocking
assignments.
Guideline #2: When modeling latches, use nonblocking assignments.
Guideline #3: When modeling combinational logic with an always
block, use blocking assignments.
Guideline #4: When modeling both sequential and combinational
logic within the same always block, use nonblocking assignments
Verilog Coding Guidelines
Guideline #5: Do not mix blocking and nonblocking assignments in
the same always block.
Guideline #6: Do not make assignments to the same variable from
more than one always block.
Guideline #7: Use $strobe to display values that have been assigned
using nonblocking assignments.
Guideline #8: Do not make assignments using #0 delays.
Verilog "stratified event queue"
Electrical Properties
Signal Types
§ 0 : Logical 0, or false condition
§ 1 : Logical 1, or false condition
§ Z : High impedance state
§ X : Unknown logic condition. Can be 0, 1 or Z
Signal Types(cont)
0 0 X Z
0
1 1
Z X Z Z
1
X X
Signals (cont)
0
0 S0 Z
X
S1
1 SEL
X
X
S0 S1 SEL Z
1 X X 0 S0
1
X X X 1 S1
0 0 X 0
0 1 1 X 1
X
X
Signal Strength (cont)
Logic 0 strength Logic 1 strength
7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7
Su0 St Pu0 La0 We0 Me0 Sm HiZ HiZ Sm1 Me1 We La1 Pu1 St Su1
0 0 0 1 1 1
Su1(7)
Su1(7)
La0(4)
Verilog Syntax for Strength
Only for gate instantiation
// and gate with weak pull up
and (supply0, weak1) (out, in1, in2);
Note:
Valid strength keywords are supply1, strong1, pull1, weak1,
highz1, supply0, strong0, pull0, weak0, highz0.
Support for transmission gate
rcmos, rpmos, rnmos, rtran, rtranif0,rtrainif1 reduce the output
strength as follow:
Input Strength Output Strength
in1
Supply drive Pull drive
Strong drive Pull drive sel out
Pull drive Weak drive
Weak drive Medium in0
capacitor
High High impedance
impedance
Timing Delay in ASIC library
Pin-to-Pin delay
module AND2 (Z, A1, A2); A1 to Z delay
input A1, A2;
output Z;
and (Z, A1, A2);
specify A1
specparam A1_to_Z=12, Z
A2_to_Z=14;
(A1 => Z) = A1_to_Z; A2
(A2 => Z) = A2_to_Z;
endspecify
endmodule
A2 to Z delay
Timing Delay in Gate
Back-annotation
Delay
Verilog SDF
Calculation
Physical
Information
Timing Delay Calculation
RC
network
Output Table
Delay skew Look-up
Load Load
Cell
Library Input SDF
Skew skew
Timing Delay - SDF Back-Annotation
Using system task $sdf_annotate(). Example
§ $sdf_annotate(“full_chip.sdf”);
§ $sdf_annotate(“mod1.sdf”, mod1, , “mod1_sdf.log”);
Note:
$sdf_annotate() can be placed anywhere in the HDL code.
However, it make no sense to put it after time 0
Macros,
Conditional Compilation
&
Naming Convention
Macro
§ Macro names and the names used in the design are different
§ Macro definition is global. There is not scope restriction.
§ Macro can be re-define. The last definition read is used.
§ Keyword cannot be used as macro name. (It does not make sense).
§ One line comment (//) will be excluded in the text substituted.
§ Macro can also be defined in the command line. These macro has
the highest priority.
(e.g. verilog design.v +define+regressionSuit=“4” )
Macro Cont..
‘define WORD 8 //word size
‘define CLOCKMUX ssmux8
module register(…)
reg [‘WORD-1 : 0] cpu_reg;
…
‘CLOCKMUX hand_clockMux (…);
…
endmodule
Conditional Compilation
§ ‘ifdef, ‘else and ‘endif can be nested
§ Syntax for the ignored Verilog texts are not checked.
§ Verilog simulator does not keep record of the ignored text. Thus
any output (e.g. profiling and encryption) from the simulation does
not retain the full Verilog input.
module adder(a, b, c);
output [8:0] a; input [7:0] b, c;
reg [8:0] a;
always @ (b or c) begin
‘ifdef BEHAVIOURAL
a = b + c;
‘else
gateAdder #(8, 7, 7)i0 (a, b, c);
‘endif
end
endmodule
Good Naming Convention
§ Use all upper-case for constants specified by ‘define macro and
code inclusion control name defined by ‘ifdef and ‘define.
§ Use short instance name.
§ Unique pre-fix for modules belong to the same circuit partition.
§ Use the same port name and wire name when the signal goes
through different hierarchy.
§ Use very short name in ASIC library.
§ Do not use port names that are used in the ASIC library.
Verilog for Logic
Simulation
Introduction
Input Waveform
command
line
Simulation
Testbench Log
Key
Design
Log
File Output
$display(), $write() and $monitor() have a counterpart to write to a
specific file, beside the log file.
integer fileID;
initial begin
fileID = $fopen(“capture.dat”);
if (fileID == 0)
$finish;
$fdisplay(fileID, “Start Simulation %s”,
$pli_currentDateTime() );
end
Test bench
§ The following things are essentially required to be
provisioned a test bench.
§ timing control
§ input stimulus
§ device under test
§ reference model
§ diagnostic logging
§ assertion checking
Test bench – timing control
initial begin
#10 inputA = 1’b1;
#12 inputB = 1’b1; inputC=1’b0; inputD=1’b1;
#9 {inputA, inputB} = 2’b00;
end
initial begin
clock = 1’b0;
forever
#10 clock = !clock;
end
Waveform Probing using VCD
Verilog supports Value Change Dump (VCD) output. A VCD
waveform viewer can show the result in the form of waveform
display.
Specify VCD filename $dumpfile(“<fileName>”);
$dumpvars(<level>
Specify dump variable
<,<module or variable>>*);
Start/Stop dumping $dumpon; / $dumpoff;
Waveform Probing using VCD
$dumpfile;
§ Dump all variables in the design.
$dumpfile(1, top.mod1);
§ Dump all variables in the module top.mod1.
$dumpfile(0, top.mod1);
§ Dump all variables in the module top.mod1, and in all module
instances below top.mod1 in the design hierarchy.
$dumpfile(0, top.mod1, top.mod2.net1);
§ Dump all variables in top.mod1 and all modules instantiate
below top.mod1. Net top.mod2.net1 is also dumped. <level> only
affect module, not variable.
Interactive Debugging
Simulation control (depends on simulator)
§ $finish() : finish the simulation
§ $stop() : stop simulation and enter interactive mode
§ . : continue simulation
§ ,; : step
§ $reset : restart the simulation
§ $reset_count : number of times $reset is called
Some useful system tasks
§ $showvars() : show unresolved values of specified variables
§ $system() : execute a system command
§ $showallinstance(): show number of instances of each module,
gate and primitive in the design
Simulation Tips 1
Zero-delay loop
A common mistake in big design. Usually indicates a logic error.
module top(reset);
input reset;
reg a;
always begin
if ( !reset ) begin // what happen when
#10 a = 0; // reset is 1
#10 a = 1;
end
end
endmodule
A more complicated zero delay loop
module top; always @(posedge clk or
reg clk, reset, d; posedge reset)
reg [3:0] a, b, c, res; if(reset)
{a,b,c,d}=13’b0;
initial begin else
clk = 0; d = !d;
forever #10 clk = !clk;
end always @(a or d) begin
b = b + 1’b1;
initial begin if (d) res = b + d;
reset = 0; end
#10 reset = 1;
#10 reset = 0; always @(b) c = c + 1’b1;
#1000 $finish;
end always @(c) a = a + 1’b1;
endmodule
Simulation Tips 2
Accelerated vs. Non-accelerated Construct
…
reg var;
parameter delay=10 Accelerated
assign #delay a = b; continuous
assign #(delay + 1) c = d; assignment
assign e = f & g;
assign #var h = i; Non-accelerated
assign j = k + m; continuous
… assignment
Simulation Tips 3
Timing violation in register when crossing timing domains
unSyncD syncD
clk1
clk2
unSyncD
clk2
syncD
The timing violation can “kill” the simulation. The “X”state get
propagated to the rest of the circuit, and the simulation
becomes meaningless.
unSyncD
sel
clk1
clk2
Introduction to PLI
Where PLI is Used
§ The Programming Language Interface (PLI) provides a set of
interface routines to read internal data representation, write to
internal data representation, and extract information about the
simulation environment. User-defined system tasks and
functions can be created with this predefined set of PLI interface
routines.
§ PLI is used to customize the capability of the Verilog language
by defining their own system tasks and functions for which
designers need to interact with the internal representation of
the design and the simulation environment in the Verilog
simulator.
Simulation Flow Using PLI routines
Generations of Verilog PLI
§ Task/Function (tf_) routines make up the first generation PLI.
These routines are primarily used for operations involving user-
defined task/function arguments, utility functions, callback
mechanism, and writing data to output devices.
§ Access (acc_) routines make up the second-generation PLI. These
routines are provide object-oriented access directly into a Verilog
HDL structural description. These routines can be used to access
and modify a wide variety of objects in the Verilog HDL
description.
§ Verilog Procedural Interface (vpi_) routines make up the third-
generation PLI. These routines are a superset of the functionality
of acc_ and tf_ routines.
Uses Of PLI
§ PLI can be used to define additional system tasks and functions.
Typical examples are monitoring tasks, stimulus tasks,
debugging tasks, and complex operations that cannot be
implemented with standard Verilog constructs.
§ Application software like translators and delay calculators can be
written with PLI.
§ PLI can be used to extract design information such as hierarchy,
connectivity, fanout, and number of logic elements of a certain
type.
§ PLI can be used to write special-purpose or customized output
display routines. Waveform viewers can use this file to generate
waveforms, logic connectivity, source level browsers, and
hierarchy information.
Uses Of PLI (Contd..)
§ Routines that provide stimulus to the simulation can be written
with PLI. The stimulus could be automatically generated or
translated from some other form of stimulus.
§ General Verilog-based application software can be written with
PLI routines. This software will work with all Verilog simulators
because of the uniform access provided by the PLI interface.
Linking and Invocation of PLI Tasks
example of a simple system task $hello_verilog
#include "veriuser.h"
/*include the file provided in release dir */
int hello_verilog()
{
io_printf("Hello Verilog World\n");
}
§ Whenever the task $hello_verilog is invoked in the Verilog
code, the C routine hello_verilog must be executed. The
simulator needs to be aware that a new system task called
$hello_verilog exists and is linked to the C routine
hello_verilog. This process is called linking the PLI routines
into the Verilog simulator.
§ At the end of the linking step, a special binary executable
containing the new $hello_verilog system task is created. For
example, instead of the usual simulator binary executable, a
new binary executable hverilog is produced. To simulate, run
hverilog instead of your usual simulator executable file.
§ Once the user-defined task has been linked into the Verilog
simulator, it can be invoked like any Verilog system task by
the keyword $hello_verilog. A Verilog module hello_top, which
calls the task $hello_verilog, is defined in file hello.v as shown
below:
module hello_top;
initial
$hello_verilog; //Invoke the user-defined task $hello_verilog
endmodule
Output of the simulation is as follows:
Hello Verilog World
Summary
Summary of Verilog
§ Systems described hierarchically
§ Modules with interfaces
§ Modules contain instances of primitives, other modules
§ Modules contain initial and always blocks
§ Based on discrete-event simulation semantics
§ Concurrent processes with sensitivity lists
§ Scheduler runs parts of these processes in response to
changes
Modeling Tools
§ Switch-level primitives
CMOS transistors as switches that move around charge.
§ Gate-level primitives
Boolean logic gates
§ User-defined primitives
Gates and sequential elements defined with truth tables
§ Continuous assignment
Modeling combinational logic with expressions
§ Initial and always blocks
Procedural modeling of behavior
Language Features
§ Nets (wires) for modeling interconnection
§ Non state-holding
§ Values set continuously
§ Regs for behavioral modeling
§ Behave exactly like memory for imperative modeling.
§ Do not always correspond to memory elements in synthesized
netlist.
§ Blocking vs. nonblocking assignment
§ Blocking behaves like normal “C-like” assignment
§ Nonblocking updates later for modeling synchronous behavior
Language Uses
§ Event-driven simulation
§ Event queue containing things to do at particular simulated
times.
§ Evaluate and update events.
§ Compiled-code event-driven simulation for speed.
§ Logic synthesis
§ Translating Verilog (structural and behavioral) into netlists.
§ Register inference: whether output is always updated.
§ Logic optimization for cleaning up the result.
Little-used Language Features
§ Switch-level modeling
§ Much slower than gate or behavioral-level models.
§ Insufficient detail for modeling most electrical problems.
§ Delicate electrical problems simulated with a SPICE-like
differential equation simulator.
§ Delays
§ Simulating circuits with delays does not improve confidence
enough.
§ Hard to get timing models accurate enough.
§ Never sure you’ve simulated the worst case.
§ Static timing analysis has taken its place.
Verilog Strengths and Weaknesses
§ Verilog is widely used because it solves a problem
§ Good simulation speed that continues to improve.
§ Designers use a well-behaved subset of the language.
§ Makes a reasonable specification language for logic synthesis.
§ Logic synthesis one of the great design automation success
stories.
§ Verilog is a deeply flawed language
§ Non-deterministic.
§ Often weird behavior due to discrete-event semantics.
§ Vaguely defined synthesis subset.
§ Many possible sources of simulation/synthesis mismatch.
References
§ http://www.asic-world.com/verilog/.
§ Palnitkar, Samir, Verilog HDL: A Guide to Design and Synthesis
§ www.sunburst-design.com.
§ IEEE Standard Hardware Description Language Based on the
Verilog Hardware Description Language, IEEE Computer
Society, IEEE Std 1364-1995.
ThanQ