Verilog Programming Styles
Verilog Programming Styles
4
Verilog Program Structure
module <module_name> (<port_list>);
Continuous assignments use the
Port Declaration keyword assign whereas
procedural assignments have
Data type Declaration the form
<reg variable> = <expression>
Circuit Functionality where the <reg variable> must be
a register or memory.
Procedural assignment may only
Timing Specification
appear in initial and always
endmodule constructs.
Ways to Specify the functionality
1. Gate Level
2. Structural
3. Data-flow
4. Behavioral 5
Data Flow Modeling
• Next level up: Dataflow modeling
• Continuous assignment
• The assign keyword is used
//same as
wire out;
assign #10 out = in1 & in2;
// A = 4, B = 3 // Z = 4'b1xxz, M = 4'b1xxz
// X = 4'b1010, Y = 4'b1101 // N = 4'b1xxx
A == B X == Z
X != Y Z === M
Z === N
M !== N
Bitwise Operators
// X = 4'b1010
// Y = 4'b1101
// Z = 4'b10x1
&X
|X
^X
Shift Operators
// X = 4'b1100
Y = X >> 1;
Y = X << 1;
Y = X << 2;
integer a, b, c;
a = 0;
b = -10;
c = a + (b >>> 3);
Concatenation Operator
• Unsized operands not allowed
// A = 1'b1, B = 2'b00,
// C = 2'b10, D = 3'b110
Y = {B , C}
Y = {A , B , C , D , 3'b001}
Y = {A , B[0], C[1]}
Replication Operator
reg A;
reg [1:0] B, C;
reg [2:0] D;
A = 1'b1;
B = 2'b00;
C = 2'b10;
D = 3'b110;
Y = { 4{A} }
Y = { 4{A} , 2{B} }
Y = { 4{A} , 2{B} , C }
20
Conditional Operator
assign out = (A == 3) ?
( control ? x : y ):
( control ? m : n) ;
Operators Precedence
Data Flow Modeling - Example
4 x 1 Multiplexer
4 X 1 using Conditional operator
– Dataflow modeling
• Boolean function assigned to a net
29
29
Structured Procedures
30
Structured Procedures: initial statement
• Starts at time 0
• Executes only once during a simulation
• Multiple initial blocks, execute in parallel
– All start at time 0
– Each finishes independently
• Syntax:
initial
begin
// behavioral statements
end
31
Example
module stimulus;
reg x, y, a, b, m;
initial
initial #50 $finish;
m= 1’b0; endmodule
initial
begin
#5 a=1’b1;
#25 b=1’b0;
end
initial
begin
#10 x=1’b0;
#25 y=1’b1;
end
32
Initializing variables
• Ordinary style, using initial block
reg clock;
initial clock = 0;
module adder (
output reg [7:0] sum = 0,
output reg co = 0,
input [7:0] a, b,
input ci);
...
endmodule
DSD 33
33
Structured Procedures: always statement
• Start at time 0
• Execute the statements in a looping fashion
34
Procedural Assignments
35
Cont…
• Syntax
<lvalue> = <expression>
– <lvalue> can be
• reg, integer, real, time
• A bit-select of the above (e.g., addr[0])
• A part-select of the above (e.g., addr[31:16])
• A concatenation of any of the above
– <expression> is the same as introduced in dataflow modeling
36
Blocking Procedural Assignments
• The two types of procedural assignments
– Blocking assignments
– Non-blocking assignments
• Blocking assignments
– are executed in order (sequentially)
– Example:
reg x, y, z;
reg [15:0] reg_a, reg_b;
integer count; All executed at time 0
initial begin
x=0; y=1; z=1;
count=0;
reg_a= 16’b0; reg_b = reg_a;
#15 reg_a[2] = 1’b1; executed at time 15
#10 reg_b[15:13] = {x, y, z};
count = count + 1;
end All executed at time 2537
Non-Blocking Procedural Assignments
• Non-blocking assignments
– Processing of the next statements is not blocked for this one
– Transactions created sequentially (in order), but executed after all
blocking assignments in the corresponding simulation cycle
– Syntax:
<lvalue> <= <expression>
– Example:
reg x, y, z;
reg [15:0] reg_a, reg_b;
All executed at time 0
integer count;
initial begin
x=0; y=1; z=1;
count=0;
reg_a= 16’b0; reg_b = reg_a;
reg_a[2] <= #15 1’b1; Scheduled to run at time 15
reg_b[15:13] <= #10 {x, y, z};
count <= count + 1; Scheduled to run at time 10
end
Non-Blocking Assignments (cont’d)
• Application of non-blocking assignments
– Used to model concurrent data transfers
– Example: Write behavioral statements to swap values of two
variables
39
Cont..
• When the final result of simulating two (or more)
concurrent processes depends on their order of execution
• Example:
always @(posedge clock)
b = a;
always @(posedge clock)
a = b;
• Solution: always @(posedge clock)
always @(posedge clock) begin
b <= a; temp_b = b;
always @(posedge clock) temp_a = a;
b = temp_a;
a <= b;
a = temp_b;
end
40
Timing Controls in
Behavioral Modeling
Timing Control Methods
• No timing controls No advance in simulation time
42
Delay-based Timing Controls
• Delay Duration between encountering and
executing a statement
• Delay symbol: #
43
Regular Delay Control
• Symbol: non-zero delay before a procedural assignment
44
Intra-assignment Delay Control
• Symbol: non-zero delay to the right of the
assignment operator
• Operation sequence:
1. Compute the RHS expression at current time.
2. Defer the assignment of the above computed
value to the LHS by the specified delay.
45
Intra-assignment Delay Control
Zero-Delay Control
• Symbol: #0
47
Zero-Delay Control
48
Event-based Timing Control
• Event
– Change in the value of a register or net
– Used to trigger execution of a statement or block
(reactive behavior/reactivity)
49
Regular Event Control
• Symbol: @(<event>)
• Events to specify:
– posedge sig
• Change of sig from any value to 1 or from 0 to any value
– negedge sig
• Change of sig from any value to 0 or from 1 to any value
– sig
• Any change in sig value
50
Named Event Control
• You can declare (name) an event, and then trigger
and recognize it.
• Keyword: event
event calc_finished;
52
Event OR control
• Used when need to trigger a block upon occurrence
of any of a set of events.
• The list of the events: sensitivity list
• Keyword: or
• Simpler syntax
– always @( reset, clock, d)
53
Event OR control
• Simpler syntax
– @* and @(*)
• OR
54
Level-sensitive Timing Control
• Level-sensitive vs. event-based
– event-based: wait for triggering of an event
(change in signal value)
– level-sensitive: wait for a certain condition (on
values/levels of signals)
• Keyword: wait()
always
wait(count_enable) #20 count=count+1;
55
Conditional Statements
Multiway Branching
Behavioral Modeling Statements:
Conditional Statements
• Just the same as if-else in C
• Syntax:
if (<expression>) true_statement;
if (<expression>) true_statement;
else false_statement;
if (<expression>) true_statement1;
else if (<expression>) true_statement2;
else if (<expression>) true_statement3;
else default_statement;
• True is 1 or non-zero
• False is 0 or ambiguous (x or z)
• More than one statement: begin end
Behavioural Modelling – (if - else statement)
module FA (A, B, Cin, COUT, S );
input A,B,Cin;
output COUT,S;
reg S,COUT;
always@(A or B or C)
begin
if(A==0 && B==0 && C==0)
begin
S=0; COUT=0;
end
• Syntax:
case (<expression>)
alternative1: statement1;
alternative2: statement2;
...
default: default_statement; // optional
endcase
• Notes:
– <expression> is compared to the alternatives in the order
specified.
– Default statement is optional
2010 DSD 59
59
Behavioural Modelling – Case statement
module mux4bit( i, s, out);
input [3:0] i;
input [1:0] s;
Output reg out;
always @(i or s)
begin
case (s)
2’b00:out=i[0];
2’b01:out=i[1];
2’b10:out=i[2];
2’b11:out=i[3];
default:out=0;
endcase
end
endmodule
Behavioural Modelling – (case statement)
module FA (input wire A, B, Cin, output reg S,
output reg Cout);
always @(A or B or Cin)
begin
case (A | B | Cin)
3'b000: begin S = 0; Cout = 0; end
3'b001: begin S = 1; Cout = 0; end
3'b010: begin S = 1; Cout = 0; end
3'b011: begin S = 0; Cout = 1; end
3'b100: begin S = 1; Cout = 0; end
3'b101: begin S = 0; Cout = 1; end
3'b110: begin S = 0; Cout = 1; end
3'b111: begin S = 1; Cout = 1; end
endcase
end
Behavioral Modeling Statements: Loops
• Loops in Verilog
– while, for, repeat, forever
• The while loop syntax:
while (<expression>)
statement;
62
Loops (cont’d)
• The for loop
– Similar to C
– Syntax:
for( init_expr; cond_expr; change_expr)
statement;
63
Loops (cont’d)
• The repeat loop
– Syntax:
repeat( number_of_iterations )
statement;
– The number_of_iterations expression is evaluated only
when the loop is first encountered
integer count;
initial
begin
count = 0;
repeat(128) begin
$display("Count = %d", count);
count = count + 1;
end
end
64
Loops (cont’d)
• The forever loop
– Syntax:
forever
statement;
– Equivalent to while(1)
65
Generate Statement
• Allows Verilog code to be generated
dynamically at elaboration time before the
simulation begin.
• Convenient when the same operation or
module instance is repeated for a multiple bit
of vector or when certain Verilog code is
conditionally is conditionally included based on
parameter definitions
66
Example 1: Bitwise XOR for two N-bit buses
module bitwise_xor (out, i0, i1);
parameter N = 32; // 32-bit bus size
output [N-1 : 0] out;
Input [N-1: 0] i0, i1;
// Declared a temporary loop variable. This variable is used only in the evaluation of
generate blocks. It does not exist during simulation of a Verilog design
genvar j;
generate
for (j=0; j<N, j=j+1)
begin: xor_loop
xor g1 (out [j], i0[j], i1[j]); always @ (i0[j] or i1[j] )
OR
out [j] = i0[j] ^ i1[j];
end
endgenerate
endmodule
67
Example 2: 32-bit binary adder
module prac2_3a #(parameter N = 32)(input [N-1:0] a, b,input c_in,output [N-1:0]
c_out, s);
adder1 h1 (a[0],b[0], c_in, c_out[0], s[0]);
generate
genvar i;
for(i = 1; i< 32; i = i+1)
begin: prac2_3a
adder1 h1 (a[i],b[i], c_out[i-1],c_out[i], s[i]);
end
endgenerate
endmodule
module adder1 ( input a, input b, input c_in, output c_out, output sum);
assign {c_out, sum} = a + b + c_in;
endmodule
68
Example 3: N-bit look ahead adder
module prac2_lookahead #(parameter N =32)(input [N-1:0] a,input [N-1:0] b, output
[N:0] result);
wire [N:0] C;
wire [N-1:0] G, P, SUM;
genvar i;
generate
for (i=0; i<N; i=i+1)
begin: x1
adder1 h1(.a(a[i]),.b(b[i]),.c_in(C[i]),.sum(SUM[i]),.c_out());
end
endgenerate
genvar j;
generate
69
Cont…
for (j=0; j<N; j=j+1)
begin: x2
assign G[j] = a[j] & b[j]; //Generate (G) Terms: Gj=Aj*Bj
assign P[j] = a[j] ^ b[j]; //Propagate Terms: Pj=Aj+Bj
assign C[j+1] = G[j] | (P[j] & C[j]); //Carry Terms
end
endgenerate
endmodule
module adder1 ( input a, input b, input c_in, output c_out, output sum);
assign {c_out, sum} = a + b + c_in; endmodule
2010 DSD 70
70
Blocks
• Some more constructs on Behavioral
Modeling
– Parallel blocks
– Nested blocks
2011 DSD 71
71
Sequential blocks
• Used to group multiple statements
• Sequential blocks
– Keywords: begin end
– Statements are processed in order.
– A statement is executed only after its preceding
one completes.
• Exceptions: non-blocking assignments and
intra-assignment delays
– A delay or event is relative to the simulation time
when the previous statement completed
execution
2011 DSD 72
72
Parallel Blocks
• Parallel Blocks
– Keywords: fork, join
– Statements in the blocks are executed concurrently
– Timing controls specify the order of execution of the
statements
– All delays are relative to the time the block was entered
• The written order of statements is not important
• The join is done when all the parallel statements are finished
2011 DSD 73
73
Sequential vs. Parallel Blocks
initial
begin
x=1’b0;
#5 y=1’b1;
#10 z={x,y};
#20 w={y,x};
end
initial
fork
x=1’b0;
#5 y=1’b1;
#10 z={x,y};
#20 w={y,x};
join
2011 DSD 74
74
Parallel Blocks and Race
75
Task and Function
Introduction
• Procedures/Subroutines/Functions in SW
programming languages
– The same functionality, in different places
• Verilog equivalence:
– Tasks and Functions
– Used in behavioral modeling
– Part of design hierarchy Hierarchical name
2010 DSD 77
77
Functions
• Keyword: function, endfunction
• Can be used if the procedure
– does not have any timing control constructs
– returns exactly one single value
– has at least one input argument
2010 DSD 78
78
Function Declaration Syntax
2010 DSD 79
79
Function Invocation Syntax
<func_name> ( <argument(s)> );
• Example:
function my_not;
input in;
my_not= ~in;
endfunction
reg ni;
initial
ni = my_not(i);
2010 DSD 80
80
Function Semantics
– much like function in Pascal
– An internal implicit reg is declared inside the
function with the same name
– The return value is specified by setting that
implicit reg
– <range_or_type> defines width and type of
the implicit reg
•<type> can be integer or real
•default bit width is 1
2010 DSD 81
81
Examples: Parity Calculation
//Define a module that contains the function calc_parity
module parity;
reg [31:0] addr;
reg parity;
// compute new parity whenever address value changes
always@(addr)
begin
parity = calc_parity(addr) // first invocation of calc_parity function
$display (“Parity calculated = %b”, calc_parity(addr)); // second invocation
end
2010 DSD 83
83
Task Declaration Syntax
task <task_name>;
<I/O declarations> // optional
<variable and event declarations>
begin // if more than one statement needed
<statement(s)>
end // if begin used!
endtask
2010 DSD 84
84
Task Invocation Syntax
<task_name>;
<task_name> (<arguments>);
2010 DSD 85
85
I/O declaration in modules vs. tasks
– Both use keywords: input, output, inout
– In modules, represent ports
•connect to external signals
– In tasks, represent arguments
•pass values to and from the task
2010 DSD 86
86
Task Examples : Use of input and output arguments
//Define a module called operation that contains the task bitwise_oper
module operation
parameter delay = 10;
reg [15:0] A, B;
reg [15:0] AB_AND, AB_OR, AB_XOR;
always@(A or B)
begin
bitwise_oper (AB_AND, AB_OR, AB_XOR); // invoke the task
end
2010 DSD 88
88
Differences between...
• Functions • Tasks
– Can enable (call) just – Can enable other tasks
another function (not task) and functions
– Execute in 0 simulation time – May execute in non-zero
– No timing control simulation time
statements allowed – May contain any timing
– At least one input control statements
– May have arbitrary
input, output, or
– Return only a single value inout
– Do not return any value
2010 DSD 89
89
Nothing ever becomes real till it is
experienced
John Keats
Gate Level Modeling
• Usages of gate-level modeling t1
Small designs
Netlist of gates, Logic Synthesis
module fa1bit (a, b, c, s,
cout);
input a,b,c;
output s, cout; t2
wire t1,t2,t3;
xor (t1, a, b);
xor (s, t1,cin);
and (t2, a, b);
and (t3, t1, cin);
or (cout, t2, t3);
t3
endmodule
91
Gate Level Modeling
endmodule
92
Gate Delays in Verilog
❖Rise delay
❖Fall delay
❖Turn-off delay
93
Specifying Gate Delay
// Delay of delay_time for all transitions
and #(delay_time) a1(out, i1, i2);
Examples:
94
Min/Typ/Max Delay values
❖Can be separately specified for each delay type
// One delay
// if +mindelays, delay= 4
// if +typdelays, delay= 5
// if +maxdelays, delay= 6
and #(4:5:6) a1(out, i1, i2);
// Two delays
// if +mindelays, rise= 3, fall= 5, turn-off = min(3,5)
// if +typdelays, rise= 4, fall= 6, turn-off = min(4,6)
// if +maxdelays, rise= 5, fall= 7, turn-off = min(5,7)
and #(3:4:5, 5:6:7) a2(out, i1, i2);
// Three delays
// if +mindelays, rise= 2 fall= 3 turn-off = 4
// if +typdelays, rise= 3 fall= 4 turn-off = 5
// if +maxdelays, rise= 4 fall= 5 turn-off = 6
bufif0 #(2:3:4, 3:4:5, 4:5:6) a3(out, in, ctrl);
95
Switch level Modeling
module my_nor (a, b, out);
input a,b;
output out;
wire c;
supply1 power1;
supply0 gnd;
end module
96