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

§ A Hardware Description Language is one that can describe circuit’s operation. § Usually deal with the design of digital logic circuits and systems.HDLs – WHAT-WHY-HOW § WHAT is a HDL? § HDLs – A class of programming/computer languages used for formal description of electronic circuits. . conceptual design & organization and can test it by means of simulation.

§ These needs led to a the use of CAD techniques for digital design. § Highly important to find potential functional bugs in the early stages of 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? § It is impractical to verify large circuits on breadboards or large chips after manufacturing.

etc. (C.HDLs – WHAT-WHY-HOW § WHY were HDLs required? (contd.) § Digital logic circuits involve Concurrency of operations.) § Software Programming languages – Sequential in nature. Pascal. § Traditional programming languages lack the capability for explicitly expressing time.. Time consuming & Costlier. § Using s/w programming languages to represent hardware is – Inconvenient. FORTRAN. .

. § Designers can develop an executable functional specification that documents the exact behavior of all the components and their interfaces. and optimization. § Designers can create tools which automatically manipulate the design for verification. § Designers can make decisions about cost. power. synthesis. and area earlier in the design process.HDLs – WHAT-WHY-HOW § HOW are HDLs advantageous? § Allows designer to talk about what the hardware should do without actually designing the hardware itself. performance.

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 . Implementation CPU SubSystem RTL Gate level Treansistor level Arith Reg.. Design adder subtr . Mem..

Hardware Design Flow § HDLs and CAD tools are used to describe hardware for: § Design & Modeling § Simulation § Synthesis § Testing § Documentation .

Verilog HDL Introduction .

§ SystemVerilog – Extended from Verilog and C++. § Verilog 2001 – IEEE Standard 1364-2001. § Later .History § Invented by Phil Moorby & Prabhu Goel at Gateway Design Automation Systems in 1983/84. § Verilog 2005 – IEEE Standard 1364-2005. § Verilog-95 – IEEE Standard 1364-1995. Cadence took full proprietary in 1990. § In 1995. Cadence published Verilog for public domain under OVI (Open Verilog International). .Verilog HDL .

§ Simulated to check functionality. § Design written in Verilog.How Verilog Is Used § It is a general purpose HDL with support for . § Synthesized (netlist generated). . § Allows different levels of abstraction to be mixed in the same design. § Static timing analysis. § “Synthesis subset” § Can be translated using Synopsys’ Design Compiler or others into a netlist.

§ § § § Behavioral Level Dataflow Level Gate Level Switch level Behavioral Dataflow Gate Level Switch level Lowest Abstraction Level Highest Abstraction Level § Register Transfer Level (RTL) § A combination of both Behavioral & Dataflow constructs. .Levels of Abstraction § Verilog supports a design at 4 different levels of abstraction. § Acceptable to logic synthesis tool.

) § Behavioral Level :. § Gate Level :. § Switch Level :.Levels of Abstraction (Cont..Describes the logic gates and the connections between logic gates in a design.Describes the flow of data between registers and how a design processes that data.Describes the transistors and storage nodes in a device and the connections between :-describes them . § Data Flow Level :.Used to model the behavior of a design without describing its actual hardware structure.

and § Bottom-up design methodology. We build bigger cells. we define the top-level block and identify the sub-blocks necessary to build the top-level block.Design Methodologies § There are 2 types of design methodologies: § Top-down design methodology. we first identify the building blocks that are available to us. . using these building blocks. § In a bottom-up design methodology. § In a top-down design methodology.

Design Methodologies (Cont..) Top-Level Block Subblock1 Subblock2 Subblock3 Leaf Cell Leaf Cell Leaf Cell Leaf Cell Leaf Cell Leaf Cell Top-Down Design Methodology .

.Design Methodologies (Cont.) Top-Level Block Macro Cell1 Macro Cell 2 Macro Cell 3 Leaf Cell Leaf Cell Leaf Cell Leaf Cell Leaf Cell Leaf Cell Bottom-Up Design Methodology .

§ A corresponding keyword endmodule must appear at the end of the module definition. § In Verilog a module is declared by the keyword module. § Elements are grouped into modules to provide the common functionality that is used at many places in the design.Modules § A module is the basic building block in Verilog. . § A module provides the necessary functionality to the higher-level block through its port interface (inputs and outputs).

Modules (Contd. § Module instantiation is like creating actual objects (Instances) from the common template (module definition). and § connecting test bench to the design. § Each instance of module has all the properties of that module.. one module can instantiate another module. § Module instantiations are used for: § connecting different parts of the designs. .) § Modules CANNOT be nested. § Rather.

§ Use them to make your design more readable and manageable.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. § Debugging individual module is a lot easier than debugging the whole system together. § Verilog modules are like modules in schematics or classes in C++.

<statements>. // input. begin. always // dataflow statements endmodule . // initial. etc. end. register. output. inout // wire.Structure of module module <mod name> (<port list>). <declarations>.

always constructs.Structure of module (Contd.. . memories and wires as wells as procedural constructs such as functions and tasks. § The <declares> section specifies data objects as registers. inout and output ports which are used to connect to other modules. continuous assignments or instances of modules. § The <port list> is a list of input. § The <statements> may be initial constructs.) § The <module name> is an identifier that uniquely names the module.

.

Basic Languages Concepts .

-4’b11 .. space § String with double quotes § Identifier § A letter or _ can be followed by letters.Lexical Conventions § Keywords § In lower case § Case sensitive § Delimit tokens.3’b10x. digits. 4’b11. ‘o765.549. $ and _ § Max 1024 characters § Numbers § [<sign>] [<size>] <base> <num> § e.g. ‘h8ff.

1:not ready output data. */ input status. 2009 No unauthorized copying is allowed. Block comment cannot be nested. Example /* Copyright Kacper Technologies Pvt Ltd. // sync with clock mClock . and end with */. and end with newline. // 0:ready. Block comment. start with /*.Verilog Comments Verilog supports 2 type of comment syntaxes § § Single line comment start with //.

X. Default is ‘decimal’ 0-9. ‘d. (usually 32 bits) ‘b. ‘O. ‘B. ‘o. a-f. ?. ‘h. ‘D. ‘H.Verilog Number Specifications § § Two representations: sized & unsized Format:<number of bits><base><number> <number of bits> <base> <number> Bit length in decimal. default is host machine word size. This is an optional value & if not specified. _ . Z. A-F.

Num = ‘d-12. .Verilog Numbers Specifications (Contd. § // Negative number // 8 bit –ve number // Illegal !! // _ for readability .) § Negative numbers: put minus sign before size. Reg [31:0] data. Num = -6. § Represented by 2’s complement internally. Num = -8’d4. reg [5:0] Num.. data = 32’h_1234_5678.. Often _ (Underscore) is used in between digits of the number for readability. § Format: -<size><base><number> § <size> field is always +ve.

Num = ‘b11??1. Num = 6’b_100x. z ? high impedance value A question mark ‘?’ can also be used as an alternative to ‘z’. Reg [31:0] data. reg [5:0] Num.. x ? unknown value. // Num = 6’b00100x // 32 bit no with all x bits // Num = 6’bzzzz01 // Num = 6’b011zz1 // data = 32’hX5f32693 . . data = 32’bx..) § § § Verilog numbers may have x or z as part of numbers. data = 32‘h_x5f3_2693. Num = ‘bz01.Verilog Numbers Specifications (Contd.

wire status. Num = ‘bx. … Num = 16. if (status == 1) Num = 8’b1010_0101. Num = ‘b10x. Num = -8’d4.Verilog Numbers: Example module Verilog_number. reg [7:0] Num. Num = ‘b0x. if (status == 1’b1) … endmodule // 8’b0001_0000 // two’s complement of 4 // 8’bxxxx_xxxx // 8’b0000_000x // 8’b0000_010x // status == 32’h0001 // status == 1’b1 .

k. k = r.0 Reg[7:0] B. C.Data Types § reg: Register § § § § Integer & Real Data Types § Declaration wire: Wire/net integer i. § Reals are initialized to 0. real r. reg A. x. 1. // k is rounded to 3 § Integers are not initialized in Vector: Verilog!! Reg[0:7] A. Default: 1-bit (Scalar) r = 2.9. § . B. Possible Values: 0. z § Use as registers (inside procedures) i = 1.

§ They are always driven by some source. § Default value for any net type variable is ‘z’. . triand. etc. wand.Nets § Nets represent the connections between hardware elements. § Different types: wire. § Usually. trireg. wor. tri. trior. declared by the keyword wire. § wire is the most common of all.

.

Registers § These correspond to variables in the C language. § Unlike nets. registers do not need any drivers. § 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.

Registers (Contd. However. . the compiler will generate latches or flip-flops for them. 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..) § In synthesis.

. § A variable is declared of type wire if it appears on the left side of an continuous assignment statement. reg is assigned within always or initial blocks.) § So.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.” § Verilog register data types: reg / time / integer / real / realtime / event (reg is the most common of all. § Structural code continuous assignment statements start with the keyword assign.”All other variables are of net type.

§ Usually preferred for arithmetic manipulations over reg. § Differs from reg type as it stores signed quantities as opposed to reg storing unsigned quantities. . § Declared with keyword integer.Integers § A general purpose register data type with default value having all x bits. § Default width: host machine word size (minimum 32 bits).

Real Numbers § Real number constants declared with a keyword real. the real number is rounded off to the nearest integer. § Two notations: Decimal & Scientific notation. § When a real value is assigned to an integer. § Real numbers CANNOT have a range declaration. § Real constants have default value of 0. .

§ Depending upon the timescale specified. realtime provides the simulation time with the fractional part with given precision. it is used to store the simulation time. § time is an unsigned 64-bit by default.Time & Realtime Data types § time – A special register data type used mainly to store simulation time. . Usually. § realtime is similar to time except that it has initial value of 0.

NOR Reduction AND .Logical Operators Operator ~& | ~| ^ ~^ or ^~ == or === != or !== > >= < <= ?: Operation Reduction NAND Reduction OR Reduction NOR Reduction XOR Reduction XNOR Logical Inequality Logical Inequality Relational Conditional Operator Operation ! && || ~ & | ^ ^~ or ~^ & Logical Negation Logical AND Logical OR Bit-wise Negation Bit-wise AND Bit-wise OR Bit-wise Exclusive OR Bit-wise Ex.

False (“0”) or Unknown (“X”) Examples 1’b1 && 1’b0 2’b11 && 2’b10 2’b1X && 2’b11 0 0 X 1’b1 || 1’b0 2’b11 || 2’b10 2’b1X || 2’b11 1 1 1 .Logical Operation Example operand1 operand2 1 2 3 4 5 6 7 8 && A B C D E F G H True (“1”).

Bitwise Operators § & § | § ~ → bitwise AND → bitwise OR → bitwise NOT § ^ → bitwise XOR § ~^ or ^~ → bitwise XNOR § Operation on bit by bit basis 8 & A B C D E F G H 1 2 3 4 5 6 7 1 & A 2 & B 3 & C 4 & D 5 & E 6 & F 7 & G 8 & H .

xor. $displayb(& a). or. (same as 1&1&1&1) // evaluates to 1 // bitwise or (evaluates to 1) . $displayb(| b). nor. ~|. They take one operand and perform a bit-bynext-bit operation. § The reduction operators are and. initial begin a = 4'b1111. end // bitwise and. ~&. ^. ~^. b = 4'b0101.Reduction operators § Key symbols: &. starting with the two leftmost bits. nand. |. xnor and an alternative xnor. giving a 1bit result. ^~. c = 4'b0011.

Reduction operation & 1 2 3 4 5 6 7 8 1 & 2 3 & & 4 5 & 6 7 & & 8 & .

displays 0100 //shift right by 2.Shift operators § Key symbols: >>. § The empty bits caused by shifting are filled with zeros. displays 0010 . § The shift operators are shift left and shift right. $displayb(a << 1). The shift operator takes a vector and a number indicating the shift. initial begin a = 4'b1010. $displayb(a >> 2). reg [3:0] a. <<. module shiftTest. end endmodule // shiftTest // shift left by 1.

Y = A if sel is ‘1’ B if sel is 0 .Conditional Operator § cond_expr ? true_expr : false_expr § A ternary operator § Acts like a 2-to-1 mux. A B 1 0 sel Y Y = (sel)? A : B.

// catx = 1_010_101 caty = {b.} → concatenates op1. a = 1’b1. catx = {a. a}.. b. c = 3’b 101. . op2.. // caty = 010_11_1 catz = {b.c. reg [2:0] b. 2’b11.b = 3’b 010. op2.Concatenation Operator § {op1. § Operands must be sized !! … reg a. // WRONG !! … . 1}. . to single number. c}.

… reg a. b.Replication Operator § <no> { <variable/sized_number> } § <no> is an integer. c = 3’b 101. a = 1’b1.b = 3’b 010. 2{c}}. // catr = 1111_010_101101 … .c. catr = {4{a}. reg [2:0] b.

.4’b1z0x == 4’b1z0x → x 4’b1z0x === 4’b1z0x → 1 .g.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.

Operator precedence Operators Unary Multiply.! ~ * / % + >> << < <= >= > == != === !== & ~& ^ ^~ | ~| && || ?: Lowest Precedence Highest Logical Conditional . Subtract Shift Relational Equality Reduction Operator Symbols + . Divide. Modulus Add.

§ There are 2 representations for vectors: § A little-endian notation: [high# : low#] § A big-endian notation: [low# : high#] wire [3:0] busA. reg [1:4] busB. § The left most number is an MSB (Most Significant Bit). reg [0:15] busC. // little-endian notation // big-endian notation .Vectors § Vectors have multiple bits and are often used to represent buses.

end // Accessing only bits 16 to 9 of data = dest_addr[0] dest_addr[1] dest_addr[2] dest_addr[3] = out[60]..Vectors (Contd.) § Vector Part Select data[15:8] = 8’h_12. = out[62]. . reg [3:0] dest_addr. inter_carry = carry[1:3]. § Slice management reg [63:0] out. = out[61]. initial begin dest_addr = out[63:60]. = out[63].

. bus_A[1] = bus_B[1]. end … = bus_A[2] = bus_B[0]. bus_A[0] = bus_B[2]. reg [0:2] bus_B. initial begin bus_A = bus_B.) § Vector assignment (by position!!) … reg [2:0] bus_A..Vectors (Contd.

Vectors (Contd. … nibble1 = data1[31-:4].: <width>] reg [31:0] data1. // selects 4 bits from 31 to down. reg [0:3] nibble2.e. i. [31:28] byte1 = data1[24-:8].. // selects data1[24:17] byte2 = data2[10+:8]. // selects data2[10:17] nibble2 = data2[28+:4]. reg [0:7] byte2. reg [0:31] data2. reg [7:0] byte1.) § Variable Vector Part Select § [<starting_bit>+ : <width>] § [<starting_bit>. reg [3:0] nibble1. // selects data2[28:31] .

§ Escaped chars: \n for newline \\ for \ \t for tab %% for % \” for “ \ooo characters as octal … reg [8*13:1] string_val. // MS Bytes are filled with 0 string_val = “I am overflowed”.. string_val = “hello”. // can hold up to 13 chars ..Strings § Implemented with regs. // “I ” is truncated … . string_val = “Hello Verilog”.

// array of check-points real results [39:0]. § Verilog supports multi-dimensional arrays. § Elements are accessed by: <ary_name> [<index>]. // array of buses reg [31:0] payload [34:0]. // array of integers with 20 elements wire [3:0] y [10:1]. integer ary1 [19:0]. // array of real numbers .Arrays § Declaration: <type> <vector_size> <ary_name> <ary_size>. // array1 is an array with 100 elements // each element is of 1 bit. § <ary_size> is declared as a range. // array of vectors time checkpoints [1:50]. reg array1 [99:0].

) //Multi-dimensional arrays reg [7:0] sonet_frame [89:0][8:0]. // a 2-dimentional array representing the SONET frame. // 3-dimentional array of integers ..Arrays (Contd. reg [7:0] matrix3d [9:0] [24:0] [3:0].

… reg [7:0] string_val [99:0]. reg [7:0] ray2d [4:0] [49:0]. // a memory with 100 elements // each of 1 byte // 2-dimentional array reg [31:0] mem32 [`DEPTH-1:0]. // 32-bit memory … .Memories § Declaration: reg <vector_width> <ary_name> <no_of_locations>.

Connectivity in Verilog .

.

. § A wire if it is assigned through continuous assignment. § An output port must be a wire if it is generated declaratively. § The following are true of module interfaces: § An input or inout port is a wire type within its module. and inout (bidirectional ports) for interfaces. § Bidirectional ports cannot be assigned to procedurally.Port assignments § Modules contain functional descriptions and have input. § An output port must be § a reg if it is assigned to procedurally. § An output port must be a wire if it is generated by a submodule. output.

.

Unconnected ports are designated by two commas with no signal listed. in any order. . module instantiation is used to make connections between different parts of the design.Module Instantiations § As we saw earlier. § Port named instantiation lists the port name and signal connected to it. § 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.

.. ). ).. . signal..) § Connections by Ordered List <module_name> <instance_name> [instance_array_range] ( signal.Module Instantiations (Contd. § Connections by Named List <module_name> <instance_name> [instance_array_range] ( . .port_name(signal). . .port_name(signal)..

.Module Instantiations (Contd. § Instantiations together.) § 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. are used for connecting different modules . the instance will have all the properties of the lower level module.

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 D (Signals)

nand1

nand2

§ Signals of the dff may be accessed using hierarchical naming as shown below: TB_TOP TB_TOP.dff1.Q TB_TOP.nand1 TB_TOP.nand1.o1 TB_TOP.dff1.QB

Modeling using Verilog

buf bufif1.Gate Level Modeling § Verilog has built in primitives like gates. xnor not. and switches. nand. notif0 . These cells are then used for gate level simulation or what is called as SDF simulation. but are used in post synthesis world for modeling the ASIC/FPGA cells. or. xor. transmission gates. notif1. § These are rarely used for in design work. bufif0. nor. § Ex:.and.

Gate Level Modeling (Contd. // 4 input XOR gate and x2(z. nand n1(z. a. b).. b. c.) § The gates have one scalar output and multiple scalar inputs. a. b. a. // Inverter bufif0 U1( data_bus. // 2 input NAND gate xor x1(z. // 3 input AND gate or(z. a. // Buffer not n1(out. data_enable_low ). c). // Instance name is optional buf b1(out. d). b). § Gate instance name is optional. § The first terminal in the list of gate terminals is an output and the other terminals are inputs. data_drive. in). . in).

.

.

.

.

.

.

§ Turn-off Delay: associated with a gate output transition to z from another value. § If the output of gate changes to ‘x’.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. . the minimum of the three delays is considered.

.

§ Min.Gate Delays (Contd. fall_time. maximum and typical delay value that a designer expects the gate to have.. § The gate delay cam be specified as follows: <gate_primitive> #(rise_time. . typ or max values can be chosen at runtime by options provided in the simulator. turnoff_delay) § The gate delay can be specified with only one delay time or rise and fall times or with all 3 delay values.) § Min / Max / Typ delay values: They represent the minimum.

fall & turnoff delays and #(10) a1( and_out. in). i1.. fall and turnoff delays // For transition to x. i3 ). 5) // examples for #(min : typ : max) values not #(2:3:5) inv(out.Gate Delays (Contd. the delay is taken as min(1. i2. in2 ).) // rise.16) OR( op. 5) xg( o. // rise & fall times xor #(1. // delay time or #(14. in1. b ). // rise. 3. 3. // min delay=2 // typ delay = 3 // max delay = 5 . a.

max rise delay=5 min fall delay=2. 1:4:7 ) inv( out.max turnoff delay=3 */ . in1. typ rise delay=3. /* min rise delay=2. in2 )..Gate Delays (Contd. typ fall delay=4. in ). max fall delay=5 buf #( 2:3:5. typ turnoff delay=1. max rise delay=5 // min fall delay=1. max fall delay=5 min turnoff delay=0. typ rise delay=3. typ fall delay=3. 1:4:7.) nor #( 2:3:5. 0:1:3 ) inv( out. // min rise delay=2.

xor #5 x1( sum. carry.2. input a. a. fall and turnoff delay and #(1. a. b. b ). a.Gate Level Modeling Examples // 1-bit Half Adder module ha( sum. output sum. b ). // rise. endmodule . carry.3) a1( carry. b ).

CLK) . Q_BAR.Y)..X).Q. nand U3 (Q. CLK ).Q_BAR. nand U4 (Q_BAR.CLK) . D.) module dff ( Q. endmodule . // Four Instantiations of nand gates nand U1 (X.Gate Level Modeling Examples (Contd.CLK.X. nand U2 (Y. input D. output Q.D.Q_BAR.

§ Dataflow modeling involves continuous assignments. that is driving values to the net. . § Syntax: assign <drive_strength> #<delay> <list_of_assignments>.Dataflow Modeling § The data flow between registers and the way that data gets processes is modeled using dataflow modeling. § assign is used to drive value on the net by continuos assignment.

.) // Regular continuous assignment wire out. // Same effect is achieved by an implicit continuous assignment wire out = var1 & var2. assign out = var1 & var2.Dataflow Modeling (Cont. .

#10 A = A + 1. e.g. A number followed by # shows the delay value.Delays § A delay control expression specifies the time duration between initially encountering the statement and when the statement actually executes. logic gates have delays associated with them. . § In real circuits . § The delay is represented using #. § There are different ways to specify delays in continuous assignments. Verilog provides the mechanism to associate delays with gates.

// which is equivalent to the following: // wire out.g.) § Regular Assignment Delay: § This is the most commonly used method. § Implicit Continuous Assignment Delay: § Similar to implicit assignment statement with delay added.g. § e. – wire #10 q = a ^ b. § e. // assign #10 out = a ^ b.assign #10 q = x + y.Delays (Cont.. .

) § Net Declaration Delay: § The delay can be put on the net in declaration itself. § e.. assign out = a & b. // assign #10 out = a & b.Delays (Cont.g. // which is equivalent to the following: // wire out. . – wire #10 out.

noo. input a. assign invo = ~a. oo. xoo. output ao. assign noo = #3 a ~| b. assign ao = a & b. noo. xno. oo. b. a. xoo. ao. assign xno = a ~^ b. endmodule . nao. #10 assign oo = a | b. b ).Dataflow Modeling Examples // All basic logic gates module gates( invo. nao. assign #1 nao = a ~& b. xno. assign xoo = a ^ b.

b. sel ).. input [3:0] a. endmodule . input sel.Dataflow Modeling Examples (Contd. assign op = sel ? a : b. a.) // 2:1 Multiplexer module mux21(op. b. output op.

the details of the handshake mechanism between different processes are implied. input data received data data ready request data overflow acknowledge data .Behavioral Modeling § In RTL and Gate level implementation. The states are cycle-to-cycle accurate.

§ In behavioral modeling.) § 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.. you can use events for synchronizing.Behavioral Modeling (Contd. The details of implementation is based on the application. input data received data data ready request data .

Assignment inside procedural blocks are called procedural assignment. All the circuitries are active in parallel. § Verilog supports parallelism by allowing any number of “always” and “initial” blocks. . However.g. hardware circuitry is concurrent in nature. C..) § Most of the programming languages (e. or only one active process at any one time. Basic) are sequential in natural. Each “always” and “initial” block run concurrently. § always and initial blocks are called procedural blocks.Behavioral Modeling (Contd.

initial begin … imperative statements … end § Runs when simulation starts § Terminates when control reaches the end § Good for providing stimulus always begin … imperative statements … end § Runs when simulation starts § Restarts when control reaches the end § Good for modeling / specifying hardware .Procedural Blocks § Procedural blocks are the basic components for behavioral modeling.

initial begin #10 a = 1.Procedural Blocks (Contd. a = 1. wait(~i). b = 1.. end . #10 a = 0. end § or a wait for an event always @(posedge clk) q = d. b = 0.) § Run until they encounter a delay. always begin wait(i). a = 0.

§ initial block § Executes only once. It must have timing control. (unless delay is specified) § All blocks execute in parallel. § Statements in a block are executed sequentially.. § always block § Executes repeatedly.Procedural Blocks (Contd. but all within one unit of simulated time.) § Procedural blocks are like concurrent processes. otherwise it become INFINITE LOOPS .

. The sensitivity list is used to model combinational and sequential logic behavior. § always procedural blocks process statements repeatedly. § initial procedural blocks process statements one time. § sensitivity_list (optional) is an event timing control that controls when all statements in the procedural block should be evaluated.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..

.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. § Each timing control is absolute to when the group started. § Each timing control is relative to the previous statement. so that all statements evaluated concurrently. § fork & join are used to two or more statements together in parallel. . so that statements are evaluated in the order they are listed.

assignment may set wire values . § Primitives or cont.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.

Blocking & Non-blocking Assignments § There are two types of assignment statements are there in Verilog: § Blocking statements § Non-blocking statements. § A blocking assignment must evaluate the RHS arguments and complete the assignment without interruption from any other Verilog statement.It is a way of blocking the further statements until the current statement execution is completed. § The assignment is said to "block" other current assignment has completed. § Blocking Assignment:. assignments until the .

§ 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 & Non-blocking Assignments § Non Blocking assignments allow scheduling of assignments without blocking execution of the statements that follow in a sequential block.

§ The blocking assignment with timing delays on the RHS of the blocking operator. such as on the same clock edge. § 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.Blocking Assignments § The blocking assignment operator is an equal sign (=). which is considered to be a poor coding style.

Blocking Assignments (Contd. a race condition can occur. the order execution is unknown.) § If blocking assignments are not properly ordered.. . § When blocking assignments are scheduled to execute in the same time step. § 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.

endmodule . rst. input clk. y2. reg y1.Blocking Assignments Example module fbosc1 ( y1. rst ). output y1. clk. // preset else y2 = y1. always @( posedge clk or posedge rst ) if (rst) y2 = 1. always @(posedge clk or posedge rst ) if (rst) y1 = 0. // reset else y1 = y2. y2. y2.

the design won’t behave like shift register! .A Flawed Shift Register § The following code doesn’t work as one may expect: module flawed_sr. d4. reg d1. d2. So. always @(posedge clk) d3 = d2. the order of execution becomes tool-specific. always @(posedge clk) d2 = d1. endmodule § Because of all blocking assignments in different always blocks. always @(posedge clk) d4 = d3. d3.

and § schedules the LHS update to take place at the end of the time step. other Verilog statements can be evaluated and updated. . § They are called “non-blocking” because§ the assignment evaluates the RHS expression of a it at the beginning of a time step. § Between evaluation of the RHS expression and update of the LHS expression.Non-blocking Assignments § The non-blocking assignment operator is the same as the lessthan-or-equal-to operator ("<=").

the RHS expression of other Verilog non-blocking assignments can also be evaluated and LHS updates scheduled.. § Update the LHS of non-blocking statements at the end of the time step.) § Also.Non-blocking Assignments (Contd. § Verilog statements from being evaluated. . The non-blocking assignment does not block other. Execution of nonblocking assignments can be viewed as a two-step process: § Evaluate the RHS of non-blocking statements at the beginning of the time step.

rst ). endmodule . output y1. input clk.. y2. // reset else y1 <= y2. rst. clk. y2. reg y1. always @( posedge clk or posedge rst ) if (rst) y2 <= 1. y2. always @( posedge clk or posedge rst ) if (rst) y1 <= 0.) module fbosc2 ( y1.Non-blocking Assignments (Contd. // preset else y2 <= y1.

) Nonblocking rule: This version works: reg d1. LHS updated only after all events for the current instant have run RHS evaluated when assignment runs . always @(posedge clk) d2 <= d1.. d3.Non-blocking Assignments (Contd. always @(posedge clk) d4 <= d3. always @(posedge clk) d3 <= d2. d4. d2.

b <= a. a b c “ ” .Non-blocking Looks Like Latches a = 1. “ a 1 b c ” 1 a <= 1. c = b. c <= b. b = a.

“while” and “repeat” and “forever” loop // example of “for” loop for( i=0. end .Looping Flow Control Verilog supports “for”. i<`MEMSIZE. end // example of “while” loop i = 0. while(i<`MEMSIZE) begin mem[i] = 8’b0. i=i+1) begin mem[i] = 8’b0.

repeat (`MEMSIZE) begin mem[i] = 8’b0. i = i + 1. if (i == `MEMSIZE) disable mem_init. end . end // example of “forever” loop i = 0. i = i + 1. forever begin : mem_init mem[i] = 8’b0.// example of “repeat” loop i = 0.

§ Use task or function when: § A section of the code that is used more than once. . § Break long procedural blocks into smaller parts in order to improve readability and maintenance of the code. with possibility different inputs.Task and Function § Verilog support encapsulation of a piece of code into a task or a function. § A code that is expected to be issued interactively.

Difference between task and function § A task can have timing control constructs. § A task can have inputs and outputs. whereas function must have at least one input and only one output. § The code that initiated a task has to wait for that task to complete or disabled before continuing execution. (which is the name of the function itself) . whereas function cannot. A function can only model combinatorial functionality.

endfunction . endtask Example of a function function [1:0] function_example. in2. out2. in2. input [1:0] in1. #1 out2 = in1 | in2.Example of a task task task_example. output [1:0] out1. input [1:0] in1. #1 out1 = in1 & in2. function_example = in1 & in2.

§ $display : This system task is used to display the text and formatted data on the screen. § $stop: It stops /suspends the simulation. it displays the formatted string specified within double quotes. Whenever. any one of them changes. § $monitor : It continuously monitors the changes in any of the variable/signal specified in the parameter list. It inserts a newline at end of display text automatically.System Tasks § Verilog has some of the inbuilt task as part of the language itself. .

System Tasks (Contd. When one wants to display the values of the variables which are assigned within non-blocking statements. § $write: It is similar to $display except that it does not insert a newline at the end of the formatted output by default.) § $finish: It terminates the simulation. it is a good practice to display them using $strobe. It is used mainly in test bench. § $random: It generates a 32-bit signed integer randomly. § $strobe: It is used for strobing purpose. ..

.System Tasks (Contd. § $realtime: Same as $time excepts it shows the fraction part as well. .) § $time: It returns the current simulation time.

`timescale <ref_time_unit>/<precision> . § `timescale: It is used to specify the timescale for simulation. It has two parts: reference time unit & time precision.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. First one specifies the time unit and the later determines the minimum unit that is considered for any round off.

\nA = %d”. a). $display(“Initializing…. monitor($time. end always #25 a = $random. reg [3:0] a. #300 $finish. a). initial begin a = 3. “ \tA = %d”.System Tasks & Compiler Directives Example `timescale 10ns/1ns `define A 10 module abc(). 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 .

) § Verilog supports “event” data type.. … endmodule § Trigger an event using “ ->event_variable” § Wait for an event using “@event_variable” . event e1.Synchronization (Contd. module event_example. e2.

always begin … fork <statement 1>. … <statement N>.Synchronization – fork and join module barrel_sync. <statement 2>. join <statement S>. end endmodule <statement 1> to <statement N> are executed in parallel <statement S> is executed only when <statement 1> to <statement N> are completed .

execution continues from the start of the always block … always begin : write_block <statement 1>. out=#10 ram[index] from the previous cycle) will be removed. end … if “write_through”is true.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 start from <statement 1> . all pending events (e. … if ( write_through ) disable write_block. out = #10 ram[index].g.

end .Forever Statement § This loop executes continuously and never completes. as shown in an example: § Syntax. § An infinite loop that continuously executes the statement or statement group. § Infinite loops in Verilog use the keyword forever. forever #50 clock=~clock. forever<execution statement> initial begin clock=0. § expression to prevent combinational feedback. § You must break up an infinite loop with an @(posedge clock) or @(negedge clock).

Generate Statements § Generate statements are used when the same operation or module instance is repeated for multiple bits of vector. § All generate instantiations are coded with a module scope and require keywords generate – endgenerate. functions and tasks as well as control over instantiations. . § Generate case. § Generate statements allow control over the declaration of variables. § There are three methods to create generate statements: § Generate loop. § Generate conditional.

.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.

parameter <identifier> = constant. § Used to pass information globally.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 byte_size = 8. . reg[byte_size-1:0] A.

Race Conditions .

. as permitted by the Verilog Standard. § It can be eliminated by using non-blocking assignments instead of blocking assignments.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.

initial begin a=0.Race Conditions & their Solutions module race. § The solution is to delay the end. two parallel blocks have no guaranteed ordering. . $display with a #0 delay: initial begin #10 if (a) initial begin $display(“may not print”). reg a. #10 a=1. endmodule end § In this example. #10 if (a) end #0 $display ("may not print"). so it is ambiguous whether the $display statement will be executed.

Flip-Flop Race Condition module test( out. in. clk. dff dff0( a. output q. d. a. in. input in. clk ). clk ). dff dff1( out. clk. clk ). reg q. always @(posedge clk) q = d. output out. // race! endmodule . clk ). input d. wire a. endmodule module dff( q.

always @(posedge clk) q <= #1 d. . § 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.§ It is very common to have race conditions near latches or flipflops. always @(posedge clk) q = #1 d. always @(posedge clk) q <= d. § 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.

UDPs .

designers occasionally like to use their own custombuilt primitives when developing a design. nor. and not. or.User Defined Primitives § Verilog provides a standard set of primitives. nand. § Verilog provides the ability to define User-Defined Primitives (UDP). . as a part of the language. These are also commonly known as built-in primitives. such as and. § However.

) § 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. The value of the output is also the internal state of the UDP.. § Sequential UDPs take the value of the current inputs and the current output to determine the value of the next output. . Good examples of sequential UDPs are latches and flip-flops.User Defined Primitives (Contd. A good example is a 4-to-1 multiplexer.

The inputs are declared with the keyword input. UDPs can have only one scalar output terminal (1 bit). the output terminal must also be declared as a reg. Since sequential UDPs store state. Multiple output terminals are not allowed. § § § § .Rules to Define UDP § UDPs can take only scalar input terminals (1 bit). Multiple input terminals are permitted. the output terminal is declared with the keyword output. In the declarations section. The terminal must always appear first in the terminal list.

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; 0 ? ? ? 0 0 : 0; ? 1 ? ? 0 1 : 1; ? 0 ? ? 0 1 : 0; ? ? 1 ? 1 0 : 1; ? ? 0 ? 1 0 : 0; ? ? ? 1 1 1 : 1; ? ? ? 0 1 1 : 0; ? ? ? ? x ? : x; ? ? ? ? ? x : x; endtable endprimitive I0 I1 I2 I3 S0

Out
Mux

S1

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 .

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.FSM Classification Mealy: Output is a function of present state and inputs. Input Next state Decoder Memory Output Decoder Output Clock .

FSM Classification Moore: Output is a function of present state only that are synchronized with the clock. Input Next state Decoder Output Decoder Output Memory Clock Input Next state Decoder Output Memory Clock .

FSM encoding Encoding the states is assigning unique binary numbers to the states State Initial S1 S2 S3 S4 Binary 000 001 010 011 100 Gray 000 001 011 010 110 One-hot 00001 00010 00100 01000 10000 .

. there will be only one switching between adjacent states. This reduces glitches at the outputs due to unequal delays of storage devices.FSM encoding § Binary The number of storage devices (Flip-flops) is minimum. § Gray If it is gray encoded.

§ Use “casex” for output and next state decoder .clock frequency) is not limited by the combinational logic. Hence Faster FSM.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.

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 .

output and register : level of abstraction . latches : transfer between input.RTL Synthesis What is RTL Register Transfer Level : storage element. like flip-flop.

.RTL Synthesis RTL synthesis RTL Synthesis is a process to transform design description from RTL abstraction to the gate abstraction.

Control-Data Flow Graph Gate level Optimization Cell from a technology specific library.RTL Synthesis VHDL/Verilog RTL level Optimization Structural representation. Logic Level Optimization Fixed Synchronous logic. Boolean equation representation of combinational logic Netlist .

or almost 2 years for 10 designers. . it will take 6666 man’s day to design a 1 million gate design. § If a designer can design 150 gates a day.Why is RTL synthesis important? § It is an important tool to improve designers’ productivity to meet today’s design complexity. This is assuming a linear grow of complexity when design get bigger.

Synthesis Process Synthesis RTL Cell Library § § § § § § § § § § § § § § § Operating Condition Design Constraint Area Timing Power Design Rule DFT Cell Name Cell Type Cell Function Cell Area Cell Timing Cell Power Cell Pin Cell Pin Loading Cell design rule Wire Load Table Gate .

For this reason only a subset of Verilog is synthesizable.Synthesis Process § Not all Verilog commands synthesize easily. § However in hardware only variables stored in flip-flops are easy to initialize. These presentation will concentrate on that subset. . § For example initial initializing variables is easy to do in a program where all variables are stored.

. § Technology libraries are created by the silicon vendor. They can be understood by the tools. § A library may contain: § The timing and electrical characteristics of the cells § Net delay and net parasitic information § Definition of capacitance.Technology Library § A Technology Library contains a set of primitive cells which can be used by synthesis tools to build a circuit. § Most libraries are compiled before delivery. Not by the synthesis tools. time and resistance units. but are unreadable to you.

Verilog Procedure § initial is not synthesizable and is used for test benches. § always without @ condition. or at least not of type wire. In a structural code the LHS variable should be of type wire . is normally only used in test benches § Variables on the left-hand side should be of type reg in a procedural code .

If all left-hand values can be calculated from a single procedure entry.Only Put Latches If Necessary § Many procedures do not need to store values.it will infer a latch. 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. Example 1 Example 2 . since it has to remember the values when enable =0 .

Set all outputs to some value at the start of the procedure. . else z=4. always @(. end Method 1: . every path must evaluate all outputs. if (a) x=2.Only Put Latches If Necessary § Every time one executes a procedure all of the variables defined anywhere in the procedure must be calculated. Else synthesis will insert latches to hold the old value of those unevaluated outputs. y=0. Later on different values can overwrite those values. § If the procedure has several paths. begin x=0. elseif (b) y=3. z=0. .

y=0. z=4.Method 2 Be sure every branch of every if and case generate every output. z=0. always @(. . . end elseif (b) begin x=0. y=3. y=0. z=0. end else begin x=0. begin if (a) begin x=2. end end end .

Latches and Combinational always @(C or D) :. It may just result in combinational logic. and/or combinational logic.Procedural synthesis Logic Inference Deciding what logic to synthesize from code is called inference. latches. always @ Can infer: flip-flops.This may generate a latch. always @(posedge Clk) This is the statement that tells the logic compiler to generate flip flops. .

Latch Inference Inserting Latches With or Without Your Asking Latches form if //Latch Inference form if reg Q. //Initialize if (Ck) Z <= D. end . always @(Clk or D) begin if (Clk) Q <= D. always @(Ck or D) begin Z<=1’b0. end //No Latch Inference from if reg Z.

any unused code is discarded. . Some of the steps are: § Expansion . § Constant folding .loop statements are unrolled to a series of individual statements.subprograms are in-lie expanded.RTL level Optimization § Code related processing is first performed when a model is synthesized. A + 3 + 2 becomes A + 5 § Loop unrolling . § Dead code removal .eg.

E. ‘+’ operator can be carry look-forward (fastest). . § Different implementations of arithmetic operators have different area and timing characteristics.RTL level Optimization § Bit minimization . operator bit width. § Resource sharing. VHDL state encoding.for example. carry look-ahead or ripple carry (smallest). § Common sub-expression sharing. or assignments of different widths in Verilog. § Operator reordering. etc. etc.g.

If (S == 1’b0) begin L <= A + B. L=A+B M=L+L FORK N=A-C JOIN MERGE CDFG level optimization techniques will be used.C. end. else N <= A + C. end if. N <= A . N=A+C SELECT .CDFG format § The control data flow graph is often used by synthesis tools for highest internal representation. M <= L + L.

Logic level optimization § All registered elements are fixed. only combinational logic is optimized. § The types of logic optimization include: § minimization § equation flattening § equation factorization § The algorithms used work on multiple equations and multiple outputs. § Optimization at this level involves restructuring of equations according to the rules of Boolean law. .

Logic level optimization L = A.B N=C+D Y1=M.B+C+D flatten equations Y1=A.D Y2=A.B+C+D factorize factorize M=A.N Y2=M+N .B.B L=M.C Y1=L+A.B.B.D Y2=M+C+D M=A.C+A.B.C Y1=L+M.D Y2=A.

§ 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.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. .

.Mapped circuit before gate level optimization.

After gate level optimization 3 cells 14 transistors 3.5 equivalent gates .

Verilog Coding Guidelines .

Guideline #4: When modeling both sequential and combinational logic within the same always block. Guideline #3: When modeling combinational logic with an always block. Guideline #2: When modeling latches. use nonblocking assignments. use blocking assignments. use nonblocking assignments .Verilog Coding Guidelines Guideline #1: When modeling sequential logic. use nonblocking assignments.

Verilog Coding Guidelines Guideline #5: Do not mix blocking and nonblocking assignments in the same 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. . Guideline #6: Do not make assignments to the same variable from more than one always block.

Verilog "stratified event queue" .

Electrical Properties .

Can be 0. or false condition 1 : Logical 1. or false condition Z : High impedance state X : Unknown logic condition.Signal Types § § § § 0 : Logical 0. 1 or Z .

Signal Types(cont) 0 0 X Z 0 1 1 Z X Z Z 1 X X .

Signals (cont) 0 X 1 X 1 X 0 X 0 S0 S1 SEL X S0 1 X X 0 X 1 S1 X X 0 1 SEL 0 1 X X Z S0 S1 0 1 Z .

Signal Strength (cont) Logic 0 strength Logic 1 strength 7 6 5 4 3 Su0 St 0 Pu0 La0 We0 2 1 0 Me0 Sm 0 HiZ 0 0 HiZ 1 1 Sm1 2 3 4 5 6 7 Me1 We 1 La1 Pu1 St 1 Su1 Su1(7) Su1(7) La0(4) .

weak1) (out. pull1.Verilog Syntax for Strength Only for gate instantiation // and gate with weak pull up and (supply0. in1. . in2). strong0. pull0. supply0. highz0. weak0. strong1. weak1. Note: Valid strength keywords are supply1. highz1.

rtranif0.rtrainif1 reduce the output strength as follow: Input Strength Supply drive Strong drive Pull drive Weak drive High impedance Output Strength Pull drive Pull drive Weak drive Medium capacitor High impedance in0 in1 sel out . rnmos. rpmos.Support for transmission gate rcmos. rtran.

(A2 => Z) = A2_to_Z. (A1 => Z) = A1_to_Z. A2). specify specparam A1_to_Z=12. A2.Timing Delay in ASIC library Pin-to-Pin delay module AND2 (Z. endspecify endmodule A1 to Z delay A1 Z A2 A2 to Z delay . A1. output Z. A2_to_Z=14. input A1. A2). A1. and (Z.

Timing Delay in Gate Back-annotation Verilog Delay Calculation SDF Physical Information .

Timing Delay Calculation RC network Delay Load Cell Library Output skew Load Input skew Table Look-up Skew SDF .

mod1. .sdf”). it make no sense to put it after time 0 .log”).SDF Back-Annotation Using system task $sdf_annotate().sdf”. “mod1_sdf. However. Example § § $sdf_annotate(“full_chip. $sdf_annotate(“mod1. Note: $sdf_annotate() can be placed anywhere in the HDL code.Timing Delay .

Conditional Compilation & Naming Convention .Macros.

Keyword cannot be used as macro name. (e.v +define+regressionSuit=“4” ) . These macro has the highest priority.g. One line comment (//) will be excluded in the text substituted. Macro can be re-define. verilog design. (It does not make sense). There is not scope restriction. The last definition read is used. Macro can also be defined in the command line.Macro § § § § § § Macro names and the names used in the design are different Macro definition is global.

‘define WORD 8 //word size ‘define CLOCKMUX ssmux8 module register(…) reg [‘WORD-1 : 0] cpu_reg..Macro Cont. … endmodule . … ‘CLOCKMUX hand_clockMux (…).

g. profiling and encryption) from the simulation does not retain the full Verilog input.Conditional Compilation § ‘ifdef. always @ (b or c) begin ‘ifdef BEHAVIOURAL a = b + c. input [7:0] b. ‘endif end endmodule . b. § Verilog simulator does not keep record of the ignored text. output [8:0] a. b. c). module adder(a. ‘else and ‘endif can be nested § Syntax for the ignored Verilog texts are not checked. 7. c). 7)i0 (a. c. reg [8:0] a. ‘else gateAdder #(8. Thus any output (e.

Do not use port names that are used in the ASIC library. . Use short instance name. Use the same port name and wire name when the signal goes through different hierarchy. Unique pre-fix for modules belong to the same circuit partition. Use very short name in ASIC library.Good Naming Convention § § § § § § Use all upper-case for constants specified by ‘define macro and code inclusion control name defined by ‘ifdef and ‘define.

Verilog for Logic Simulation .

Introduction Input command line Simulation Waveform Testbench Log Design Key Log .

dat”). initial begin fileID = $fopen(“capture. $write() and $monitor() have a counterpart to write to a specific file.File Output $display(). end . beside the log file. $fdisplay(fileID. integer fileID. if (fileID == 0) $finish. $pli_currentDateTime() ). “Start Simulation %s”.

§ § § § § § timing control input stimulus device under test reference model diagnostic logging assertion checking .Test bench § The following things are essentially required to be provisioned a test bench.

end initial begin clock = 1’b0. inputC=1’b0. forever #10 clock = !clock. end . inputB} = 2’b00. #12 inputB = 1’b1.Test bench – timing control initial begin #10 inputA = 1’b1. inputD=1’b1. #9 {inputA.

. A VCD waveform viewer can show the result in the form of waveform display.<module or variable>>*). $dumpvars(<level> <. Specify VCD filename $dumpfile(“<fileName>”). / $dumpoff. Specify dump variable Start/Stop dumping $dumpon.Waveform Probing using VCD Verilog supports Value Change Dump (VCD) output.

<level> only affect module. and in all module instances below top. § Dump all variables in the module top. § Dump all variables in the module top. § Dump all variables in top. not variable. $dumpfile(0.mod1).mod1). $dumpfile(0.mod2.mod1 in the design hierarchy.net1).mod1. Net top.mod1.mod1. $dumpfile(1. top. top. § Dump all variables in the design.mod2.mod1. top.Waveform Probing using VCD $dumpfile.mod1 and all modules instantiate below top. . top.net1 is also dumped.

$reset : finish the simulation : stop simulation and enter interactive mode : continue simulation : step : 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 .Interactive Debugging Simulation control (depends on simulator) § § § § § § $finish() $stop() .

// reset is 1 #10 a = 1.Simulation Tips 1 Zero-delay loop A common mistake in big design. Usually indicates a logic error. reg a. end end endmodule . input reset. always begin if ( !reset ) begin // what happen when #10 a = 0. module top(reset).

res. end always @(posedge clk or posedge reset) if(reset) {a. #10 reset = 1. end initial begin reset = 0.b. reset. endmodule .c. end always @(b) c = c + 1’b1. reg [3:0] a.d}=13’b0. b. always @(a or d) begin b = b + 1’b1. #10 reset = 0.A more complicated zero delay loop module top. else d = !d. if (d) res = b + d. #1000 $finish. c. d. always @(c) a = a + 1’b1. forever #10 clk = !clk. reg clk. initial begin clk = 0.

Simulation Tips 2 Accelerated vs. … Accelerated continuous assignment Non-accelerated continuous assignment . assign #var h = i. Non-accelerated Construct … reg var. assign #(delay + 1) c = d. assign j = k + m. assign e = f & g. parameter delay=10 assign #delay a = b.

Simulation Tips 3 Timing violation in register when crossing timing domains unSyncD syncD clk1 clk2 unSyncD clk2 syncD .

The “X”state get propagated to the rest of the circuit. unSyncD sel clk1 clk2 . and the simulation becomes meaningless.The timing violation can “kill” the simulation.

Introduction to PLI .

§ 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. 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.Where PLI is Used § The Programming Language Interface (PLI) provides a set of interface routines to read internal data representation.

Simulation Flow Using PLI routines .

§ Verilog Procedural Interface (vpi_) routines make up the thirdgeneration PLI. These routines can be used to access and modify a wide variety of objects in the Verilog HDL description. . These routines are provide object-oriented access directly into a Verilog HDL structural description.Generations of Verilog PLI § Task/Function (tf_) routines make up the first generation PLI. and writing data to output devices. These routines are a superset of the functionality of acc_ and tf_ routines. callback mechanism. These routines are primarily used for operations involving userdefined task/function arguments. § Access (acc_) routines make up the second-generation PLI. utility functions.

. logic connectivity. connectivity. § Application software like translators and delay calculators can be written with PLI. Waveform viewers can use this file to generate waveforms.Uses Of PLI § PLI can be used to define additional system tasks and functions. stimulus tasks. fanout. Typical examples are monitoring tasks. debugging tasks. and complex operations that cannot be implemented with standard Verilog constructs. § PLI can be used to write special-purpose or customized output display routines. and number of logic elements of a certain type. § PLI can be used to extract design information such as hierarchy. source level browsers. and hierarchy information.

) § Routines that provide stimulus to the simulation can be written with PLI.Uses Of PLI (Contd. § General Verilog-based application software can be written with PLI routines. .. The stimulus could be automatically generated or translated from some other form of stimulus. This software will work with all Verilog simulators because of the uniform access provided by the PLI interface.

h" /*include the file provided in release dir */ int hello_verilog() { io_printf("Hello Verilog World\n"). . the C routine hello_verilog must be executed.Linking and Invocation of PLI Tasks example of a simple system task $hello_verilog #include "veriuser. This process is called linking the PLI routines into the Verilog simulator. The simulator needs to be aware that a new system task called $hello_verilog exists and is linked to the C routine hello_verilog. } § Whenever the task $hello_verilog is invoked in the Verilog code.

For example. a new binary executable hverilog is produced. A Verilog module hello_top. § Once the user-defined task has been linked into the Verilog simulator. instead of the usual simulator binary executable. which calls the task $hello_verilog. is defined in file hello.§ At the end of the linking step. //Invoke the user-defined task $hello_verilog endmodule Output of the simulation is as follows: Hello Verilog World . run hverilog instead of your usual simulator executable file. initial $hello_verilog. it can be invoked like any Verilog system task by the keyword $hello_verilog.v as shown below: module hello_top. To simulate. a special binary executable containing the new $hello_verilog system task is created.

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.

Palnitkar. .References § § § § http://www.asic-world.sunburst-design. IEEE Std 1364-1995. IEEE Standard Hardware Description Language Based on the Verilog Hardware Description Language.com.com/verilog/. IEEE Computer Society. Samir. Verilog HDL: A Guide to Design and Synthesis www.

ThanQ .

Sign up to vote on this title
UsefulNot useful