Uploaded by martin87

Advanced Verilog Workshop

advertisement
CUSTOMER EDUCATION SERVICES
Advanced Verilog
Workshop
Student and Lab Guide
50-I-022-XSLG-010
Version 2.6
Developed and Presented By:
Willamette HDL, Inc.
7345 SW 165th Pl
Beaverton, OR 97007
(503) 590-8499
www.whdl.com
Synopsys Customer Education Services
700 East Middlefield Road
Mountain View, California 94043
Workshop Registration: 1-800-793-3448
www.synopsys.com
Copyright Notice and Proprietary Information
Copyright  2005 Synopsys, Inc. All rights reserved. This software and documentation contain confidential and proprietary
information that is the property of Synopsys, Inc. The software and documentation are furnished under a license agreement and
may be used or copied only in accordance with the terms of the license agreement. No part of the software and documentation
may be reproduced, transmitted, or translated, in any form or by any means, electronic, mechanical, manual, optical, or otherwise,
without prior written permission of Synopsys, Inc., or as expressly provided by the license agreement.
Right to Copy Documentation
The contract agreement between Synopsys, Inc. and Willamette HDL, Inc. gives copyright determination to Willamette HDL, Inc.
for this course material. Synopsys licensees are permitted to make copies of this documentation for internal use only. Each copy
shall include all copyrights, trademarks, service marks, and proprietary rights notices, if any. Licensee must assign sequential
numbers to all copies. These copies shall contain the following legend on the cover page:
“This document is duplicated with the permission of Synopsys Inc. and Willamette HDL Inc., for the exclusive use of
__________________________________________ and its employees. This is copy number __________.”
Destination Control Statement
All technical data contained in this publication is subject to the export control laws of the United States of America. Disclosure to
nationals of other countries contrary to United States law is prohibited. It is the reader’s responsibility to determine the applicable
regulations and to comply with them.
Disclaimer
SYNOPSYS, INC., AND ITS LICENSORS MAKE NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO
THIS MATERIAL, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
Registered Trademarks (®)
Synopsys, AMPS, Arcadia, C Level Design, C2HDL, C2V, C2VHDL, Cadabra, Calaveras Algorithm, CATS, CSim, Design
Compiler, DesignPower, DesignWare, EPIC, Formality, HSPICE, Hypermodel, iN-Phase, in-Sync, Leda, MAST, Meta, MetaSoftware, ModelTools, NanoSim, OpenVera, PathMill, Photolynx, Physical Compiler, PowerMill, PrimeTime, RailMill, RapidScript,
Saber, SiVL, SNUG, SolvNet, Superlog, System Compiler, Testify, TetraMAX, TimeMill, TMA, VCS, Vera, and Virtual Stepper are
registered trademarks of Synopsys, Inc.
Trademarks (™)
abraCAD, abraMAP, Active Parasitics, AFGen, Apollo, Apollo II, Apollo-DPII, Apollo-GA, ApolloGAII, Astro, Astro-Rail, Astro-Xtalk,
Aurora, AvanTestchip, AvanWaves, BCView, Behavioral Compiler, BOA, BRT, Cedar, ChipPlanner, Circuit Analysis, Columbia,
Columbia-CE, Comet 3D, Cosmos, CosmosEnterprise, CosmosLE, CosmosScope, CosmosSE, Cyclelink, Davinci, DC Expert, DC
Expert Plus, DC Professional, DC Ultra, DC Ultra Plus, Design Advisor, Design Analyzer, Design Vision, DesignerHDL,
DesignTime, DFM-Workbench, DFT Compiler, Direct RTL, Direct Silicon Access, Discovery, DW8051, DWPCI,
Dynamic-Macromodeling, Dynamic Model Switcher, ECL Compiler, ECO Compiler, EDAnavigator, Encore, Encore PQ, Evaccess,
ExpressModel, Floorplan Manager, Formal Model Checker, FoundryModel, FPGA Compiler II, FPGA Express, Frame Compiler,
Galaxy, Gatran, HDL Advisor, HDL Compiler, Hercules, Hercules-Explorer, Hercules-II, Hierarchical Optimization Technology, High
Performance Option, HotPlace, HSPICE-Link, iN-Tandem, Integrator, Interactive Waveform Viewer, i-Virtual Stepper, Jupiter,
Jupiter-DP, JupiterXT, JupiterXT-ASIC, JVXtreme, Liberty, Libra-Passport, Library Compiler, Libra-Visa, Magellan, Mars,
Mars-Rail, Mars-Xtalk, Medici, Metacapture, Metacircuit, Metamanager, Metamixsim, Milkyway, ModelSource, Module Compiler,
MS-3200, MS-3400, Nova Product Family, Nova-ExploreRTL, Nova-Trans, Nova-VeriLint, Nova-VHDLlint, Optimum Silicon,
Orion_ec, Parasitic View, Passport, Planet, Planet-PL, Planet-RTL, Polaris, Polaris-CBS, Polaris-MT, Power Compiler,
PowerCODE, PowerGate, ProFPGA, ProGen, Prospector, Protocol Compiler, PSMGen, Raphael, Raphael-NES, RoadRunner,
RTL Analyzer, Saturn, ScanBand, Schematic Compiler, Scirocco, Scirocco-i, Shadow Debugger, Silicon Blueprint, Silicon Early
Access, SinglePass-SoC, Smart Extraction, SmartLicense, SmartModel Library, Softwire, Source-Level Design, Star, Star-DC,
Star-MS, Star-MTB, Star-Power, Star-Rail, Star-RC, Star-RCXT, Star-Sim, Star-SimXT, Star-Time, Star-XP, SWIFT, Taurus,
TimeSlice, TimeTracker, Timing Annotator, TopoPlace, TopoRoute, Trace-On-Demand, True-Hspice, TSUPREM-4, TymeWare,
VCS Express, VCSi, Venus, Verification Portal, VFormal, VHDL Compiler, VHDL System Simulator, VirSim, and VMC are
trademarks of Synopsys, Inc.
Service Marks (SM)
MAP-in, SVP Café, and TAP-in are service marks of Synopsys, Inc.
SystemC is a trademark of the Open SystemC Initiative and is used under license.
ARM and AMBA are registered trademarks of ARM Limited.
All other product or company names may be trademarks of their respective owners.
Printed in the U.S.A.
Document Order Number: 50-I-022-XSLG-010
Advanced Verilog Student and Lab Guide
Synopsys Customer Education Services
Advanced Verilog v2.6
for
Advanced Verilog
© 2004 Willamette HDL, Inc.
1
Notes:
© 2004 Willamette HDL, Inc. &
Slide 1
This page was intentionally left blank.
Advanced Verilog
© 2004 Willamette HDL, Inc.
2
Notes:
© 2004 Willamette HDL, Inc. &
Slide 2
Verilog Review & General topics
Verilog information
8
Modeling methodology
9
Verilog basics review
Procedural blocks
Timing controls
Time and event queues
Blocking Proc. assignments
Non-blocking Proc. assignments
Rules of Thumb
Course
Outline
21
22
24
25
29
36
48
Recent enhancements
Verilog 2001
Multi-dimension arrays
Indexed part-select
Parameters
ANSI-style port declarations
File IO
55
Verilog is a registered trademark of Cadence Design Systems, Inc.
Synopsys and VCS are trademarks of Synopsys, Inc.
Any other trademarks mentioned in this document are fully recognized as the property of their respective owners
The contents of this training material and the related electronic files are copyright protected. Duplication, publication or other use is strictly prohibited
Advanced Verilog
© 2004 Willamette HDL, Inc.
3
Notes:
© 2004 Willamette HDL, Inc. &
Slide 3
SystemVerilog Enhancements
Variables & datatypes
Casting
Arrays
Structures
Ports
Tasks
functions
69
74
77
78
89
95
98
100
Outline
(cont’d)
Behavioral Modeling
Behavioral Verilog
Thinking Behaviorally
Behavioral SRAM
Scoping
Named events
Behavioral State machines
Bus Functional Models
Advanced Verilog
104
111
112
115
116
122
136
© 2004 Willamette HDL, Inc.
4
Notes:
© 2004 Willamette HDL, Inc. &
Slide 4
Validation / Verification
Assertion Based Verification
SystemVerilog Assertions
Concurrent assertions
Sequences
Repetition
Sequential expressions
Property blocks
Verification directives
Clocks
Assertion Methodology Guidelines
SVA Checker Lib
142
154
158
166
170
174
184
190
193
197
203
Verilog for Test
Code Profiling
Instantiation
Libraries
Self checking tests
Timeout Mechanisms
Vector Manipulation
Timing Checks
Test Exercise
207
208
209
214
222
224
225
228
232
Sample Solutions
238
Advanced Verilog
© 2004 Willamette HDL, Inc.
Outline
(cont’d)
5
Notes:
© 2004 Willamette HDL, Inc. &
Slide 5
This page was intentionally left blank.
Advanced Verilog
© 2004 Willamette HDL, Inc.
6
Notes:
© 2004 Willamette HDL, Inc. &
Slide 6
Day 1
Advanced Verilog
© 2004 Willamette HDL, Inc.
7
Notes:
© 2004 Willamette HDL, Inc. &
Slide 7
Verilog information
General:
1. Verilog® HDL, A Guide to Digital Design and Synthesis
by Samir Palnitkar - SunSoft Press / Prentice Hall
2. The Verilog® Hardware Description Language (3rd edition)
by Thomas & Moorby - Kluwer Academic Publishers
3. Digital Design and Synthesis with Verilog® HDL (latest edition)
by Sternheim, Singh, Madhavan, and Trivedi - Automata Publishing
More on our web site.
Net:
www.whdl.com --> links
Advanced Verilog
© 2004 Willamette HDL, Inc.
8
Notes:
© 2004 Willamette HDL, Inc. &
Slide 8
Top-Down
Design
Flows
Architectural
HDLArchitectural
By hand
HDL - Behavioral
Libraries
Graphical
“C”, truth tables,
etc.
By hand
HDL - RTL
Behavioral
Synthesis
By hand
Mixed Schematic
&
HDL - Gate models
Board
Logic
Synthesis
ASIC
FPGA
Netlist
Advanced Verilog
© 2004 Willamette HDL, Inc.
9
Notes:
© 2004 Willamette HDL, Inc. &
Slide 9
HDL
Modeling
Overview
Architectural
Definition
Behavioral
Abstract
Behavioral
equivalence
maintained
Functional
equivalence
maintained
HDL Compiler®
Advanced Verilog
Models
may
be
mixed
RTL
ASIC
FPGA
PLD
Detailed
Implementation
Other
By Hand
Gate Schematic
© 2004 Willamette HDL, Inc.
10
Notes:
© 2004 Willamette HDL, Inc. &
Slide 10
Mixed-Level Simulation
CPU
MEM
I/O
Behavioral
RTL
Gate
Advanced Verilog
© 2004 Willamette HDL, Inc.
11
Notes:
© 2004 Willamette HDL, Inc. &
Slide 11
Behavioral Equivalence
MEM
Read
Instruction
Data
(6 cycles later)
Behavioral
RTL
Read
Instruction
Gate
Advanced Verilog
© 2004 Willamette HDL, Inc.
Data
(6 cycles later)
12
Notes:
© 2004 Willamette HDL, Inc. &
Slide 12
Functional Equivalence
MEM
Behavioral
Read
Instruction
Data
(6 cycles later)
Read
Instruction
Data
(6 cycles later)
RTL
Gate
Advanced Verilog
© 2004 Willamette HDL, Inc.
13
Notes:
© 2004 Willamette HDL, Inc. &
Slide 13
Behavioral Model
Architectural
Characteristics:
Behavioral
•
Interfaces between Major Models are mixed
clock/event driven
•
Balance of design is event driven behavioral code
•
Behaviorally accurate
Purpose:
RTL
•
Integrated System Model
•
Fastest simulating code
Challenges:
•
Behavioral design is new: guidelines, models etc.
are scarce
Gate
Advanced Verilog
© 2004 Willamette HDL, Inc.
14
Notes:
© 2004 Willamette HDL, Inc. &
Slide 14
Behavioral-Level
System Example
CPU
Event
driven
Clk
driven
Bus IF
Event
driven
Clk
driven
Bus IF
Memory
I/O Board
Clk
driven
Bus IF
Event
driven
Disk
Clk
driven
Bus IF
Event
driven
Clk
Bus
driven
Bus
IF
Arbiter
Advanced Verilog
© 2004 Willamette HDL, Inc.
15
Notes:
© 2004 Willamette HDL, Inc. &
Slide 15
Behavioral-Level
Board Example
Bus
Mixed clk/event code for interface:
always wait (bus_valid)
@ (posedge clk)
Bus Interface
begin
data_reg <= #`delay bus_data;
addr_reg <= #`delay bus_addr;
Bus
State
Machine
In
Q
Out
Q
Memory
end
Memory
Event
Control
Event code for rest of module:
always wait (in_q_not_empty)
begin
read_queue(in_q, data_reg, addr_reg);
#`delay $damem(‘mem”,addr_reg,data_reg);
end
Advanced Verilog
© 2004 Willamette HDL, Inc.
16
Notes:
© 2004 Willamette HDL, Inc. &
Slide 16
RTL Model
Architectural
Characteristics:
Behavioral
•
Fully clock driven RTL code with some behavioral
constructs
•
Contains complete functional description
•
Cycle accurate
Purpose:
RTL
•
Input for Synthesis tools
•
Validation model for gate-level code
•
Full functionality
Challenges:
•
Textual entry
•
Synthesis coding style
Gate
Advanced Verilog
© 2004 Willamette HDL, Inc.
17
Notes:
© 2004 Willamette HDL, Inc. &
Slide 17
Example - RTL
Bus
always @ (posedge clk)
if (bus_valid)
begin
data_reg <= #`delay bus_data;
addr_reg <= #`delay bus_addr;
Bus Interface
end
Registers,
State Machines
& other Logic
Memory Interface
always @ (posedge clk)
if (memory_write)
Memory
Memory
Advanced Verilog
#`delay memory [addr_reg] = data_reg;
© 2004 Willamette HDL, Inc.
18
Notes:
© 2004 Willamette HDL, Inc. &
Slide 18
Gate Model
Architectural
Characteristics:
Behavioral
•
Fully clock driven Structural code (gate-level)
•
ASIC's, PLD's, Glue logic
•
Synthesized representation
•
Schematic representation
Purpose:
•
RTL
Representation for Physical design
Challenges:
• More simulator events, so slower simulation
Gate
Advanced Verilog
© 2004 Willamette HDL, Inc.
19
Notes:
© 2004 Willamette HDL, Inc. &
Slide 19
System-Level Simulation
Stimulus
always wait (in_q_not_empty)
begin
read_queue(in_q, data_reg, addr_reg, opcode);
case(opcode)
0:
1: $display("invalid opcode received ");
2: #`delay data_reg = memory[addr_reg];
default: do_nothing;
end
CPU
MEM
I/O
Behavioral
RTL
Gate
Advanced Verilog
© 2004 Willamette HDL, Inc.
20
Notes:
© 2004 Willamette HDL, Inc. &
Slide 20
Topic Verilog basics review
• Procedural assignments
• Time and Events (The Event Queue)
• Rules of Thumb
Advanced Verilog
© 2004 Willamette HDL, Inc.
21
Notes:
© 2004 Willamette HDL, Inc. &
Slide 21
Procedural Blocks
module name (port_names);
module port declarations
data type declarations
procedural blocks
continuous assignments
user defined tasks &
functions
primitive instances
• There are two types of procedural blocks:
• initial blocks - executes only once
• always blocks - executes in a loop
module instances
specify blocks
endmodule
• Multiple Procedural blocks may be used, if so the multiple blocks are
concurrent
• Execution order of procedural blocks is indeterminate
• Procedural blocks may have:
• Timing controls - which delays when a statement may be executed
• Procedural assignments
• Programming statements
Advanced Verilog
© 2004 Willamette HDL, Inc.
22
Speaker notes:
• Procedure blocks are concurrent in time, still done sequentially by computer itself so
end up with order during a time step
• When you have concurrent always blocks the simulator does NOT do a round robin
executing one statement from each, then one statement from each. Rather it
executes as many statements as it can in a particular always block (stopped by a
timing control) before switching execution to the next always block.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 22
Procedural statement
groups
When there is more than one statement within a
procedural block the statements must be grouped.
Sequential grouping:
Parallel grouping:
always
begin
a = 5;
c = 4;
wake_up = 1;
end
initial
begin
fork // example of nesting
a = 5;
c = 4;
wake_up = 1;
join
d = 8;
end
// executed 1st
// executed 2nd
// executed 3rd
NOTE:
• Statements are executed sequentially.
Advanced Verilog
NOTE: Inside a fork-join
• Statements are executed concurrently.
• Flow does not continue until all statements execute.
© 2004 Willamette HDL, Inc.
23
Speaker notes:
• Present the idea of "flow" i.e. how the simulator flows through the code in its
execution.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 23
Timing Controls
(procedural delays)
#delay - simple delay
Delays execution for a specific number of time steps.
#5 reg_a = reg_b;
@ (edge signal) - edge-triggered timing control
Delays execution until a transition on signal occurs.
edge is optional and can be specified as either posedge or negedge.
Several signal arguments can be specified using the keyword or.
always @ (posedge clk) reg_a = reg_b;
wait (expression) - level-sensitive timing control
Delays execution until expression evaluates true.
wait (cond_is_true) reg_a = reg_b;
Advanced Verilog
© 2004 Willamette HDL, Inc.
24
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 24
Time & Event Queues
Event Queues
time
t
t+1
t+2
t+3
• Time can only advance forward
• Time advances when every event scheduled at that time step is executed
• Simulation completes when all event queues are empty
• An event at time t may schedule another event at time t or any other time t+n
Advanced Verilog
© 2004 Willamette HDL, Inc.
25
Speaker notes:
• One event queue per time step
• abstract to help understand how simulators work. Actually multiple queues.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 25
Zero time loops
A zero time loop is encountered when events are continuously
scheduled at a time step without advancing time.
• Characterized by the simulator appearing to "hang"
(usually accompanied by a heartfelt "rats!").
Example
always a = b;
This causes the event a <-- b to be continuously scheduled and
executed at time t. Time can not advance beyond the start
time t.
a<-b
a<-b
a<-b
a<-b
a<-b
t
t+1
Advanced Verilog
© 2004 Willamette HDL, Inc.
26
Speaker notes:
• Use control-c to interrupt, then single step to see where you are at in the code.
• If you zero time loop on certain instructions some simulators will reach limits and
either kick you out or core dump. Make the above a non-blocking assignment and
VCS will core-dump.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 26
"Deadlocks"
A "deadlock" is encountered when a portion of the
code is waiting for events to occur and no events
are being scheduled.
• Characterized by simulation finishing
apparently in a premature fashion (usually
accompanied with an incredulous "what?")
• Simulation finishes because no events are
scheduled
Advanced Verilog
© 2004 Willamette HDL, Inc.
27
Speaker notes:
• Classical software deadlock where "a" waits for "b" which is waiting for "c" which is
waiting for "a".
• Usually only in behavioral modeling.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 27
Procedural assignments
Assignments made within procedural blocks are called procedural assignments:
• Value of the RHS of the equal sign is transferred to the LHS
• LHS must be a register data type (reg, integer, real or time)
NO NETS!
• RHS may be any valid expression or signal
always @ (posedge clk)
begin
a = 5;
// procedural assignment
c = 4*32/6; // procedural assignment
wake_up =$time; // procedural assignment
end
Advanced Verilog
© 2004 Willamette HDL, Inc.
28
Speaker notes:
• One of the most common problems new Verilog users have is trying to assign values
to nets from within an always block.
• A very common example of this problem is trying to directly assign a value to an
output port inside of an always block.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 28
Blocking Assignments
•
RHS expression evaluated
•
Assignment is scheduled
•
Flow blocks until assignment is executed
initial
Time
begin
a = b;
c = d;
e = f;
end
a<-b(t)
Event Queues
c<-d(t)
e<-f(t)
t
t’ t
t’’
t+1
t+2
t+3
<-- Execution order
Advanced Verilog
© 2004 Willamette HDL, Inc.
29
Speaker notes:
• Draw up on white board before explaining how blocking assignments work. use the
example coding correctly to generate the waveform for the assignment of three
registers a,c,e each clocked at the rising edge of a clock signal with a propagation
delay of 1, as a way of leading up to the rules of thumb through out the following
slides. The goal is to correctly code up so a waveform would be generated correctly
for the registers given that a gets b(t) at time = t+1, c gets b(t) at time = t+1, and e
gets f(t) at time = t+1. Assume the rising edge of the clock is at time = t. b,d,f are
also changing at time = t+1. Draw out the registers and a waveform with clk, a,b,c,d.
• Explain the event queue diagram and nomenclature.
• After walking through the explanation of the scheduling ask the question "if I
Notes:
substituted the following code ' always @ (posedge clk) ' for the ' initial ' would the
code then generate the waveform correctly for a,c & e?" the answer is no since
propagation delay is not taken into account. With this code a get the proper value but
at the wrong time. a gets b(t) at time = t instead of time = t+1.
© 2004 Willamette HDL, Inc. &
Slide 29
Delayed Blocking assignments
•
Evaluation of the assignment is delayed by the timing control
•
RHS expression evaluated
•
Assignment is scheduled
•
Flow blocks until assignment is executed
Event Queues
initial
begin
#1 a = b;
end
t
a<-b(t+1)
t+1
t+2
equivalent to...
begin
#1;
a= b;
end
Advanced Verilog
Time
t+3
<-- Execution order
© 2004 Willamette HDL, Inc.
30
Speaker notes:
• After walking through the explanation of the scheduling ask the question "if I
substituted the following code ' always @ (posedge clk) ' for the ' initial ' would the
code then generate the waveform correctly for a?" the answer is no since
propagation delay is not modeled correctly. With this code a get the wrong value but
at the proper time. a gets b(t+1) instead of b(t).
Notes:
© 2004 Willamette HDL, Inc. &
Slide 30
Delayed Blocking assignments
Event Queues
initial
Time
t
begin
#1 a = b;
#1 c = d;
#1 e = f;
end
a<-b(t+1)
t+1
c<-d(t+2)
t+2
e<-f(t+3)
t+3
<-- Execution order
equivalent to…
begin
#1;
a= b;
#1;
c=d;
#1;
e=f;
end
Advanced Verilog
LHS delays are additive with blocking assignment.
© 2004 Willamette HDL, Inc.
31
Speaker notes:
• After walking through the explanation of the scheduling ask the question "if I
substituted the following code ' always @ (posedge clk) ' for the ' initial ' would the
code then generate the waveform correctly for a?" the answer is no. Same problem
as previous slide except compounded since the delays are additive because of the
blocking assignments.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 31
Blocking Intra-procedural
delayed assignment
•
•
RHS expression evaluated
Assignment is scheduled but delayed by the timing control
•
Flow blocks until assignment is executed
Event Queues
Time
t
a<-b(t)
initial
t+2
begin
a = #1 b;
end
Advanced Verilog
t+1
t+3
<-- Execution order
© 2004 Willamette HDL, Inc.
32
Speaker notes:
• After walking through the explanation of the scheduling ask the question "if I
substituted the following code ' always @ (posedge clk) ' for the ' initial ' would the
code then generate the waveform correctly for a?" the answer is yes!
Notes:
© 2004 Willamette HDL, Inc. &
Slide 32
Blocking Intra-procedural
delayed assignment
Event Queues
initial
begin
a = #1 b;
c = #1 d;
e = #1 f;
end
Time
t
a<-b(t)
t+1
c<-d(t+1)
t+2
e<-f(t+2)
t+3
<-- Execution order
RHS delays accumulate with blocking assignment.
Advanced Verilog
© 2004 Willamette HDL, Inc.
33
Speaker notes:
• After walking through the explanation of the scheduling ask the question "if I
substituted the following code ' always @ (posedge clk) ' for the ' initial ' would the
code then generate the waveform correctly for a?" the answer is no. a is correct but
since the delays are additive because of the blocking assignment c & e are incorrect.
• Suggested alternatives may come from students:
1) using 3 separate always blocks. That works but is not the best of styles.
Alternative style is better (non-blocking).
2) using fork-join instead of begin end works, but not synthesizable. Also you can still
have race conditions.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 33
Quiz
always @ (posedge clk)
a = b;
always @ (posedge clk)
b = c;
Assume b = 3 and c = 5.
After the first @ (posedge clk)
what is the value of a?
Advanced Verilog
© 2004 Willamette HDL, Inc.
34
Speaker notes:
• trick question. The correct answer is " indeterminate" since you don't know which
always block executes first.
• If you run the code over and over again you will get the same result. i.e. the same
always block goes first.
• Different simulators will give different results.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 34
Quiz
always @ (posedge clk)
begin
a = b;
b = a;
end
After the first @ (posedge clk),
does this do a swap?
Advanced Verilog
© 2004 Willamette HDL, Inc.
35
Speaker notes:
• No it doesn't. Use the event queue to illustrate if needed with given initial values for a
& b.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 35
Non-blocking Assignments
•
RHS expression evaluated
•
•
Assignment is scheduled at the end of the queue
Flow continues on
•
Assignment is made at end of the time step
Event Queues
initial
begin
a <= b;
end
Time
t
a<-b(t)
t+1
t+2
t+3
<-- Execution order
Advanced Verilog
© 2004 Willamette HDL, Inc.
36
Speaker notes:
• Point out that original value of b is stored into a temp location.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 36
Race solved!
always @ (posedge clk)
a <= b;
always @ (posedge clk)
b <= c;
a always gets the value in b
Event Queues
a<-b(t)
Time
t
b<-c(t)
t+1
t+2
t+3
<-- Execution order
Advanced Verilog
© 2004 Willamette HDL, Inc.
37
Speaker notes:
• The order of execution doesn't matter. May need to walk through both orders to show
this.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 37
Swap Accomplished!
always @ (posedge clk)
begin
a <= b;
b <= a;
end
a always gets b, b always gets a
Event Queues
b<-a(t)
Time
t
a<-b(t)
t+1
t+2
t+3
<-- Execution order
Advanced Verilog
© 2004 Willamette HDL, Inc.
38
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 38
Mixed Blocking and
Non-blocking
Event Queues
initial
begin
a = b;
c <= d;
c = f;
end
c<-d(t)
a<-b(t)
t
t+1
t+2
t+3
<-- Execution order
DO NOT DO THIS!!
Advanced Verilog
c<-f(t)
Time
© 2004 Willamette HDL, Inc.
39
Speaker notes:
• Note difference in order of evaluation vs. execution. Good way to confuse yourself!
Notes:
© 2004 Willamette HDL, Inc. &
Slide 39
Delayed Non-blocking Assignments
•
initial
begin
#1 a <= b;
end
Evaluation of the assignment is delayed by the
timing control
•
•
RHS expression evaluated
Assignment is scheduled at the end of the queue
•
Flow continues on
•
Assignment is made at end of the time step
Event Queues
Time
t
t+1
a<-b(t+1)
t+2
t+3
<-- Execution order
Advanced Verilog
© 2004 Willamette HDL, Inc.
40
Speaker notes:
• Same result as the blocking assignment: #1 in front - no go.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 40
Non-blocking
Intra-procedural
delayed Assignments
initial
begin
a <= #1 b;
end
•
RHS expression evaluated
•
Assignment is delayed by the timing control
and is scheduled at the end of the queue
•
Flow continues on
•
Assignment is made at end of the time step
Event Queues
Time
t
t+1
a<-b(t)
t+2
t+3
<-- Execution order
Advanced Verilog
© 2004 Willamette HDL, Inc.
41
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 41
Non-blocking
Intra-procedural
delayed Assignments
initial
begin
a <= #1 b;
c <= #1 d;
e <= #1 f;
end
Event Queues
Time
t
e<-f(t)
c<-d(t)
a<-b(t)
t+1
t+2
t+3
<-- Execution order
RHS delays do not accumulate with non-blocking
-butLHS delays would accumulate same as in blocking case.
Advanced Verilog
© 2004 Willamette HDL, Inc.
42
Speaker notes:
• This works for all three registers.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 42
Procedural assignment
Example
f+1
f
e
d
c
b
a
Expected output:
fedcba
1xxxxx
21xxxx
321xxx
4321xx
54321x
654321
765432
and so on
Advanced Verilog
© 2004 Willamette HDL, Inc.
43
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 43
pound.v
module pound;
reg [7:0] a,b,c,d,e,f;
reg clk;
initial
begin
clk=0;
f = 1;
forever
#25 clk = !clk;
end
/*** group 1 ***/
always @ (posedge clk) // group 1
begin
e = f;
end
/*** group 2 ***/
always @ (posedge clk) // group 2
begin
c = d;
d = e;
end
/*** group 3 ***/
always @ (posedge clk) // group 3
begin
a = b;
b = c;
end
/*** group 4 ***/
always @ (posedge clk) // group 4
begin
f = f + 1;
end
initial
$monitor (f,,e,,d,,c,,b,,a);
initial
#700 $stop;
endmodule
Is this the best way to do it? Why or why not? If not, what would be the best way to do it?
Advanced Verilog
© 2004 Willamette HDL, Inc.
44
Notes:
© 2004 Willamette HDL, Inc. &
Slide 44
+race
VCS has built-in race condition detection. ( +race option)
It can spot “many” race conditions in your simulations:
read-write
write-write
2 processes access variable simultaneously
2 processes write variable simultaneously
If you try this on pound.v: vcs –R +race pound.v
You will get 2 new output files:
race.out
one line per race detected
race.unique.out
filtered to show only unique races
race.unique.out
Unique Races
Races of no consequence removed
Synopsys VCS RACE REPORT
25 "e": read pound (pound.v: 21) && write pound (pound.v:15)
75 "c": read pound (pound.v: 28) && write pound (pound.v:20)
Advanced Verilog
© 2004 Willamette HDL, Inc.
VCS Tip!
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
module pound;
reg [7:0] a,b,c,d,e,f;
reg clk;
initial
begin
clk=0;
f = 1;
forever
#25 clk = !clk;
end
/*** group 1 ***/
always @ (posedge clk) // group 1
begin
e = f;
end
/*** group 2 ***/
always @ (posedge clk) // group 2
begin
c = d;
d = e;
end
/*** group 3 ***/
always @ (posedge clk) // group 3
begin
a = b;
b = c;
end
/*** group 4 ***/
always @ (posedge clk) // group 4
begin
f = f + 1;
end
initial
$monitor (f,,e,,d,,c,,b,,a);
initial
#700 $stop;
endmodule
45
Notes:
© 2004 Willamette HDL, Inc. &
Slide 45
Virsim Tip!
Lab: Delta Cycle display
1. Type: vcs –RI pound.v & in the IW specify a Step Time of 100
2. Also in IW select pulldown Sim >> Record Delta Cycle Data
3. Open the HB and WW windows and display all signals in pound.v
#2
4. In IW click OK to run simulation to time 100
5. In WW right-click on clk edge at time 75 and select Expand Time
#4
#4
#1
Advanced Verilog
© 2004 Willamette HDL, Inc.
46
Notes:
© 2004 Willamette HDL, Inc. &
Slide 46
Lab: Delta Cycle display (2)
expanded
“delta-time”
5. WW updates to look like this:
#6
Virsim Tip!
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
/*** group 1 ***/
always @ (posedge clk) // group 1
begin
e = f;
end
/*** group 2 ***/
always @ (posedge clk) // group 2
begin
c = d;
d = e;
end
30.
31.
32.
33.
34.
/*** group 4 ***/
always @ (posedge clk) // group 4
begin
f = f + 1;
end
/*** group 3 ***/
always @ (posedge clk) // group 3
begin
a = b;
b = c;
end
6. Within the expanded “delta time” at 75nS, notice the order in which the registers update (left to right):
E, C, D, B, F. This corresponds to the “indeterminate” order of execution of the procedural blocks.
Question: Why did race.unique.out (2 slides back) report a race condition on register “c” at time 75?
race.unique.out
75 "c": read pound (pound.v: 28) && write pound (pound.v:20)
Answer: The waveforms show that on posedge clk, “c” is assigned 8’h01 correctly from “d”, BUT “b” is assigned 8’h01 incorrectly by sampling the new value of “c”.
“b” should have stayed at 8’hxx.
Advanced Verilog
© 2004 Willamette HDL, Inc.
47
Notes:
© 2004 Willamette HDL, Inc. &
Slide 47
Rules of Thumb - 1
Synthesizable Verilog:
•
Use blocking assignments for
combinational always blocks
and do not use delays...
Example
always @(dat)
i_dat = ~dat;
Non-synthesizable Verilog:
•
•
•
When the RHS is a fixed value,
use a blocking assignment
Any procedural delay should appear
on the LHS
Do not use non-blocking
assignments,
which tend to be confusing
Examples
#5 a = `FALSE;
#5 b = 42;
#5 c = c+1;
// inc/decrement of values
Advanced Verilog
© 2004 Willamette HDL, Inc.
48
Speaker notes:
• emphasize that the top is for synthesizable code.
• Bullet #3 in bottom text leads into next slide.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 48
Quiz
Given the following code:
`define FALSE 0
`define TRUE 1
initial
begin
a = `FALSE;
a <= `TRUE;
if (a == `TRUE)
$display ("True");
else
$display ("False");
end
What will print out? True or False?
Advanced Verilog
© 2004 Willamette HDL, Inc.
49
Speaker notes:
• answer is False since the assignment of a <-- 1 is scheduled but not executed when
the if statement executes.
• What happens if a #1 is placed in front of the if statement? Prints out True. Not good
practice to put #1 in your code to make it work the way you think it should.
• What happens if both assignments are non-blocking? Still prints out False since a = x
when if statement executes.
Notes:
© 2004 Willamette HDL, Inc. &
Slide 49
Rules of Thumb - 2
Synthesizable Verilog:
Non-synthesizable Verilog:
•
•
•
Use non-blocking assignments
exclusively for sequential always
blocks
A RHS delay, produces an ‘intuitive’
transport delay in simulation and
makes waveforms easier to read
•
When the RHS is a "sampled" value (e.g. registers
and wires driven by another concurrent block),
use a non blocking assignment
Any procedural delay should appear on the RHS
Examples
Example
always @(posedge CLK)
Q <= #1 D;
a <= #5 b; // where b is a register
c <= #5 d; // where d is a wire
The procedural delay (#) on the RHS best models
propagation delay as an engineer understands it.
Advanced Verilog
© 2004 Willamette HDL, Inc.
50
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 50
Rules of Thumb - 0
• Be Consistent!
• Apply the ROT’s uniformly!
Advanced Verilog
© 2004 Willamette HDL, Inc.
51
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 51
Given the following code:
Harder Quiz
module hard_quiz;
reg [3:0] a,b,c;
initial // init registers at time zero
begin
a <= 0;
b <= 0;
c <= 0;
end
initial
begin
#1b <= 1;
c <= 5;
a <= 1;
while (a < c)
begin
$display (”at time = %0d b = %h”,$time, b);
#5 a <= a+1;
Lesson?
b <= b+1;
Non-blocking assignments can be confusing.
end
end
endmodule
What is the output?
Advanced Verilog
© 2004 Willamette HDL, Inc.
52
Notes:
© 2004 Willamette HDL, Inc. &
Slide 52
Given the following code:
Harder Quiz
Revision 1
module hard_quiz_1;
reg [3:0] a,b,c;
initial // init registers at time zero
begin
a <= 0;
b <= 0;
c <= 0;
end
initial
begin
#1b <= 1;
c <= 5;
a <= 1;
while (a <= c) //change to less than or equal to
begin
$display (”at time = %0d b = %h”,$time, b);
#5 a <= a+1;
b <= b+1;
end
end
endmodule
Now what is the output?
Advanced Verilog
© 2004 Willamette HDL, Inc.
53
Notes:
© 2004 Willamette HDL, Inc. &
Slide 53
Given the following code:
Harder Quiz
Revision 2
module hard_quiz_2;
reg [3:0] a,b,c;
initial // init registers at time zero
begin
a <= 0;
b <= 0;
c <= 0;
end
initial
begin
#1b <= 1;
c <= 5;
a <= 1;
while (a <= c)
begin
$display (”at time = %0d b = %h”,$time, b);
#5 a = a+1; //change to blocking
b = b+1; //change to blocking
end
Of course YOU would never mix blocking
end
And non-blocking assignments would you? ☺
endmodule
Now what is the output?
Advanced Verilog
© 2004 Willamette HDL, Inc.
54
Notes:
© 2004 Willamette HDL, Inc. &
Slide 54
Verilog 2001 Enhancements
The Verilog 2001 Standard produced by IEEE makes some important and
useful enhancements to the base language. Many of these enhancements
were already part of VCS or are part of the SystemVerilog support added
with VCS v7
Indexed vector part-selects
Multi-dimensional arrays
Signed arithmetic extensions
Power operator
Wildcard sensitivity list
Comma separated sens. List
Enhanced File IO
Inline-Explicit parameter passing
Sized Parameters
Combined port and type declarations
ANSI style port/IO declarations
“reg” declaration/initialization
Enhanced conditional compilation
To use these in your code, you must add “ +v2k ” to the vcs command line.
Advanced Verilog
© 2004 Willamette HDL, Inc.
55
Notes:
© 2004 Willamette HDL, Inc. &
Slide 55
Verilog2001: Multi-dimension indexing
Prior to Verilog 2001 a bit or subrange of a location in the array could not be
accessed directly, a temporary variable had to be used.
temp = mem[33];
3_bit_reg = temp[8:6];
// data_reg gets data at addr 33
//get three bits of addr 33
mem
255
temp
8
8
33
3_bit_reg
6
2
0
6
“address”
dimensions
first (in order)
0
15
0
Verilog 2001 finally corrects this:
3_bit_reg = mem[33][8:6];
“data”
dimensions
(slicing) last
Multi-dim. Indexing only supported on RHS of an assignment
Advanced Verilog
© 2004 Willamette HDL, Inc.
56
Notes:
© 2004 Willamette HDL, Inc. &
Slide 56
Verilog2001: enhancements
Enhanced conditional compilation:
`ifndef macro
verilog source
`elsif macro2
verilog source
`endif
`undef
Any-dimensional arrays of registers AND nets…
syntax:
reg/net [msb:lsb] identifier [first_addr:last_addr], [first_addr:last_addr] , [… ;
where
msb:lsb determine the width (word size) of the memory
first_addr:last_addr determine each dimension (address range) of the array
Addressing Multi-dim arrays:
“address”
dimensions
first (in order)
reg [15:0] D3 [1023:1020] [15:8] [7:3] [2:0];
// 4x8x5x3 array of 16-bit reg’s
initial begin
D3 [1023] [15] [7] [2] = 16’hFFFF;
// store:
ffff
D3 [1023] [15] [7] [2] = D3 [1023] [15] [7] [2] –1;
// decrement: fffe
$display(“%h”, D3 [1023] [15] [7] [2] [7:0] );
// print:
fe
“data”
end
dimensions
(slicing) last
Advanced Verilog
© 2004 Willamette HDL, Inc.
57
Notes:
© 2004 Willamette HDL, Inc. &
Slide 57
Indexed vector part-selects
Bit-selects in verilog expressions may use variables:
reg [63:0] data;
reg data_bit;
reg [7:0] data_byte;
integer bit_sel;
initial begin
data = 32;
bit_sel = 5;
data_bit = data[bit_sel];
// Prior to Verilog 2001, variables may NOT be used for part-selects.
data_byte = data[bit_sel:0];
// Unsupported in any verilog version!
// Verilog 2001 introduces a new syntax…
data_byte = data[bit_sel -: 6];
end
// Defines a 6-bit slice ( i.e. data[5:0] )
New Syntax
-:
base_expr +:
base_expr
Advanced Verilog
offset
// neg. offset from base_expr (inclusive)
offset
// pos. offset from base_expr (inclusive)
© 2004 Willamette HDL, Inc.
58
Notes:
© 2004 Willamette HDL, Inc. &
Slide 58
Parameter redefinition
Currently, Verilog supports two styles of parameter redefinition:
Explicit: defparam hierarchy_path.parameter_name = value;
Implicit: module_name # (value) instance_name (signals);
The Verilog 2001 Standard adds a third (recommended) style:
In-Line explicit:
module_name # (.parameter_name(value)) instance_name (signals);
module fifo (d_in, d_out, write, read, full, empty);
...
parameter width = 8, depth = 32;
...
endmodule
//module definition
//parameter declarations and default values
module test_fifo;
// testbench
...
fifo # (.depth(64), .width(16) ) fifo_64(d_in_64,d_out_64,write_64,read_64,full_64,empty_64);
// instance of fifo with override of parameters: depth to 64 and width to 16
...
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
59
Notes:
© 2004 Willamette HDL, Inc. &
Slide 59
Combined port/type declarations
Verilog 2001 supports co-declaration of a port AND its related variable:
port_direction port_type port_name, port_name ... ;
Vector (Multiple bit) port declarations:
port_direction port_type [port_size] port_name, port_name ... ;
port_direction :
port_type :
port_name :
port_size :
input, inout (bi-directional) or output
is a data type (reg, wire)
legal identifier
is a range from [msb:lsb]
input wire a, into_here, george;
input wire [7:0] in_bus, data;
output reg [8:31] out_bus;
inout wire [maxsize-1:0] a_bus;
Advanced Verilog
// scalar ports and nets
// vectored ports and nets
// vectored port and driving reg
// parameterized port and net
© 2004 Willamette HDL, Inc.
60
Notes:
© 2004 Willamette HDL, Inc. &
Slide 60
ANSI style port declarations
Port declarations can also be made within the parentheses of the module
declaration.
module module_name (port_direction port_type [port_width] port_name,
port_direction port_type [port_width] port_name,
etc. etc.
);
module MUX2 (output
input
input
input
Advanced Verilog
reg [1:0]
wire [1:0]
wire [1:0]
wire [1:0]
out,
sel,
in_a,
in_b ) ;
© 2004 Willamette HDL, Inc.
61
Notes:
© 2004 Willamette HDL, Inc. &
Slide 61
Topic – Verilog 2001 File IO routines
Introducing some of the coolest features of Verilog 2001
• Access data from a file by char, line, block
• Log selective data to many files (previous limit: 32)
• Faster than PLI equivalents (~30% faster)
Advanced Verilog
© 2004 Willamette HDL, Inc.
62
Notes:
© 2004 Willamette HDL, Inc. &
Slide 62
File IO routines
$fopen
$fclose
$ferror
$fgetc
$fgets
$fflush
$fread
$fscanf
$fseek
$fsscanf
$ftell
$rewind
$sformat
$swrite
$swriteb
$swriteh
$swriteo
$ungetc.
- Runs in compatible mode OR with optional type arguments e.g. “r[b]” “w[b]” “a[b]”
- Returns error message on a file (if any) as a string (<= 640 chars)
- Reads a character from a file
NOTE
“b” implies binary data
rather than ascii
but this distinction isn’t
necessary for UNIX
- Reads binary data from a file into a reg or memory
- Reads characters from a file, interpreting them according to format specs.
- Returns offset to last position read/written in a file (e.g. total file size read)
Advanced Verilog
New substitution directives:
%c - substitute a single character
%u - substitute unformatted binary data
%z - read unformatted binary data ( $fscanf etc.)
© 2004 Willamette HDL, Inc.
63
Notes:
© 2004 Willamette HDL, Inc. &
Slide 63
Example File IO code: file_read.v
`define FILE_SIZE 10000
module file_read;
integer rfile, wfile, in, i;
reg [7:0] mem[0:`FILE_SIZE -1];
reg [13*8:1] file_name[0:1]; // Allow DOS filenames
reg [640:1] e_msg;
initial
begin
file_name[0] = “file.bin"; // Filename
rfile = $fopen(file_name[0], "rb"); // Open the file for reading
in = $fread(mem, rfile, 0);
// Read file into memory
i = $ferror(rfile, e_msg);
// check for error message if any
$display("\nFile size: %0d $ferror msg: %0s \n\n", $ftell(rfile), e_msg);
$fclose(rfile);
$finish;
end
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
64
Notes:
© 2004 Willamette HDL, Inc. &
Slide 64
File IO Exercise:Steganographic Decryption
Working directory: STEG_DECODE
Purpose: Write an abstract Verilog model using v2001 fileio routines
The picture message.bmp is encoded with a secret message, hidden in the least significant bit
of each pixels value. The algorithm skips pixels 0-63 of the file.
Pixels 64-79 contain the length of the message in bytes. (Multiply by 8 for total pixel-count)
Once you know the length, the message is in pixels 80 and later.
The bits in each group of 8 pixels are arranged least significant to most significant.
1.
2.
Working directory: STEG_DECODE
Code up a Verilog module which reads in the binary file and decodes the message.
Use File IO function $fread to load the file into a byte-wide memory.
Example 1:- How the message length is encoded:
Byte 64
1
0
1
0
1
Byte 65
0
1
1
1
0
1
...
0
1
1
Message Length
1
0
1
1
1
1
1
1
1
0
...
Byte 78
0
0
1
Byte 79
0
1
1
1
0
79
78 77
76 75
74 73
72
71
70
69 68
67 66
65
64
0
1
x
x
x
x
x
x
x
1
1
Advanced Verilog
x
x
x
© 2004 Willamette HDL, Inc.
x
x
65
Notes:
© 2004 Willamette HDL, Inc. &
Slide 65
File IO Exercise:
Steganographic Decryption
Example 2:- One byte of a message you might find in bytes 80+
Byte 80
1
0
1
0
1
Byte 81
0
1
0
1
0
1
Byte 82
0
0
1
1
1
0
1
0
1
0
1
0
1
0
1
0
1
1
1
0
1
1
1
1
1
1
0
0
1
1
1
1
0
0x72 = 'r'
0
1
1
1
0
0
1
0
Byte 85
0
1
1
1
0
1
Byte 86
0
1
Byte 83
Byte 84
1
0
0
1
Byte 87
0
1
1
1
0
1
1
1
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
66
Notes:
© 2004 Willamette HDL, Inc. &
Slide 66
File IO: Writing a binary file
You just saw how to open/read a binary file in Verilog; but what about writing such a file?
Here is the Verilog code used to encrypt the message you just retrieved:
// Encrypt text for Steganographic decoder problem
//
// Must compile with +v2k for multi-dimen. addressing
//
`define FILE_SIZE 65535
module encrypt;
integer tfile, rfile, wfile, ifs, tfs, i, pxl,chrs;
reg [15:0] siz;
reg [3:0] bits;
reg [7:0] img [0:`FILE_SIZE -1]; // ,
reg [7:0] txt[0:157];
pxl=64;
for(i=0; i<=15; i=i+1)
// encode message length
if(tfs[i])
img[pxl+i] = img[pxl+i] | 8'b1;
else
img[pxl+i] = img[pxl+i] & 8'hfe;
initial
begin
tfile = $fopen("message.txt", "r"); // Open the text file for reading
rfile = $fopen("morning.bmp", "rb"); // Open the img file for reading
wfile = $fopen("message.bmp", "w"); // Open new img file for writing
i = $fread(img, rfile, 0);
// Read the image into memory
ifs = $ftell(rfile);
// capture file size in "ifs"
i = $fread(txt, tfile, 0);
// Read the text into memory
tfs = $ftell(tfile);
// capture file size in "tfs"
$display("\n\nText File: %0d bytes IMG File: %0d bytes\n\n",tfs, ifs);
for(i=0; i<=tfs; i=i+1)
$write("%s",txt[i]);
tfs=tfs+8;
// print message text
tfs=(tfs*8);
// pixels necessary for message
bits = 0;
chrs = 0;
for(i=80; i<=80+tfs; i=i+1)
begin
if(txt[chrs][bits])
img[i] = img[i] | 8'b1;
else
img[i] = img[i] & 8'hfe;
bits = bits+1;
if(bits[3])begin chrs = chrs+1; bits = 0; end
end
for(i=0; i< ifs; i = i+4)
// save img file
$fwrite(wfile,"%u", {img[i+3],img[i+2],img[i+1],img[i]});
$display("\n");
$fclose(rfile);
$fclose(wfile);
$fclose(tfile);
$finish;
end
endmodule //
Advanced Verilog
© 2004 Willamette HDL, Inc.
NOTE
UNIX files are
packed 32-bit
words
67
Notes:
© 2004 Willamette HDL, Inc. &
Slide 67
This page was intentionally left blank.
Advanced Verilog
© 2004 Willamette HDL, Inc.
68
Notes:
© 2004 Willamette HDL, Inc. &
Slide 68
SystemVerilog Enhancements
Advanced Verilog
© 2004 Willamette HDL, Inc.
69
Notes:
© 2004 Willamette HDL, Inc. &
Slide 69
The promise of System Verilog
•
•
•
•
Abstract Structures
Executable Spec
Interfaces/Protocols
Transaction-level Modeling
Architects
Verification
Engineers
SystemC
VCS
Hardware
Designers
• High Level Models
• RTL improvements
• Timing
Advanced Verilog
© 2004 Willamette HDL, Inc.
70
Notes:
© 2004 Willamette HDL, Inc. &
Slide 70
System Verilog pedigree
System Verilog expands the features of classic Verilog (Verilog 95?)
by adding Verilog 2001 and more.
Verilog 95
• Concurrency & timing
• Event Ordering
• RTL/gate/switch simulation
• Signal strength modeling
Verilog 2001
• ANSI port/argument lists
• Automatic tasks/functions
• Generate statements
• Signed Arithmetic
• Multi-dim arrays
New ( Unique ) Features
• $root
• Interfaces
• Combin/seq/latch processes
• Assertions (orphaned)
• SVA Assertions
C/C++
• Data types
• Structs & Unions
• Dynamic memory
v3.0
VCS 7.1.1
Advanced Verilog
© 2004 Willamette HDL, Inc.
71
Notes:
© 2004 Willamette HDL, Inc. &
Slide 71
System Verilog 3.1 adds much more
Verilog 95
• Concurrency & timing
• Event Ordering
• RTL/gate/switch simulation
• Signal strength modeling
Verilog 2001
• ANSI port/argument lists
• Automatic tasks/functions
• Generate statements
• Signed Arithmetic
• Configurations
• Multi-dim arrays
New ( Unique ) Features
• Fork-join control options
• Comb/seq/latch processes
• Assertions (SVA)
• Interfaces
• Classes, inheritance etc.
• Operator overloading
• Program Blocks
• Clocking Domains
• Semaphores/Mailboxes
• Random data Generation
• Constraints
• Handles (safe pointers)
• Direct Programming I/F (DPI)
C/C++
• Data types
• Structs & Unions
• Dynamic memory
v3.1
VCS X.X
Advanced Verilog
© 2004 Willamette HDL, Inc.
72
Notes:
© 2004 Willamette HDL, Inc. &
Slide 72
VCS 7.1 Simulator
SystemVerilog
Code
*.sv
Verilog
Code
*.v
VCS 7.1
+v2k
+sysvcs
Run-time switch to enable Verilog 2001 features
Advanced Verilog
© 2004 Willamette HDL, Inc.
Run-time switch to enable SV features
73
Notes:
© 2004 Willamette HDL, Inc. &
Slide 73
Variables
SystemVerilog is 100% backward compatible with Verilog 1995 and 2001.
In addition:
• SystemVerilog inherits variables/types from C
• SystemVerilog has additional types for system-level design and test
There are 2 types of variable in SystemVerilog
Static
• Allocated and initialized at time zero
• Exist for the entire simulation
Automatic
•
•
•
•
Designed to allow recursion in blocks, tasks and functions
Reallocated and initialized each time a block/task/function is entered
May NOT be used to trigger an event
May NOT be assigned by a non-blocking assignment
Advanced Verilog
© 2004 Willamette HDL, Inc.
74
Notes:
© 2004 Willamette HDL, Inc. &
Slide 74
Data Types: Basic & Integer
Basic data types
integer types are signed or unsigned
integer sig; // signed by default
integer unsigned usig;
int unsigned usig;
time
64-bit integer, defaults to seconds
Synth
real
from Verilog, like C double, 64-bits 2003.12
shortreal from C float, 32-bits
string
variable size array of “char” 7.1
bit, reg, logic default to unsigned
void
non-existant data, used for functions
Others default to signed
Integer data types
char
shortint
int
longint
byte
bit
reg
integer
logic
from C (usually 8-bit signed integer)
16-bit signed integer
32-bit signed integer
64-bit signed integer
8-bit signed integer (usually same as char)
0 or 1
from Verilog (unsized: 0, 1, X, Z)
32-bit signed from Verilog (sized: 0, 1, X, Z)
like reg but with different usage rules
Advanced Verilog
© 2004 Willamette HDL, Inc.
char
shortint
int
longint
byte
bit
reg
logic
integer
2-state
( 1, 0 )
4-state
( 1, 0, X, Z )
75
Notes:
© 2004 Willamette HDL, Inc. &
Slide 75
Data Types: User defined
Not content with adding a wide set of new datatypes to the mix, SystemVerilog borrows
from C the syntax for declaring new types: typedef
typedef int mm ;
// mm becomes a new type
mm centi =10, metre = 1000;
// these are 2 new variables of type ‘mm’
Synth
2003.12
ignore
Strange as it may seem, a type may be used before it is defined
7.1
Synth
2003.12
typedef delay;
// known as an “empty” typedef
delay sec = 1 ;
// declare/initialize even though you do not know yet what it is ☺
typedef int delay;
Synthesis Tips (2003.12)
1. Synthesis tools ignore variable initialization
2. typedef must be defined before being used
Advanced Verilog
© 2004 Willamette HDL, Inc.
76
Notes:
© 2004 Willamette HDL, Inc. &
Slide 76
Data Types: Casting
Type Casting
Synth
2003.12
<type>′ (<value>)
Convert between data types with the cast (forward-tick):
int′ (2.0*3.0); // Cast result to integer
10′ (a+b);
// implies a number of bits (10 here)
signed′ (a); // works for sign-changing too
User defined types may also be cast:
mytype′ (b);
For compatibility these Verilog functions are supported:
$itor, $rtoi, $bitstoreal, $realtobits, $signed, $unsigned
Advanced Verilog
© 2004 Willamette HDL, Inc.
77
Notes:
© 2004 Willamette HDL, Inc. &
Slide 77
Arrays - Multidimensions
Synth
2003.12
SystemVerilog supports multi-dimensional arrays just like Verilog…
bit [7:0] mem [4:1]; // byte-wide memory with 4 addresses, like Verilog
mem[ i ] [6:1] = 0;
// 2D+ indexing supported (like Verilog 2001)
From Verilog 2001 you also get multi-multi-dimensions… phew!
bit [a:b] [n:m] [p:q] mem [ t:u] [v:w] [x:y]; // arbitrary dimensions
packed
unit
unpacked
SystemVerilog uses the terms packed and unpacked to refer to how the data is actually
stored in memory (e.g. packed => 8-bits to a byte, unpacked => 1 bit per word )
a0
a1
a2
a3
b3 b2 b1 b0
packed
Advanced Verilog
unpacked
© 2004 Willamette HDL, Inc.
78
Notes:
© 2004 Willamette HDL, Inc. &
Slide 78
Arrays – Multidim. (simplified)
It may help you to think of these in the classic Verilog terminology…
So it’s as if you have multi-dimensions of data and of address…
bit [a:b] [n:m] [p:q] mem [ t:u] [v:w] [x:y]; // big ugly (5D) memory ☺
(packed) data
address
(unpacked)
The packed dimensions describe how the data is arranged (or packed)
and the unpacked dimensions describe how you map this data to a multi-dimension address…
bit [3:0] [7:0] aa ;
byte3
byte2
// a single, packed 4-byte data word (4x8 = 32 bits)
byte1
bit [3:0] [7:0] bb [1:0];
byte0
aa[0] = aa[0] + 1; // byte increment
// 2-deep array of packed 4-byte data words
byte3
byte2
byte1
byte0
byte3
byte2
byte1
byte0
Advanced Verilog
aa
bb[1]
bb[0]
bb[1] = bb[0]; // word assignment
© 2004 Willamette HDL, Inc.
79
Notes:
© 2004 Willamette HDL, Inc. &
Slide 79
Array Access – Example 1
bit [3:0] [7:0] aa ;
bit [3:0] [7:0] bb [10:1] ;
// packed 4-byte variable
// array of 10 4-byte words
10
7:0
7:0
7:0
7:0
9
7:0
7:0
7:0
7:0
8
7:0
7:0
7:0
7:0
7
7:0
7:0
7:0
7:0
6
7:0
7:0
7:0
7:0
5
7:0
7:0
7:0
7:0
4
7:0
7:0
7:0
7:0
3
7:0
7:0
7:0
7:0
2
7:0
7:0
7:0
7:0
1
7:0
7:0
7:0
7:0
2
1
0
3
Figuring out how to access these arrays can also be confusing…
Remember, start with unpacked dimensions proceeding left to right,
then continue with the packed, proceeding left to right…
bb[9] = bb[8] + bb[7];
bb[10][1:0] = bb [9][3:2] ;
Advanced Verilog
// add 2 4-byte words
// copy 2 MS bytes
// from word 9 to word 10 (LS bytes)
© 2004 Willamette HDL, Inc.
10
7:0
7:0
7:0
7:0
9
7:0
7:0
7:0
7:0
8
7:0
7:0
7
7:0
7:0
6
7:0
7:0
7:0
7:0
7:0
7:0
7:0
7:0
+
10
7:0
7:0
7:0
7:0
9
7:0
7:0
7:0
7:0
8
7:0
7:0
7:0
7:0
80
Notes:
© 2004 Willamette HDL, Inc. &
Slide 80
Array Access – Example 2
7:0
10
9
7
6
5
© 2004 Willamette HDL, Inc.
7:0
7:0 7:0 7:0 7:0 7:0 7:0 7:0 7:0
7:0
7:0
1
0
1
packed
7:0
ed
7:0
2
ck
7:0
3
2
un
pa
3
7:0
7:0
9
7:0 7:0 7:0 7:0 7:0 7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0
7:0
7:0
7:0
7:0
7:0
7:0 7:0
8
7:0
7:0
7:0
Advanced Verilog
7:0
1
10
// set that whole byte
7:0
3
7:0
cc[9] [1] [3] = 8’hff;
7:0
2
NOTE
• All unpacked indices must be provided, every time
• Use packed indices as needed to slice the packed vector
// set the LSB of byte 3 of address 9x1
7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
4
cc[9] [1] [3] [0] = 1’b1;
7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0
7:0 7:0 7:0
8
bit [3:0] [7:0] cc [10:1] [3:1] ; // 2D array (10x3) of 4-byte words
7:0
7:0 7:0 7:0 7:0 7:0 7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0
7:0
7:0
7:0
7:0
9
7:0 7:0 7:0 7:0 7:0 7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0 7:0 7:0
7:0
7:0
7:0
7:0
7:0
7:0
7:0 7:0
8
7:0
10
7:0
7:0
7:0
81
Notes:
© 2004 Willamette HDL, Inc. &
Slide 81
module use_arrays;
bit[3:0][7:0] bb [10:1];
bit[3:0][7:0] cc [10:1][3:1];
Arrays – Using them 2
// This example code 'proves' the previous slide
initial
begin
$display("\n\nPart 1:\n");
$monitorh(bb[9],,bb[8],,bb[7]);
bb[9] = 'hff;
bb[8] = 'h55;
bb[7] = 'h22;
#100 bb[9] = bb[8] + bb[7];
#100 bb[10][1:0] = bb[9][3:2];
#100 $display("\n\nPart 2:\n");
Part 1:
000000ff 00000055 00000022
00000077 00000055 00000022
Part 2:
NOTE
$monitor cannot display the
whole of arrays bb or cc,
but it CAN show the packed
dimensions if you fully
define the unpacked ones!
00000000
33221100
b3221100
aa221100
$monitorh(cc[9][1]);
#100 cc[9][1] = 'h33221100; // initialize 32-bit vector
#100 cc[9][1][3][7] = 1'b1;
// set MSB of MSbyte of 32-bit vector
#100 cc[9][1][3] = 8'haa;
// load MSbyte of 32-bit vector
#100 $display("\n\n");
end
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
82
Notes:
© 2004 Willamette HDL, Inc. &
Slide 82
Arrays – Allowed data types
Unpacked
• Familiar from Verilog, may be ANY Datatype
• Only access a single element at a time
• Although whole arrays may be copied
• One element may be assigned procedurally while
another is assigned continuously
• Specified as a range ( int mem [256:1] )
unpacked
a0
a1
a2
a3
bit a [3:0]; // unpacked array of bits
Packed
• Only bit-level types (reg, wire, logic, bit)
• Access whole array or slice as a vector
• All elements must be assigned identically
• Compatible with $monitor/$display etc.
• Allows arbitrary length integers/arithmetic
[3:0]
bit
packed
bit [3:0] b; // packed array of bits
Synth
2003.12
bit
b3 b2 b1 b0
[3:0]
Advanced Verilog
© 2004 Willamette HDL, Inc.
83
Notes:
© 2004 Willamette HDL, Inc. &
Slide 83
Arrays – Supported Operations
int var=3;
bit[7:0] PA = 8'haa, PB = 8'hbb;
byte UA [7:0] = {default: 'haa}; byte UB [7:0] = {default: 'hbb};
bit[3:0][7:0] MPA;
0
10
20
30
40
50
60
PA: aa, PB: bb,
PA: bb, PB: bb,
PA: ab, PB: ba,
PA: aa, PB: ba,
MPA: 00000000
MPA: deadbeef
MPA: deadbef0
UA[4]:
UA[4]:
UA[4]:
UA[4]:
aa,
bb,
ab,
aa,
Synth
2003.12
UB[4]:
UB[4]:
UB[4]:
UB[4]:
bb
bb
ba
ba
initial begin
$monitor($stime,,"PA: %h, PB: %h, UA[4]: %h, UB[4]: %h",PA,PB,UA[4],UB[4]);
Packed & unpacked arrays support:
#10 PA = PB;
UA = UB;
#10 PA[7:4] = 'hA;
PB[3:0] = PA[7:4];
UA[4][7:4] = 'hA;
UB[4][3:0] = UA[4][7:4];
#10 PA[var -:4] = PA[var+1 +:4];
UA[4][var -:4] = UA[4][var+1 +:4];
#10 $monitor($stime,,"MPA: %h",MPA);
#10 MPA = 32'hdeadbeef;
#10 MPA = MPA+1;
end
Advanced Verilog
Read/write
Read/write of a slice
Read/write of a variable slice
Only packed arrays allow:
Assignment from an integer
Treatment as an integer in an expression
© 2004 Willamette HDL, Inc.
84
Notes:
© 2004 Willamette HDL, Inc. &
Slide 84
module array_ops2;
Arrays and $readmemh/b
HINT
bit[7:0] PA [3:0];
bit[1:0][7:0] PB [3:0]; // two pkd dimensions
$readmemX supports only a
single unpacked dimension
byte UA [7:0];
byte UB [7:0][1:0];
initial
begin
#10 $readmemh("hex.dat",PA);
for(int i=0; i<=3;i++) $display("PA[%0h",i,"]: %b",PA[i]);
#10 $readmemh("hex.dat",PB);
$display("");
for(int i=0; i<=3;i++) $display("PB[%0h",i,"]: %b",PB[i]);
#10 $readmemh("hex.dat",UA);
$display("");
for(int i=0; i<=3;i++) $display("UA[%0h",i,"]: %b",UA[i]);
/* #10 $readmemh("hex.dat",UB); // ILLEGAL, only 1 unpkd dim allowed
for(int i=0; i<=3;i++) $display("UB[",i,"]: ",UB[i]); */
end
endmodule
Advanced Verilog
Synth
2003.12
© 2004 Willamette HDL, Inc.
PA[0]:
PA[1]:
PA[2]:
PA[3]:
00000000
00000001
10101010
11111111
PB[0]:
PB[1]:
PB[2]:
PB[3]:
0000000000000000
0000000000000001
0000000010101010
0000000011111111
UA[0]:
UA[1]:
UA[2]:
UA[3]:
00000000
00000001
10101010
11111111
85
Notes:
© 2004 Willamette HDL, Inc. &
Slide 85
Arrays - Examples
bit [2:0][7:0] m = 24’b0;
// packed 3-byte vector
bit [3:0] [7:0] abc [1:10],
def [1:9] [ 1:3];
// 2 arrays, same packed dimensions
// but different unpacked
typedef bit [1:6] bsix;
bsix [1:10] mine;
// 6-bit packed vector
// 60-bit packed vector
typedef bsix mem_type [0:3];
mem_type bar [0:7];
// unpacked array of 4 ‘bsix’ elements
// unpacked array of 8 ‘mem_type’ elements
Advanced Verilog
© 2004 Willamette HDL, Inc.
86
Notes:
© 2004 Willamette HDL, Inc. &
Slide 86
Array Querying functions
Synth
2003.12
SystemVerilog allows querying of the attributes of an array:
$bits, $left, $right, $low, $high, $increment, $length, $dimensions
$dimensions:
returns the number of dimensions in the array (0 if scalar)
bit [3:0] [7:0] aa;
initial $display( $dimensions(aa) );
// prints “ 2 ”
$bits:
Number of bits in a packed array or struct
initial $display( $bits(aa) );
// prints “ 32 ”
${left|right}:
Bounds of a variable
bit [3:1] [7:4] bb;
bit [3:1] [7:4] cc [2:0];
initial begin
$display( $left(bb) , $right(bb) );
$display( $left(cc) , $right(cc) );
end
Synth
2003.12
// $left => msb, $right => lsb
// prints “ 3
// prints “ 2
1”
0”
${low|high}:
Min|max bounds of a variable
$increment:
returns 1 if $left is greater than or equal to $right
returns –1 if $left is less than $right
$length:
returns number of elements in the dimension ( $high - $low +1 )
Advanced Verilog
© 2004 Willamette HDL, Inc.
// min|max of $left and $right of variable
87
Notes:
© 2004 Willamette HDL, Inc. &
Slide 87
Array Query - quiz
module arrays_quiz;
bit [3:0][7:0] a;
bit
b [3:0];
bit
c [3:0][7:0];
bit
[5:0] d [3:0][31:0];
bit [7:0][5:0] e [3:0][31:0];
initial
begin
$display("bit [3:0][7:0] a;",
$bits(a),, $dimensions(a),, $length(a,1),, $length(a,2));
$display("bit
b [3:0];" ,
$bits(b),, $dimensions(b),, $length(b,1));
$display("bit
c [3:0][7:0]; ", $bits(c),, $dimensions(c),, $length(c,1),, $length(c,2));
$display("bit
[5:0] d [3:0][31:0]; " , $bits(d),, $dimensions(d),, $length(d,1),, $length(d,2),, $length(d,3));
$display("bit [7:0][5:0] e [3:0][31:0];" , $bits(e),, $dimensions(e),, $length(e,1),, $length(e,2),, $length(e,3),, $length(e,4));
end
endmodule
2
1
2
3
4
2
1
2
3
4
4
4
4
4
4
4
4
4
4
4
© 2004 Willamette HDL, Inc.
32
4
32
768
6144
8
32
32
8
6
8
6
Advanced Verilog
32
4
32
768
6144
8
8
32
32
bit [3:0][7:0] a;
bit
b [3:0];
bit
c [3:0][7:0];
bit
[5:0] d [3:0][31:0];
bit [7:0][5:0] d [3:0][31:0];
bit [3:0][7:0] a;
bit
b [3:0];
bit
c [3:0][7:0];
bit
[5:0] d [3:0][31:0];
bit [7:0][5:0] d [3:0][31:0];
6
8
6
88
Notes:
© 2004 Willamette HDL, Inc. &
Slide 88
Structures
Synth
2003.12
From C SystemVerilog has acquired the idea of a structure.
Think of a structure as an object containing members of any type.
struct { bit[7:0] my_byte;
int
my_data;
char
my_char;
} my_struct;
// my_byte, my_data and my_char are "members" of my_struct.
The members can be referenced individually (using the
as a unit.
initial begin
my_struct.my_byte = 8’hab;
my_struct = {0, 99, “A”};
end
Advanced Verilog
. operator) or altogether
Structures may:
• Be packed or unpacked
• Be assigned as a whole
• Pass to/from a function or task as a whole
• Contain arrays
© 2004 Willamette HDL, Inc.
89
Notes:
© 2004 Willamette HDL, Inc. &
Slide 89
Unpacked Structures
Synth
2003.12
By default, structs are unpacked. Their implementation is tool dependant for
maximum flexibility.
a0
a1
Unpacked
a2
a3
struct { bit[1:0]
bit[2:0]
bit[5:0]
bit[8:0]
} u_pkt;
a0;
a1;
a2;
a3;
You may think of an unpacked structure as a logical grouping of different objects,
different types etc.
They may be defined as a type:
typedef struct { byte RED,GRN,BLU;
} RGB;
// Named structure
RGB screen [0:399][0:639];
// declare screen of 640x400 pixels
Advanced Verilog
© 2004 Willamette HDL, Inc.
90
Notes:
© 2004 Willamette HDL, Inc. &
Slide 90
Unpacked structure examples
struct { bit[7:0] opcode;
bit[23:0] addr;
} INSTR;
// Referred to as an anonymous structure
INSTR.addr = 0;
// clear addr in INSTR
typedef struct { bit[7:0] opcode;
bit[23:0] addr;
} instruction; // Named structure
instruction INSTR;
// declare one!
Synthesis Tip (2003.12)
Each element of an unpacked struct must be initialized individually.
Example:
instruction <= 0;
// NOT allowed for synthesis
instruction <= {opcode: 0, addr: 0}; // Synthesizable style
Advanced Verilog
© 2004 Willamette HDL, Inc.
91
Notes:
© 2004 Willamette HDL, Inc. &
Slide 91
Packed Structures
Synth
2003.12
Packed structs are more useful in hardware simulation. As with arrays, packing means
the elements of the structure are arranged in the form of a wide vector.
a0 a1
a2
a3
struct packed {
bit[1:0]a0;
bit[2:0] a1;
bit[5:0] a2;
bit[8:0]a3;
} p_pkt;
A declaration of "packed" offers advantages:
• Easy conversion to bit-vectors
• May be accessed as a whole
• First member specified is most significant
• May be declared as signed for arithmetic
…and responsibilities:
• Only bit-oriented datatypes (bit, logic, reg, net) are allowed.
• Unpacked arrays/structures are NOT allowed
• if any member is 4-state, all members are cast to 4-state
Advanced Verilog
© 2004 Willamette HDL, Inc.
92
Notes:
© 2004 Willamette HDL, Inc. &
Slide 92
Packed Structures - examples
struct packed signed { int a; shortint b; byte c; bit[7:0] d;} pack1; // signed, 2 state
struct packed unsigned { time a; logic[7:0] b;} pack2;
// unsigned, 4 state
typedef struct packed { // Packed struct/unions may also be typedef’d
bit[3:0] f1;
bit[7:0] f2;
bit[11:0] f3;
bit f4;
bit[63:0] f5;
} a_packed_struct;
Advanced Verilog
© 2004 Willamette HDL, Inc.
93
Notes:
© 2004 Willamette HDL, Inc. &
Slide 93
Uses of structures
Structures are the ideal way to encapsulate data "packets“.
•Use as data or control abstraction in architectural models
•Use as abstraction for top-down I/O design
Advanced Verilog
Behavioral:
Pass structures through ports,
as arguments to tasks/functions etc.
Use to refine structure size/content.
RTL:
Break structure apart
& define final I/O.
© 2004 Willamette HDL, Inc.
94
Notes:
© 2004 Willamette HDL, Inc. &
Slide 94
Module Ports
Like Verilog 2001 SystemVerilog allows co-declaration of port AND type
port_direction port_type port_name, port_name ... ;
input wire a, into_here, george;
output reg [8:31] out_bus;
// scalar ports and nets
// vectored port and driving reg
Port declarations can also be made within the parentheses of the module
declaration (also in Verilog 2001).
module MUX2 (output logic [1:0]
input logic [1:0]
input
[1:0]
out,
in_a, in_b,
sel ) ;
Ports may be of ANY SystemVerilog type including events, structs, arrays etc.
typedef struct {
bit isfloat;
union { int i; shortreal f; } n;
} tagged; // named structure
module mh1 (input event e1, input int in1, output tagged out1);
...
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
95
Notes:
© 2004 Willamette HDL, Inc. &
Slide 95
Port Connection Rules
Synth
2003.12
Since ports default to a net type (like Verilog) classic Verilog rules apply.
BUT for ports declared as non-net type (e.g. logic) things simplify a lot. ☺
wire
port type
(SV default)
Like Verilog
net,
reg,
logic
etc.
net
reg,
net,
logic
tri
tri
Any
compatible type
Any
SystemVerilog type
module
non-wire
port type
(e.g. logic)
net
tri
tri
SystemVerilog only
Any
SystemVerilog type
Advanced Verilog
© 2004 Willamette HDL, Inc.
Net type
only
96
Speaker notes:
• Will cover inouts in its own section later
Notes:
© 2004 Willamette HDL, Inc. &
Slide 96
SV types are flexible
Synth
2003.12
For example, “logic” (and reg) are
• can be treated as reg/wire (V2001)
• 4-state (0,1,X,Z)
• Any width ( [MSB:LSB] )
• May be declared as signed or unsigned (default)
NOTE
SV3.0 implied a difference
between reg and logic types.
Under SV3.1 reg and logic
are semantically identical.
VCS follows SV3.1
A variable of any SV type may be driven by any one of the following:
Choose
only one
• Arbitrary number of procedural assignments (like reg in Verilog)
• Single continuous assignment
• Single primitive/module output
Synthesis rules still forbid
assignment from multiple
procedural blocks however
May let the simulator spot
common Verilog problem
of multiple drivers to a node
Advanced Verilog
© 2004 Willamette HDL, Inc.
97
Notes:
© 2004 Willamette HDL, Inc. &
Slide 97
Tasks (new features)
Synth
2003.12
SystemVerilog makes a number of extensions to basic Verilog syntax.
•
•
•
•
•
ANSI-C style formal declarations (plus a new one: ref in SV3.1)
Arguments can be any SystemVerilog type (default is logic)
Default direction is input
task-endtask implies a begin-end structure
return statement can end the task call before endtask
task write_vector( input int data,
logic[11:0] addr);
@(negedge clk);
if (bus_error) return;
// cancel operation if bus_error true
data_bus = data;
addr_bus = addr;
return is supported in tasks but NOT return(value)
write = 1;
@(posedge clk);
#5 write = 0;
endtask
Advanced Verilog
© 2004 Willamette HDL, Inc.
98
Notes:
© 2004 Willamette HDL, Inc. &
Slide 98
Tasks (Recursion)
SystemVerilog makes major extensions to basic Verilog syntax.
• Supports automatic keyword (from Verilog 2001)
• Unlike Verilog, all local variables are dynamically declared.
• Full recursion is supported (automatic variables/arguments stored on stack)
task automatic my_task( input int local_a,
int local_b);
if (local_a == local_b)
identical
begin
my_task(local_a-1,local_b+1);
return;
end
global_a = local_a;
global_b = local_b;
// detect where arguments are
// fix by incrementing/decrementing
// end ‘this’ copy of task
// drive the outputs
endtask
Advanced Verilog
© 2004 Willamette HDL, Inc.
99
Notes:
© 2004 Willamette HDL, Inc. &
Slide 99
Functions
Synth
2003.12
function automatic int factorial (int n);
if (n==0) return(1);
// factorial 0 is 1
else return(factorial(n-1)*n);
endfunction
Extends the basic Verilog function syntax.
•
•
•
•
•
•
•
•
ANSI-C style formal declarations (plus new one: ref in SV3.1)
Arguments can be any SystemVerilog type
Return value can be a structure or union
Default direction is input, but also supports output
Function-endfunction implies a begin-end structure
return statement supported as well as assignment to function name
Supports automatic keyword, allowing recursion just like tasks
Supports void return values
Advanced Verilog
© 2004 Willamette HDL, Inc.
100
Notes:
© 2004 Willamette HDL, Inc. &
Slide 100
Recap!
In this section you learned:
1. R.O.T. #1
For combinatorial logic, use blocking assignments
and no delays.
2. R.O.T. #2
For sequential logic, use non-blocking assignments
and RHS delays if required.
3. How to structure your code for maintain/read-ability.
4. Some gotchas about using tasks.
5. Verilog 2001 File IO
6. New datatypes & port typing in SystemVerilog
7. Improvements to tasks / functions in SystemVerilog
Advanced Verilog
© 2004 Willamette HDL, Inc.
101
Notes:
© 2004 Willamette HDL, Inc. &
Slide 101
This page was intentionally left blank.
Advanced Verilog
© 2004 Willamette HDL, Inc.
102
Notes:
© 2004 Willamette HDL, Inc. &
Slide 102
Day 2
Advanced Verilog
© 2004 Willamette HDL, Inc.
103
Notes:
© 2004 Willamette HDL, Inc. &
Slide 103
Behavioral Modeling
•
•
•
•
Advanced Verilog
What is behavioral modeling?
How to think behaviorally
Behavioral coding style
Write behavioral models
© 2004 Willamette HDL, Inc.
104
Notes:
© 2004 Willamette HDL, Inc. &
Slide 104
What is Behavioral Modeling?
A behavioral model represents a black-box view of the circuit. While it may
correctly model the I/O portion of the design, it implements only the “behavior”
of the internals. So, while it looks to the rest of the simulation like a complete
model, it is actually smaller, faster and easier to write.
There are 3 main application areas for behavioral code:
1. Top-down design
CPU
MEM
2. Testbench Code
3. Stub Models in system testbenches
I/O
Behavioral
Stimulus
Generation
DUT
Response
Checking
Stimulus
Generation
DUT
Response
Checking
RTL
Gate
• First cut at the design
• Coded directly from Func. Spec
• Quick to write
• Helps answer the question
Are you designing the right thing?
Advanced Verilog
Model A Model B Model C
• Faster to write
• Faster execution
• Flexible coding style
© 2004 Willamette HDL, Inc.
Stub A
Model B
Stub C
• Speeds up simulation by
‘removing’ unnecessary detail
• Reusable across design team
105
Notes:
© 2004 Willamette HDL, Inc. &
Slide 105
Question: Consider this simple pipeline
d_1
d_2
d_3
d_out
8
8
d_in
d_out
clk
How would you model its behavior?
Advanced Verilog
© 2004 Willamette HDL, Inc.
106
Notes:
© 2004 Willamette HDL, Inc. &
Slide 106
Exercise I: Now code your solution!
Working directory: PIPE
Purpose: Write a behavioral model.
d_1
d_in
8
d_2
d_3
d_out
8
d_out
Characteristics:
• Posedge clk triggered f/fs
• 5nS clk-output delay
clk
Testbench is “test_pipe.v”
Ports:
d_in, d_out, clk
Advanced Verilog
© 2004 Willamette HDL, Inc.
107
Notes:
© 2004 Willamette HDL, Inc. &
Slide 107
test_pipe.v
test_pipe.v
d_in
clk
8
d_in
clk
d_out
8
pipe
Check
Advanced Verilog
© 2004 Willamette HDL, Inc.
108
Notes:
© 2004 Willamette HDL, Inc. &
Slide 108
at time = 26, d_out = xx which is correct
at time = 66, d_out = xx which is correct
at time = 106, d_out = xx which is correct
at time = 146, d_out = 00 which is correct
at time = 186, d_out = 04 which is correct
at time = 226, d_out = 00 which is correct
at time = 266, d_out = 00 which is correct
at time = 306, d_out = 00 which is correct
at time = 346, d_out = 00 which is correct
at time = 386, d_out = 00 which is correct
at time = 426, d_out = 01 which is correct
at time = 466, d_out = 02 which is correct
at time = 506, d_out = 03 which is correct
at time = 546, d_out = 04 which is correct
at time = 586, d_out = 05 which is correct
at time = 626, d_out = 06 which is correct
at time = 666, d_out = 07 which is correct
at time = 706, d_out = 08 which is correct
at time = 746, d_out = 09 which is correct
at time = 786, d_out = 0a which is correct
at time = 826, d_out = 00 which is correct
at time = 866, d_out = 00 which is correct
at time = 906, d_out = 00 which is correct
at time = 946, d_out = 00 which is correct
at time = 986, d_out = 00 which is correct
at time = 1026, d_out = 01 which is correct
at time = 1066, d_out = 02 which is correct
at time = 1106, d_out = 03 which is correct
at time = 1146, d_out = 00 which is correct
at time = 1186, d_out = 00 which is correct
at time = 1226, d_out = 00 which is correct
at time = 1266, d_out = 00 which is correct
at time = 1306, d_out = 00 which is correct
at time = 1346, d_out = 01 which is correct
Correct output pipe.v
and so on
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
109
Notes:
© 2004 Willamette HDL, Inc. &
Slide 109
Done?
Classify your solution:
Behavioral
RTL
Gate
Advanced Verilog
© 2004 Willamette HDL, Inc.
110
Notes:
© 2004 Willamette HDL, Inc. &
Slide 110
Topic: Thinking behaviorally
TRICK: derive an English-language description of the block and model THAT
You might start by asking yourself the following questions:
Q. What externally visible features must be modeled to capture the behavior?
Q. What "work" is performed?
Q. What external stimulus or "events" trigger a response from the model?
Q. Are there any output "events" which occur?
Q. How to describe the behavior you see:
Procedural (if/endif, assign etc)
State-machine ( case )
etc
Advanced Verilog
© 2004 Willamette HDL, Inc.
111
Notes:
© 2004 Willamette HDL, Inc. &
Slide 111
Lab 3: beh_sram
Working directory: BEH_SRAM
Purpose: Apply new features of SV like UDT’s, structs, new SV port-types.
Instructions:
Write an abstract behavioral model of a syncrhonous sram memory
•
•
•
•
Memory is 1k deep x 32bits wide
2 ports (ip and op) both of type packet.
Testbench writes and reads packets over the 2 ports.
Memory access time is 5ns
Advanced Verilog
© 2004 Willamette HDL, Inc.
beh_sram
ip
op
32bits
clk
mem
1k
array
rw_
112
Notes:
© 2004 Willamette HDL, Inc. &
Slide 112
Lab 3: beh_sram
beh_sram
ip
typedef struct {
logic [9:0] addr;
logic[31:0] data;
} packet;
op
32bits
clk
mem
1k
array
rw_
• Testbench: test_beh_sram.sv ( DO NOT LOOK AT IT! ☺ )
•
•
•
•
Packet definition shown above
sram operates on posedge of clk
rw_ signal is hi read, lo write
Memory access time is 5ns
Question: Where do you declare the packet typedef?
Think about it, experiment!
Advanced Verilog
© 2004 Willamette HDL, Inc.
113
Notes:
© 2004 Willamette HDL, Inc. &
Slide 113
Lab 3 – beh_sram (expected output)
40
80
146
186
200
266
Writing 0000000a
Writing 00000002
Read successful:
Read successful:
Writing 0000aaaa
Read successful:
to address 005
to address 001
0000000a from address 005
00000002 from address 001
to address 1ff
0000aaaa from address 1ff
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
114
Notes:
© 2004 Willamette HDL, Inc. &
Slide 114
Topic:
Scoping
module name
instance names
a
d
b
mega
flop
c
giga
e
module flop
....
reg float;
// local reg
....
endmodule
module names
Verilog supports hierarchical paths:
module_name.instance_name.instance_name.X
Example - path to reg float : a.d.e.float
Note: From module giga, the path can be shortened to: e.float
Uses:
• Test fixtures to monitor variables etc. within modules
• Redefinition of parameters
• defparam <path>.<parameter_name> = <value>;
• Behavioral modeling
• From the gui…
Advanced Verilog
© 2004 Willamette HDL, Inc.
115
Notes:
© 2004 Willamette HDL, Inc. &
Slide 115
Topic:
Named Events
Declaration- keyword: event
event request_blues;
event sleeping_in_class;
“Has no duration and carries no value!”
Made to occur only from a procedural block:
Trigger: -> operator
-> request_blues;
-> sleeping_in_class;
Used by event control (@)
always @ (request_blues)
play_blues_cd;
always @ (sleeping_in_class)
Think of a
flashing light!
teacher_throw_eraser;
Advanced Verilog
© 2004 Willamette HDL, Inc.
116
Notes:
© 2004 Willamette HDL, Inc. &
Slide 116
Named Events Example /* example program for named events */
module cannon;
cannon.v
/* declarations */
event fire_the_cannon; //event declaration
event kaboom, minute_elapsed; //can declare more than
// one event at a time
event light_fuse, load_cannon;
reg [7:0] enemy_count;
initial //initializations and generation of minute_elapsed
begin
enemy_count = 0; //init the enemy count to zero
forever #60 -> minute_elapsed; // every 60 time steps trigger event
end
/* code for the scout */
always @ (minute_elapsed) //every minute check for the enemy
begin
if (enemy_count > 0) //is there any enemy there?
begin
$display ($time,,"spotted %0d of the enemy",enemy_count);
-> fire_the_cannon; // signal the cannon soldier to fire
end
end
/* code for the cannon soldier */
always @ (fire_the_cannon) // wait for signal to fire the cannon
begin
-> light_fuse; //light the fuse to the cannon
@ (kaboom) //wait for the cannon to fire
#5 -> load_cannon; // reload the cannon
end
Advanced Verilog
/* code for the cannon */
always @ (light_fuse) // wait for fuse to be lit
begin
#5 -> kaboom; // cannon fires
$display ($time,,"fired the cannon");
@ (load_cannon); // wait for cannon reload
end
initial // the test sequence - the enemy appears
begin
#100 enemy_count = 5;
@ (kaboom) enemy_count = 0;
#60 enemy_count = 25;
@ (kaboom) enemy_count = 15;
//cannon gets 10 at a time
@ (kaboom) enemy_count = 5;
@ (kaboom) enemy_count = 0;
#60 enemy_count = 5;
@ (kaboom) enemy_count = 0;
#100 $stop;
end
endmodule
© 2004 Willamette HDL, Inc.
117
Notes:
© 2004 Willamette HDL, Inc. &
Slide 117
MANGLED 10 time
steps to report. Count,
display bag # and
“Mangled!” after each.
Exercise – Airplane baggage
SEA 10 time steps to
handle the bag. Count,
display bag # and “SEA”
after each.
DFW 5 time steps to
handle the bag. Count,
display bag # and
“DFW” after each.
Working directory: NAMED EVENTS
1Kx8
Purpose: Learn to use named events
Syntax for loading mem
$readmemh(“luggage.dat",flight98);
Unload one bag at a
time onto cart.
Look at cart every time a
new bag is put on it.
Check the label for
connecting destination &
signal the correct worker.
LAX 10 time steps to
handle the bag. Count,
display bag # and “LAX”
after each.
When flight is empty
display total # of bags
for each connecting
destination.
cart
Bag destination
ignore
7
-other-
© 2004 Willamette HDL, Inc.
7
label
3
label
4’b0000
4’b0001
4’b0010
4’b0011
SFO 5 time steps to
handle the bag. Count,
display box # and “SFO”
after each.
Advanced Verilog
flight98
0
0
destination
SEA
DFW
LAX
SFO
mangled
118
Notes:
© 2004 Willamette HDL, Inc. &
Slide 118
bag
bag
bag
bag
bag
bag
bag
bag
bag
bag
bag
…
number
number
number
number
number
number
number
number
number
number
number
0 -> SEA
1 -> DFW
2 -> DFW
3 -> LAX
4 -> LAX
5 -> SFO
6 -> SFO
7 -> SFO
8 is mangled!
9 is mangled!
10 is mangled!
Correct Output
Airplane baggage
problem
With a whole bunch in between ...
…
bag
bag
bag
bag
bag
#
#
#
#
#
number
number
number
number
number
of
of
of
of
of
1019
1020
1021
1022
1023
->
->
is
is
is
SEA bags
DFW bags
LAX bags
SFO bags
mangled bags
SFO
LAX
mangled!
mangled!
mangled!
=
=
=
=
=
202
304
205
206
107
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
119
Notes:
© 2004 Willamette HDL, Inc. &
Slide 119
Test application - Bus Monitors
PC
Card
PC
Socket
Protocol
Checker
module test(..);
...
#1;
// Why ?
-> PC1.check_read;
do_read_test(..);
-> PC1.check_dma;
do_dma_test(..);
…
protocol_check PC1 (…);
endmodule
module protocol_check(..);
event check_read, check_dma;
...
always @ check_read;
wait (read_strobe);
if (!read_rdy) error = `true;
...
...
always @ check_dma;
wait (dma_strobe);
...
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
120
Notes:
© 2004 Willamette HDL, Inc. &
Slide 120
Test Application - Structured Testing
module test(..);
...
initial
begin
#5 -> load_data;
do_test(..);
-> load_data;
do_test(..);
end
...
// Why the #5?
initial
begin
@ (load_data)
$readmemh(data1.hex, test_mem);
@ (load_data)
$readmemh(data2.hex, test_mem);
@ (load_data)
$readmemh(data3.hex, test_mem);
end
Advantage…
Gathers $readmemh tasks into
one place for easy maintenance.
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
121
Notes:
© 2004 Willamette HDL, Inc. &
Slide 121
Behavioral State Machines
Advanced Verilog
© 2004 Willamette HDL, Inc.
122
Notes:
© 2004 Willamette HDL, Inc. &
Slide 122
State Machine style
You just completed the Airplane baggage simulation!
Ba
d
Ba ide
d a!
Ba ide
d a!
id
ea
!
You might be tempted to see this as a State
Machine model (One state per independent
always block & named events to switch from one
to the other).
1. Not supported by Synthesis.
2. No help when migrating to RTL.
Advanced Verilog
© 2004 Willamette HDL, Inc.
123
Notes:
© 2004 Willamette HDL, Inc. &
Slide 123
Behavioral State Machines
Characteristics:
No state register - states are implied
Initial or always block with implied state
boundaries
No clocks
Structure:
Example state separators:
Branches in case statements, if,
wait, while, for, @
Advanced Verilog
© 2004 Willamette HDL, Inc.
124
Notes:
© 2004 Willamette HDL, Inc. &
Slide 124
An example - Memory
/* interface state machine */
initial
@ cpl2.reset
begin
initialize; // task that resets queues, memory and registers
forever
begin
wait (!q_empty(in_q,q_status));
exam_q(in_q, op_code, addr, data_block, q_status);
/* get item from queue ( without removing it ) */
case( op_code[31:28])
4'b011x: /* it is a read request */
if(!q_full(out_q))
/* check to see if out queue is not full */
begin
$display ("memory received a Block read request",$time);
ret_data; /* task that moves data from memory to out queue */
read_q(in_q,q_status); /* remove read from queue */
end
4'b001x: /* it is a block write */
begin
$display ("memory received a Block data write", $time);
#40 write_mem; /* task that moves data into memory */
read_q(in_q,q_status); /* remove write from queue */
end
default /* bad opcode */
begin
$display ("memory received a non valid opcode",$time);
$display ("opcode = %h", op_code[31:28]);
$display ("address = %h", addr);
$stop;
end
endcase
end
end
Advanced Verilog
out_q
memory
sm
in_q
@ reset
wait
!empty
read
write
Case is branch
selector
bad op
If is branch
selector
© 2004 Willamette HDL, Inc.
do read
125
Notes:
© 2004 Willamette HDL, Inc. &
Slide 125
Another Example - Arbiter
/* arbitration logic state machine */
initial
Note: Code snippet only,
@ cpl2.reset
this will not compile
begin
initialize;
forever
begin
wait (req_reg) /* wait for a bit to be set in req reg */
current_grant_prior = 0; /* set to no priority */
req reg
for (temp = 1; temp < 9; temp = temp + 1)
begin
grant reg
last_grant = last_grant+1; /* round robin */
if (last_grant == 8) /* check for wrap */
last_grant = 0;
busy reg
if (req_reg[last_grant]) /* is the bit set? */
if (prior_reg[last_grant] > current_grant_prior)
/* see if this request wins over the current winner */
set_grant;
end
#1 grant_reg[current_grant] = 1; /* set grant bit in grant reg */
last_grant = current_grant; /* set last_grant for next arb */
last_grant_prior = current_grant_prior; /* set last_grant_prior
* for next arb */
wait (busy) /* wait for busy to be set by grantee */
wait (!busy) /* wait for grantee to be done */
grant_reg = 0; /* clear grant */
end
end
Advanced Verilog
© 2004 Willamette HDL, Inc.
@ reset
wait
request
sm
set grant
wait
busy
wait not
busy
126
Notes:
© 2004 Willamette HDL, Inc. &
Slide 126
Behavioral SM Exercise
Working directory: FSM
Purpose: Model a behavioral Finite State Machine
1. In_reg is 32-bits wide
2. “mem” is 32 bits wide, 1k deep
3. Commands, addresses and
data are passed to the
mem_controller
via the in_reg
4. It is the job of your SM to
keep things straight and to
perform memory accesses
for the “outside world”
Test fixture is test_sm_behav.v
Test
Fixture
addr
32x1k
mem
in_reg
outof
sm
5. There are 4 instructions:
wt_wd – Single word write
wt_blk – 4-word block write
rd_wd – single word read
NOP – do-nothing
Advanced Verilog
© 2004 Willamette HDL, Inc.
in_reg Explanation
wt_wd
- addr
- data
wt_blk
- addr
- data
- data
- data
- data
rd_wd
- addr
- nop
- op_word
- op_word
- op_word
op_word
31 28
op
0000
0001
0010
0011
0100
0101
011x
1xxx
0
nop
nop
wt_wd
wt_blk
rd_wd
illegal
illegal
illegal
127
Notes:
© 2004 Willamette HDL, Inc. &
Slide 127
Sample Instruction Flow
in_reg
wt_blk
rd_wd
op
code
Data Data Data Data Addr
wt_wd
op
code
nop
Addr
op
code
Data Addr
addr
addr+1
addr+2
addr+3
Time
write_in_reg
write_outof
Advanced Verilog
© 2004 Willamette HDL, Inc.
128
Notes:
© 2004 Willamette HDL, Inc. &
Slide 128
* Test fixture for behavioral level state machines */
module test_sm_behav;
reg [31:0] into, outof, exp_outof;
reg clk;
event write_in_reg;
event write_outof, wait_for_outof;
/* nop */
task nop;
begin
# 5 sm_behav_0.in_reg = {4'b0000,28'h0}; // op_word
-> write_in_reg; // trigger the event
end
endtask
/* illegal op */
task ill_op;
begin
# 5 sm_behav_0.in_reg = {4'b0101,28'h0}; // op_word
-> write_in_reg; // trigger the event
end
endtask
/* the rd_wd op */
task rd_wd;
input [31:0] addr, data;
begin
#5 sm_behav_0.in_reg = {4'b0100,28'h0}; // op_word
-> write_in_reg; // trigger the event
@ (posedge clk)
#5 sm_behav_0.in_reg = addr;
exp_outof = data;
-> wait_for_outof;
-> write_in_reg; // trigger the event
@ (posedge clk)
#5 sm_behav_0.in_reg = 0; // nop
-> write_in_reg; // trigger the event
end
endtask
test_sm_behav.v
/* the wt_blk op */
task wt_blk;
input [31:0] addr,data;
begin
#5 sm_behav_0.in_reg = {4'b0011,28'h0}; // op_word
-> write_in_reg; // trigger the event
@ (posedge clk)
#5 sm_behav_0.in_reg = addr; // send address
-> write_in_reg; // trigger the event
repeat (4)
begin
@ (posedge clk)
#5 sm_behav_0.in_reg = data; // send data
-> write_in_reg; // trigger the event
data = data +1; // change the data word
end
end
endtask
/* the wt_wd op */
task wt_wd;
input [31:0] addr,data;
begin
#5 sm_behav_0.in_reg = {4'b0010,28'h0}; // op_word
-> write_in_reg; // trigger the event
#20 sm_behav_0.in_reg = addr;
-> write_in_reg; // trigger the event
#20 sm_behav_0.in_reg = data;
-> write_in_reg; // trigger the event
end
endtask
initial
into = 0; // set to nop to start off
/* tests */
integer i;
initial
begin
repeat(3) @ (posedge clk); // wait for 3 clocks
@ (posedge clk) nop;
@ (posedge clk) wt_wd('h100,'haa);
@ (posedge clk) wt_wd('h30,'hbb);
@ (posedge clk) wt_blk('h40,'ha10);
@ (posedge clk) rd_wd('h100,'haa);
@ (posedge clk) rd_wd('h30,'hbb);
@ (posedge clk) rd_wd('h40,'ha10);
@ (posedge clk) rd_wd('h41,'ha11);
@ (posedge clk) rd_wd('h42,'ha12);
@ (posedge clk) rd_wd('h43,'ha13);
@ (posedge clk) ill_op;
@ (posedge clk) nop;
#100 $stop;
end
always @ (write_outof)
$display($time,,"outof reg = %h",outof);
// instantiate sm module
sm_behav sm_behav_0();
always@ (wait_for_outof)
begin
$display("TB: waiting for write_outof in response to read request");
@ (write_outof)
if( exp_outof !== outof)
$display(" %0t TB: Read error: expecting %0h, received %0h \n", $stime, exp_outof, outof);
else
$display(" %0t TB: Read OK: expecting %0h, received %0h \n", $stime, exp_outof, outof);
end
Advanced Verilog
/* the clock */
initial
begin
clk = 0;
forever
#10 clk = !clk;
end
© 2004 Willamette HDL, Inc.
endmodule
129
Notes:
© 2004 Willamette HDL, Inc. &
Slide 129
TB: waiting for write_outof in response to read request
360 TB: Read OK: expecting aa, received aa
Expected
output
TB: waiting for write_outof in response to read request
420 TB: Read OK: expecting bb, received bb
TB: waiting for write_outof in response to read request
480 TB: Read OK: expecting a10, received a10
TB: waiting for write_outof in response to read request
540 TB: Read OK: expecting a11, received a11
TB: waiting for write_outof in response to read request
600 TB: Read OK: expecting a12, received a12
TB: waiting for write_outof in response to read request
660 TB: Read OK: expecting a13, received a13
695 illegal op received
Note: your timing may be slightly different - Why?
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
130
Notes:
© 2004 Willamette HDL, Inc. &
Slide 130
Mixed-Behavioral Models
Clocked interface - Event driven back end.
Why would you want to do this? (HINT: title of this slide)
Exercise
1. Study new block diagram below.
2. Modify code from last exercise.
3. Add a new clock-driven shell (wrapper) around sm_behav.
4. Test fixture is test_sm_func.v.
sm_func
In
Out
32
sm_behav
32
Clk
Advanced Verilog
New
clk<-> event
Xlation
Logic
Existing
Behavioral SM
model
(event driven)
Clock-driven shell
© 2004 Willamette HDL, Inc.
131
Notes:
© 2004 Willamette HDL, Inc. &
Slide 131
into
in_reg
Exercise
Test fixture is test_sm_func.v
32
wt_wd
wt_blk
addr
32x1k
mem
I/F registers:
tpd(clk-o/p) = 5nS
outof
rd_wd
outof
32
op_word
sm
31 28
op
0000
0001
0010
0011
0100
0101
011x
1xxx
clk
Test
Fixture
Advanced Verilog
- op_word
- addr
- data
- op_word
- addr
- data
- data
- data
- data
- op_word
- addr
- nop
© 2004 Willamette HDL, Inc.
0
nop
nop
wt_wd
wt_blk
rd_wd
illegal
illegal
illegal
132
Notes:
© 2004 Willamette HDL, Inc. &
Slide 132
Sample Instruction Flow
(modified)
in_reg
wt_blk
rd_wd
op
code
Data Data Data Data Addr
wt_wd
op
op
code code
op
code
nop
Addr
Data Addr
Time
Advanced Verilog
© 2004 Willamette HDL, Inc.
133
Notes:
© 2004 Willamette HDL, Inc. &
Slide 133
/*
Test fixture for sm_func
*/
module test_sm_func;
reg [31:0] into, out of, exp_outof;
reg clk;
wire [31:0] out_wire;
event wait_for_out of;
/* nop */
task nop;
# 5 into = {4'b0000,28'h0}; // op_word
endtask
/* the wt_wd op */
task wt_wd;
input [31:0] addr,data;
begin
#5 into = {4'b0010,28'h0}; // op_word
@ (posedge clk)
#5 into = addr;
@ (posedge clk)
#5 into = data;
end
endtask
/* the wt_blk op */
task wt_blk;
input [31:0] addr,data;
begin
#5 into = {4'b0011,28'h0}; // op_word
@ (posedge clk)
#5 into = addr; // send address
repeat (4)
begin
@ (posedge clk)
#5 into = data; // send data
data = data +1;// change data word
end
end
endtask
Advanced Verilog
/* the rd_wd op */
task rd_wd;
input [31:0] addr, data;
begin
#5 into = {4'b0100,28'h0}; // op_word
@ (posedge clk)
#5 into = addr;
@ (posedge clk)
#5 into = 0; // nop
exp_outof = data;
-> wait_for_outof; // spin-off routine!
end
endtask
/* illegal op */
task ill_op;
#5 into = {4'b0101,28'h0}; // op word
endtask
initial
into = 0; // set to nop to start off
/* the clock */
initial
begin
clk = 0;
forever
#10 clk = !clk;
end
test_sm_func.v
always @(posedge clk)
outof = #5 out_wire // put output in register
//always @ (outof) // any change of outof
// $display ($time,,"outof = %h",outof);
/* tests */
initial
begin
repeat(3) @ (posedge clk); // wait for 3 clocks
@ (posedge clk) nop;
@ (posedge clk) wt_wd('h100,'haa);
@ (posedge clk) wt_wd('h30,'hbb);
@ (posedge clk) wt_blk('h40,'ha10);
@ (posedge clk) rd_wd('h100,'haa);
@ (posedge clk) rd_wd('h30,'hbb);
@ (posedge clk) rd_wd('h40,'ha10);
@ (posedge clk) rd_wd('h41,'ha11);
@ (posedge clk) rd_wd('h42,'ha12);
@ (posedge clk) rd_wd('h43,'ha13);
@ (posedge clk) ill_op;
@ (posedge clk) nop;
#100 $stop;
end
// instantiate sm module
sm_func sm_func_0(into,out_wire,clk);
// check outof is correct
always@ (wait_for_outof)
endmodule
begin
repeat(3) @(negedge clk);
if( exp_outof !== outof)
$display(" %0t TB: Read error: expecting %0h, received %0h \n", $stime, exp_outof, outof);
else
$display(" %0t TB: Read OK: expecting %0h, received %0h \n", $stime, exp_outof, outof);
end
© 2004 Willamette HDL, Inc.
134
Notes:
© 2004 Willamette HDL, Inc. &
Slide 134
Sample output
420 TB: Read OK: expecting aa, received aa
480 TB: Read OK: expecting bb, received bb
540 TB: Read OK: expecting a10, received a10
600 TB: Read OK: expecting a11, received a11
660 TB: Read OK: expecting a12, received a12
716 illegal op(5) received
720 TB: Read OK: expecting a13, received a13
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
135
Notes:
© 2004 Willamette HDL, Inc. &
Slide 135
Bus Functional Models
Bus Functionality is an extremely useful modeling technique which allows us to create
models of complex programmable devices like controllers and processors without
having to implement 100% of the functionality.
Basically, a BFM is a behavioral model of the outer-shell of a device. It is capable of
reproducing 100% of the bus activity but is controlled internally by a simple sequencer
which executes “pseudo-code” provided by the designer.
BFM’s are ideal for early simulations because they can run (and help debug) in designs
with netlist errors or other problems which would prevent full-function simulation.
As you will see in the next exercise, BFM’s usually “drive” the simulation, not the TB.
CPU model
address
Pseudocode
script
script
engine
data
irq[2:0]
To make a BFM of this CPU, you need:
•
•
•
•
Module of CPU shell with full pinout
Task for each bus-cycle (e.g. write, read, nop, dma)
Script engine (clk driven)
External script in pseudo-code
clk
Advanced Verilog
© 2004 Willamette HDL, Inc.
136
Notes:
© 2004 Willamette HDL, Inc. &
Slide 136
BFM example
Example of Verilog 2001 file extensions to read commands from a script.
//Example script file to be read by this model
//
// command addr
data
//
//
read
9
0
//
write
300a deadbeef
//
read
2FF xxxxxxxx
//
nop
`define NULL 0
module script_reader;
integer file, r;
reg [5*8:1] command;
reg [31:0] addr, data;
NOTE
All references to
the command
field are 5-digit
initial
begin : file_block
file = $fopen("script.txt", "r");
if (file == `NULL)
disable file_block;
r = 1;
while(r !== 0)
begin
command = " ";
r = $fscanf(file, " %s %h %h \n", command, addr, data);
case (command)
" read":
$display("READ mem[%h], expect = %h", addr, data);
"write":
$display("WRITE mem[%h] = %h", addr, data);
" nop":
$display("NOP");
default:
$display("Unknown command '%0s'", command);
endcase
end // while r !== 0
$fclose(file);
$finish;
end // initial
endmodule // script_reader
Advanced Verilog
© 2004 Willamette HDL, Inc.
137
Notes:
© 2004 Willamette HDL, Inc. &
Slide 137
Recap!
In this section you learned:
1. How to approach writing a behavioral model.
2. How and when to use Named Events.
3. To write several example behavioral models
including a FIFO & an FSM. How to make a
behavioral model work with models of lower
abstraction levels (RTL / gate) was also discussed.
4. How to write a Bus Functional Model.
Advanced Verilog
© 2004 Willamette HDL, Inc.
138
Notes:
© 2004 Willamette HDL, Inc. &
Slide 138
Assertion Based Verification
What is ABV
Types of Assertions
Accellera
Analysis
Formal
Advanced Verilog
© 2004 Willamette HDL, Inc.
139
Notes:
© 2004 Willamette HDL, Inc. &
Slide 139
The Challenge
98
94
96
19
19
19
90
88
86
92
19
19
19
84
Effort required to verify these new
designs doubles every 6 to 9 months
19
•
82
Verification productivity has not kept
pace
19
•
160
140
120
100
80
60
40
20
0
80
Design productivity has risen tenfold
since 1990
19
•
Hardware De sign Productivity
Gates Per Day
Designs continue to grow in accordance
with Moore’s law
19
•
Ye ar
Half of all chips today
require 1 or more re-spins
~75% of all re-spins are due
to functional errors.
Advanced Verilog
© 2004 Willamette HDL, Inc.
140
Notes:
© 2004 Willamette HDL, Inc. &
Slide 140
Traditional Testbench Structure
SYSTEM_TB
CPU
Peripheral
TB1
CPU
Peripheral
TB2
•
Traditional testbenches treat the DUT as a black box. Stimulus
is applied and results are measured from external pins only.
•
OK for simple designs.
•
For complex designs:
•
It is computationally impractical to test all potential input
sequences
•
What if an internal error occurred, but the design still had a
proper output response?
•
How do you know when you are done?
Advanced Verilog
© 2004 Willamette HDL, Inc.
141
Notes:
© 2004 Willamette HDL, Inc. &
Slide 141
Assertion-Based Verification
•
The core of design verification is to ensure that a design
implementation behaves according to a given specification
•
Typically, the specification consists of a list of natural language (i.e.
not machine-readable) assertions, each of which must be verified
•
An assertion is a statement about a design's intended behavior
which must be verified
•
•
That statement itself is called a property of the design
SV assertions may appear in a number of places in your system:
•
Inside the design (perhaps the DUT module itself)
•
In an interface or program block
•
$root
•
Procedurally, within an initial/always block
Advanced Verilog
© 2004 Willamette HDL, Inc.
142
Notes:
© 2004 Willamette HDL, Inc. &
Slide 142
Types of Assertions
System Bus
(e.g. PCI)
I/O Assertions
uP Core
FIFO
Arbiter
Structural Assertions
Protocol Assertions
Advanced Verilog
© 2004 Willamette HDL, Inc.
143
Notes:
© 2004 Willamette HDL, Inc. &
Slide 143
Types of Assertions
• Structural Assertions:
• Intended internal functionality of blocks
Designers can catch errors more quickly
• I/O Assertions:
• Input combinational relationships (e.g. read_en, write_en)
• Basic sequential behavior (e.g. reset, handshake)
Ensures block is being used correctly in external context
• Protocol Assertions:
• Higher-level than interface
• Transaction descriptions
• Required responses
Ensures conformance to standards
Advanced Verilog
© 2004 Willamette HDL, Inc.
144
Notes:
© 2004 Willamette HDL, Inc. &
Slide 144
Examples of Assertions
•
•
•
I/O Assertions:
•
"The read and write enables are mutually exclusive"
•
"Reset must be held low for three rising edges of the clock"
•
"A grant never occurs without a request"
•
"A request must always be acknowledged"
Structural Assertions:
•
"The state vector is one-hot"
•
"When opcode is READ_WD, state goes from IDLE to S1 to S2,
then back to IDLE"
•
"An illegal state is never reached"
Protocol Assertions:
•
"If a master sets the transfer type to BUSY during a burst cycle,
then in the next cycle, the slave must assert HREADY and set
HRESP to 'OKAY' "
Advanced Verilog
© 2004 Willamette HDL, Inc.
145
Notes:
© 2004 Willamette HDL, Inc. &
Slide 145
White-box Monitoring
Assertions increase observability of errors in the DUT
"Open"
the black box and observe internal behavior
Add extra code inside DUT that monitors for problems
Do
not have to wait for error to propagate to external pins
Error
detection closer in both time and physical proximity to
error source
Monitor
Advanced Verilog
`ifdef MONITOR_ON
always @(state) begin
if ((state & (state - 1)) != 2'b0) begin
$display("STATE_NOT_ONE_HOT,%t",$time);
end
end
`endif
© 2004 Willamette HDL, Inc.
146
Notes:
© 2004 Willamette HDL, Inc. &
Slide 146
Verilog checkers
•
Verilog does not have an assertion construct
•
Instead, checks can be coded as procedural blocks
`ifdef MONITOR_ON
always @(a or b) begin
if (!(a^b)) begin)
$display("Error: a and b must be inverted");
$finish;
end
end
`endif
•
These blocks can be single-event or temporal, but are not very
reusable
•
OVL is a set of predefined, standard tests implemented as
modules for ease of reuse
•
OVL checks are concurrent, not embedded in procedural
code
Advanced Verilog
© 2004 Willamette HDL, Inc.
147
Notes:
© 2004 Willamette HDL, Inc. &
Slide 147
OVL Checker Library
OVL is a set of predefined, standard tests
implemented as modules for ease of reuse.
•
OVL checks are concurrent, not embedded in
procedural code.
Advanced Verilog
© 2004 Willamette HDL, Inc.
148
Notes:
© 2004 Willamette HDL, Inc. &
Slide 148
Property Languages: Sugar,
ForSpec, CBV
•
These languages come from theoretical research into
formal verification and internal customer tools (IBM,
Intel, Motorola)
•
They are intended to declare design properties that are
verified by formal (i.e. static) methods
•
They provide a concise and easy syntax for specifying
single-event and temporal properties
assert always req -> next (!req until ack);
•
Whenever req is asserted, it is de-asserted in the next
cycle and continues so until signal ack is asserted
Advanced Verilog
© 2004 Willamette HDL, Inc.
149
Notes:
© 2004 Willamette HDL, Inc. &
Slide 149
The Accellera Standardization Effort
•
Accellera standardized OVL in 2002 for embedded
RTL assertions
•
The formal verification working group selected the
Sugar proposal as its base for a standard language
in 2002
•
Accellera approved and released it as PSL (Property
Specification Language) in early 2003, and has
received tremendous vendor support
•
SystemVerilog 3.1 will support a "unified" assertion
syntax
Advanced Verilog
© 2004 Willamette HDL, Inc.
150
Notes:
© 2004 Willamette HDL, Inc. &
Slide 150
Does ABV Really Work?
Assertion Monitors
34%
Cache Coherency Checkers
Register File Trace Compare
Memory State Compare
End-of-Run State Compare
PC Trace Compare
Self-Checking Test
Simulation Output Inspection
Simulation hang
Other
9%
8%
7%
6%
4%
11%
7%
6%
8%
Assertions in real designs:
34% of all bugs found were identified
by assertions on DEC Alpha 21164 project
[Kantrowitz and Noack DAC 1996]
25% of all bugs were found were identified by
assertions on DEC Alpha 21264 project.
[Taylor et at.DAC 1998]
Kantrowitz and Noack [DAC 1996]
85% of all bugs were found using
over 4000 assertions on HP
[Foster and Coelho HDLCon 2000]
Assertion Monitors
25%
Register Miscompare
Simulation "No Progress”
PC Miscompare
Memory State Miscompare
Manual Inspection
Self-Checking Test
Cache Coherency Check
SAVES Check
22%
15%
14%
8%
6%
5%
3%
2%
10,000 assertions in Cisco RTL project
[Sean Smith 2002]
Thousands of assertions in Intel Pentium project
[Bentley 2001]
Taylor et al. [DAC 1998]
Advanced Verilog
© 2004 Willamette HDL, Inc.
151
Notes:
© 2004 Willamette HDL, Inc. &
Slide 151
This page was intentionally left blank.
Advanced Verilog
© 2004 Willamette HDL, Inc.
152
Notes:
© 2004 Willamette HDL, Inc. &
Slide 152
Day 3
Advanced Verilog
© 2004 Willamette HDL, Inc.
153
Notes:
© 2004 Willamette HDL, Inc. &
Slide 153
SV Assertions
SVA Intro example
VCS/Virsim and assertions
Immediate / Concurrent
Boolean
Sequences
Repetition etc.
Property block
Sequence Implication
Assert/Cover blocks
SVA Checker Library
Advanced Verilog
© 2004 Willamette HDL, Inc.
154
Notes:
© 2004 Willamette HDL, Inc. &
Slide 154
Assertions – Immediate / Concurrent
7.1
Immediate
• Simulation use primarily
• Execute under simulator control inside a procedural block
Imm. assertion is triggered
in procedural code/time
always @( posedge clk )
traf_light : assert ( green && !red && !yellow & go );
Failure triggers a default message
7.1
Partial support
Concurrent
• Usable by other tools as well ( e.g. formal verification )
• Clocked/sampled paradigm
• Distinguishable by the keyword property within assert or
cover verification statements
Conc. assertions may be
triggered in various ways
(including procedural code),
but time is spec'd internally
and may include sequential
checks over time
Advanced Verilog
traf_light : assert property ( @ ( posedge clk )
( green && !red && !yellow & go );
do_traf_prop : assert property ( traf_light );
© 2004 Willamette HDL, Inc.
155
Notes:
© 2004 Willamette HDL, Inc. &
Slide 155
Immediate Assertions
7.1
Tested when the assert statement is executed in procedural code.
Pass statements not yet supported
in VCS 7.1
time t;
7.1
always @( posedge clk )
if ( state == REQ )
req_assert : assert ( req1 || req2 ) $display( "%m OK" );
else
Notice if-else style… where if is implicit.
begin
else is also optional in this context
Notice optional req_assert label…
t = $time;
… and the use of %m to implicitly
#5 $display( "%m failed at time %0t",t );
insert that label in messages
end
NOTE
assert statements resolve X and Z expression values
much like if-else statements… they will fail on 0, X or Z
Advanced Verilog
© 2004 Willamette HDL, Inc.
156
Notes:
© 2004 Willamette HDL, Inc. &
Slide 156
Severity system tasks
7.1
Several new system tasks provide control over severity of a failing assertion.
These new tasks all follow $display symantics.
$fatal()
$error()
$warning()
$info()
- run-time fatal, terminate simulation
- run-time error
- run-time warning, varies by tool
- no severity implied, just informative
$display() - like $info, no severity implied
By default, an assertion (with no severity task) that fails triggers $error.
Advanced Verilog
© 2004 Willamette HDL, Inc.
157
Notes:
© 2004 Willamette HDL, Inc. &
Slide 157
Concurrent Assertions
7.1
Partial support
Concurrent assert statements describe behavior over time.
• Clock-based (clock may be user-defined but glitchless!!!)
• Structured for simplicity, flexibility & reuse
4
Verification Statements
assert , cover, bind
3
Property Declarations
property , disable iff, not, |->, |=>
2
1
Sequence Regular
Expressions
Boolean Expressions
Advanced Verilog
7.1
7.1
7.1
7.1
and, or, intersect, first_match, <time_ shift>,
*<repeat>, within, throughout, $past, $stable, $rose,
$fell, sequence
7.1
7.1
7.1
<Verilog expr, excl. +=, ++, -- etc.>, 7.1
System functions: $countones, $inset, $isunknown etc.
ended, matched
© 2004 Willamette HDL, Inc.
158
Notes:
© 2004 Willamette HDL, Inc. &
Slide 158
Concurrent SVA Example – Minilab 1
module sva_ex;
logic [2:0] cnt;
logic clk;
Boolean expressions in
linear order over time
initial
begin
clk = 0; cnt = 0;
forever #20 clk = !clk;
end
initial
begin
wait(cnt == 2) cnt = 4;
#240 $stop;
end
always @(posedge clk)
cnt = cnt +1;
Named behavior of
the design
sequence s_count3;
(cnt == 3'h1) ##1 (cnt == 3'h2) ##1 (cnt == 3'h3);
endsequence
Sampling clock
property p_count3;
@(posedge clk) (cnt == 3'h0) |=> s_count3;
endproperty
Verification
directives
assert_count3: assert property (p_count3);
cover_count3: cover property (p_count3);
endmodule
Working directory: sv_assertions/example
Purpose: See and run a “complete” assertion example
Do:
vcs –RI +sysvcs sva_ex.sv
Advanced Verilog
© 2004 Willamette HDL, Inc.
159
Notes:
© 2004 Willamette HDL, Inc. &
Slide 159
Virsim and assertions
Virsim shows assertion start time
graphically but NOT endtime
which may be much later or
never…
VirSim displays assertions like signals, but this indicates their start/end times, not value.
It also indicates their status by color:
green - success
red - failure
grey - incomplete (Notice the X for finish time above)
Expand the assertion by double-clicking: revealing sample clock ticks, result and
end-time for each attempt.
Advanced Verilog
© 2004 Willamette HDL, Inc.
160
Notes:
© 2004 Willamette HDL, Inc. &
Slide 160
Boolean expressions
Basic building blocks of assertions.
• Evaluate sampled values of variables used
• 0, X or Z interpret as false
• Excludes certain types:
• time, shortreal, real, realtime
• string, event, chandle, class
• Associative/dynamic arrays
• Variables used must be static
• Excludes these operators:
• C-assignments (+=, -=, >>= etc)
• Bump operators ( i++, i--, ++i etc)
Advanced Verilog
© 2004 Willamette HDL, Inc.
161
Notes:
© 2004 Willamette HDL, Inc. &
Slide 161
Handy System Functions
7.1
$onehot[0] (<expression>) returns true if only one bit of the expression is high.
7.1
$inset (<expression>, <expression> {, <expression> } )
returns true if the first expression matches
at least one of the subsequent expressions.
7.1
$insetz (<expression>,<expression> {, <expression> } )
same as $inset but using casez semantics
7.1
$isunknown (<expression>) returns true if any bit of the expression is ‘x’.
$countones (<expression>) returns the # of 1's in a bit-vector
Advanced Verilog
© 2004 Willamette HDL, Inc.
162
Notes:
© 2004 Willamette HDL, Inc. &
Slide 162
Concurrent Assertion Basics
Consider two signals, req/ack that handshake together
req
ack
•
•
•
•
clk
clock ticks
ticks
simulation ticks
Signals change over time and interlock to implement handshake
A Verilog design ‘models’ the algorithm
A Verilog testbench duplicates this algorithm
Traditional Verification runs both versions against one another to spot:
• Logic errors
• Sequence errors
• Time errors
• Concurrent Assertions describe the sequence of changes in signals over time
• Introduces the concept of a clock to ‘sample’ signal changes and capture the sequence
This may be a real clock or a virtual one (simulator ticks?).
Advanced Verilog
© 2004 Willamette HDL, Inc.
163
Notes:
© 2004 Willamette HDL, Inc. &
Slide 163
Concurrent Assertion Basics 2
req
ack
clk
Say you sample both signals on the posedge of clk…
The waveforms effectively become:
sequences
req
1
1
0
0
1
1
1
ack
1
1
1
0
0
1
1
e1
e2
e3
e4
clk
Sequence
start
Events:
Remember, this diagram shows what the signals look like from
the point of view of the sampling clock which must be at least as
fast as the system clock
Advanced Verilog
© 2004 Willamette HDL, Inc.
Assuming you start
with req and ack hi
SVA events are:
e1
e2
e3
e4
( !req )
( !ack )
( req )
( ack )
164
Notes:
© 2004 Willamette HDL, Inc. &
Slide 164
Concurrent Assertion Basics 3
• Clocks used in assertion specification are usually simple and
cleanly defined to avoid glitching behavior
• More complex clock definitions are allowed (but be wary):
@ (posedge (clk && gating_signal))
@ (negedge (clk iff gating_signal))
7.1
• Should a variable appear in the expression for clock AND in an
expression for the assertion, the values may be different
clock expression
assertion expression
Advanced Verilog
current value
sampled value.
© 2004 Willamette HDL, Inc.
165
Notes:
© 2004 Willamette HDL, Inc. &
Slide 165
Sequence
•
•
•
•
A list of SV boolean expressions in linear order of increasing time
Boolean test for whether a signal matches a given sequence or not
Assumes an appropriate sampling clock and start/end times
If all samples in the sequence match the simulation result
then the assertion matches; otherwise it is said to fail
Sequences are described efficiently using regular expressions to
specify values over time…
(req && ack) ##1 !req ##1 !ack ##1 req ##1 (req && ack)
Assuming you start
with req and ack hi
SVA events are:
e1
e2
e3
e4
( !req )
( !ack )
( req )
( ack )
e1
e2
e3
e4
1
1
1
0
1
req
1
0
0
ack
1
1
0
Sequence
matches
clk
Sequence
start
Advanced Verilog
Sequence
mismatch
© 2004 Willamette HDL, Inc.
Sequence
end
166
Notes:
© 2004 Willamette HDL, Inc. &
Slide 166
Sequence Operators
Available sequence operators (in order of precedence):
[*
[->
[=
- consecutive repetition operator
- goto repetition (non-consecutive, exact)
- non-consecutive repetition
and
intersect
7.1
7.1
- all sequences expected to match, end times may differ
- all sequences expected to match, end times are the SAME
or
- 1 or more sequences expected to match
throughout
- expression expected to match throughout a sequence
within
- containment of a sequence expression
7.1
##
Advanced Verilog
- sequence delay specifier
© 2004 Willamette HDL, Inc.
167
Notes:
© 2004 Willamette HDL, Inc. &
Slide 167
Delay & range
Delay:
##[N]
a ##1 b
a ##0 b
a ##1 b ##1 c
// represents a sequential delay of N cycles (default 0)
// a is true on current tick, b will be true on next tick
// a is true on current tick, so is b ☺ (Overlapping!)
// a is true, b true on next tick, c true on following tick
Range:
a ##[3:5] b
a ##[3:$] b
// a is true on current tick, b will be true 3-5 ticks from now
// a is true on current tick, b will be true after 3 ticks
$ represents a non-zero
number up to infinity
Advanced Verilog
© 2004 Willamette HDL, Inc.
168
Notes:
© 2004 Willamette HDL, Inc. &
Slide 168
Sequence block
Sequence blocks identify and encapsulate a sequence definition
sequence s1;
@ (posedge clk)
a ##1 b ##1 c;
endsequence
// s1 evaluates on each successive edge of clk
sequence s2 (data,en);
// sequence with name AND arguments
(!frame && (data==data_bus)) ##1 (c_be[0:3] == en);
endsequence
Notice no clock is defined. This may be inherited from
a higher hierarchical statement like property or assert
(More on this later)
sequence s3;
start_sig ##1 s2(a,b) ##1 end_sig;
endsequence
// sequence as subexpression
Where: s3 - is same as - start_sig ##1 (!frame && (data==data_bus)) ##1 (c_be[0:3] == en) ##1 end_sig
Advanced Verilog
© 2004 Willamette HDL, Inc.
169
Notes:
© 2004 Willamette HDL, Inc. &
Slide 169
Repetition [*N [*m:n
Repetition:
a ##1 b ##1 b ##1 b ##1 c
a ##1 b [*3] ##1 c
b [*3]
// long-winded sequence expression
// same… using efficient *N syntax
- same as - b ##1 b ##1 b
// b true over 3 ticks total
(a ##2 b) [*3] - same as - (a ##2 b ##1 a ##2 b ##1 a ##2 b )
(a ##2 b) [*1:3] - same as - (a ##2 b)
or (a ##2 b ##1 a ##2 b)
or (a ##2 b ##1 a ##2 b ##1 a ##2 b)
(a[*0:3] ##1 b ##1 c) - same as - (b ##1 c)
or (a ##1 b ##1 c)
or (a ##1 a ##1 b ##1 c)
or (a ##1 a ##1 a ##1 b ##1c)
Advanced Verilog
© 2004 Willamette HDL, Inc.
170
Notes:
© 2004 Willamette HDL, Inc. &
Slide 170
Repetition [*->
[*=
7.1
goto repetition: (repeats a boolean expression)
a ##1 b [*->min:max] ##1 c
- same as - a ##1 ((!b [*0:$] ##1 b)) [*min:max]) ##1 c
a ##1 b [*->1:N] ##1 c
// a followed by at most N samples of b
// followed by c
Non-consecutive repetition:
a ##1 b [*=min:max] ##1 c
- same as - a ##1 ((!b [*0:$] ##1 b)) [*min:max])
##1 !b [*0:$] ##1 c;
SV 3.1a changes these operators to: [= and [->
Advanced Verilog
© 2004 Willamette HDL, Inc.
171
Notes:
© 2004 Willamette HDL, Inc. &
Slide 171
Preponed
Pre-active
Current events
(processed in any order)
Events to be evaluated
after active events (e.g. #Ø )
SystemVerilog
Event Scheduler
Active
Inactive
Pre-NBA
Non-blocking assignment
updates occur here
NBA
Post-NBA
Observed
Evaluation of property expressions
e.g. assertions
Reactive
Execution of Program Block
and pass/fail code from property expressions
Post-observed
Postponed
Verilog 95
PLI
SystemVerilog
Verilog 2001+
Advanced Verilog
© 2004 Willamette HDL, Inc.
172
Notes:
© 2004 Willamette HDL, Inc. &
Slide 172
Value Change Functions
These functions detect transitions between 2 consecutive ticks
$rose ( <expression> )
- true if LSB of expression went lo-hi
$fell (<expression> )
- true if LSB of expression went hi-lo
$stable ( <expression> )
- true if no change
$past ( <expression>, [#_of_ticks] ) - # of ticks into the past to look
(defaults to 1)
Use with $stable to detect glitches?
property e2;
@(posedge clk) (read_cycle) |-> ##3 (busData == mem[$past( busAddr,3 )]);
endproperty
This is an example of a property which will be discussed shortly.
For now, just see this as a syntactical example of $past…
Advanced Verilog
© 2004 Willamette HDL, Inc.
173
Notes:
© 2004 Willamette HDL, Inc. &
Slide 173
Seq. expressions: and / or / intersect
sequence s1;
a ##1 b ##1 c;
endsequence
s1
s2 s2
o_s
sequence s2;
d ##[1:3] e ##1 f;
endsequence
a_s
i_s
Sequence expressions may be logically and / or ’d together
sequence o_s;
s1 or s2;
// o_s matches if at least one sub-sequence matches
endsequence
sequence a_s;
s1 and s2;
endsequence
// both expressions must match
// (first to match waits for the other)
// a_s matches only after BOTH sequences have matched
// both expressions must match
s1 intersect s2;// (both sequences must be same length)
endsequence
// i_s matches only if e occurs 1 cycle after d
sequence i_s;
7.1
Advanced Verilog
© 2004 Willamette HDL, Inc.
174
Notes:
© 2004 Willamette HDL, Inc. &
Slide 174
UART Lab : uart transmitter
For the next few labs you will be developing assertions to verify an RTL
UART transmitter module. Design hierarchy and pin-names are described
below:
module test_u_xmit
Signals
module u_xmit
sys_clk
uart_clk
sys_rst_l
U1
done
uart_out
xmit
data
Checker routines
sys_clk
System clock
uart_clk
Serial clock ( sys_clk
sys_rst_l
Reset ( active low )
xmit
Load data and start transmission
data
Byte of data to transmit
done
Done flag (low during transmission
uart_out
Serial bitstream out
16 )
On the next slide you will examine the "specification" waveforms you will
be assertion-checking.
Advanced Verilog
© 2004 Willamette HDL, Inc.
175
Notes:
© 2004 Willamette HDL, Inc. &
Slide 175
UART Lab: Reset waveform
Timing diagram
sys_clk
uart_clk
sys_rst_l
1
xmit
2
1 sys_clk
1 sys_clk
data
XX
done
x
uart_out
x
Advanced Verilog
byte
XX
After posedge sys_rst_l done stays hi (inactive) until xmit asserts
Start
bit “0”
© 2004 Willamette HDL, Inc.
b0
176
Notes:
© 2004 Willamette HDL, Inc. &
Slide 176
Assertions Lab 2 : sequences
Working directory: sv_assertions/uart_xmit
Purpose: Write 3 reset-related sequences...
Instructions:
Examine the design (file: test_u_xmit.sv) and find the following code (~line 105):
property p_post_rst;
@(posedge sys_clk) (!sys_rst_l) |-> s_rst_pair;
endproperty
For now just accept this code…
You will look at properties and
assert’s in just a few slides…
assert_post_rst: assert property (p_post_rst)
else $display("%m : device did not reset");
This code asserts a property (p_post_rst), which uses a sequence (s_rst_pair)
to describe the behavior of the UART signals done and uart_out at reset.
Your assignment is to write the missing sequences as follows:
Advanced Verilog
© 2004 Willamette HDL, Inc.
177
Notes:
© 2004 Willamette HDL, Inc. &
Slide 177
test_u_xmit.sv
Assertions Lab 2 :
sequences
//XXXXXXXXXXXXXXXXXXXX LAB
XXXXXXXXXXXXXXXXXXXX
//XXXXXXXXXXXXXXXXXXXX STARTS XXXXXXXXXXXXXXXXXXXX
//XXXXXXXXXXXXXXXXXXXX HERE XXXXXXXXXXXXXXXXXXXX
WRITE YOUR SEQUENCES HERE
//XXXXXXXXXXXXXXXXXXXX END OF LAB
//XXXXXXXXXXXXXXXXXXXX END OF LAB
//XXXXXXXXXXXXXXXXXXXX END OF LAB
XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
property p_rst_sigs;
@(posedge sys_clk) ($fell(sys_rst_l)) |-> s_rst_sigs;
endproperty
. . .
Instructions:
assert_rst_sigs: assert property (p_rst_sigs) //$display("%m :OK!");
else $display("%m : Signals uart_out and done failed to reset");
. . .
Edit the design (file: test_u_xmit.sv)
At the indicated area of the file (nowhere else) write 3 sequences to verify reset
behavior.
1. "s_rst_sigs" : verify for uart_out(hi) and done(lo) 1 sys_clk after sys_rst_l(negedge).
2. "s_rst_done" : verify signals done(hi) and xmit(lo) 1 sys_clk after sys_rst_l
goes inactive(posedge) and remain so until xmit(posedge).
3. "s_rst_pair" : sequence verifying that “s_rst_sigs” and “s_rst_done” both match.
Advanced Verilog
© 2004 Willamette HDL, Inc.
178
Notes:
© 2004 Willamette HDL, Inc. &
Slide 178
Assertions Lab 2 :
sequences
Instructions:
When you have finished writing the assertion sequences:
1.
Use the run.csh script to compile/run your simulation (more on this script later).
•
•
•
•
•
•
This script runs the simulator in batch mode, creating a vcdfile etc
When simulation finishes, exit vcs ( type: quit )
Notice, the script now reinvokes vcs but this time in post-process mode
from the saved vcd file
Open a wave window & drag/drop “test_u_xmit” into it
In wave window, zoom in around sys_rst_l (hi-lo transition, ~4290ns)
Notice red failures. The testbench has been deliberately sabotaged ☺
2.
Why did your assertion(s) fail at 4350ns?
3.
Examine the file “assert.report”. What do you see?
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
179
Notes:
© 2004 Willamette HDL, Inc. &
Slide 179
Seq. expressions: first_match
7.1
sequence t1;
te1 ##[2:5]te2;
endsequence
sequence ts1;
first_match(te1 ##[2:5]te2);
endsequence
Each attempt of sequence t1 can result in matches for up to four cycles:
te1 ##2 te2
te1 ##3 te2
te1 ##4 te2
te1 ##5 te2
t1 s2
t1
ts1
But, sequence ts1 will match for ONLY the first of the four t1's.
Advanced Verilog
© 2004 Willamette HDL, Inc.
180
Notes:
© 2004 Willamette HDL, Inc. &
Slide 180
Conditions over sequences - throughout
Often, some preconditions exist to enable or forbid sequences of events.
A sequence may only make sense in a particular mode, or may be forbidden
to occur in another mode.
sequence burst_rule;
@(posedge clk)
$fell (burst) ##0
(!burst) throughout (##2 (!trdy [*4]));
endsequence
burst
trdy
burst1
Here, when burst goes true (low), it is expected to stay low for the next 2 ticks
and also for the following 4 clock ticks, during which trdy is also to stay low.
Advanced Verilog
© 2004 Willamette HDL, Inc.
181
Notes:
© 2004 Willamette HDL, Inc. &
Slide 181
Seq. expressions: within
7.1
within allows containment of one sequence within another
!trdy[*7] within (($fell irdy) ##1 !irdy[*8])
Here, trdy must be low for 7 consecutive cycles entirely contained
within the second expression.
Advanced Verilog
© 2004 Willamette HDL, Inc.
182
Notes:
© 2004 Willamette HDL, Inc. &
Slide 182
Seq. expressions: ended
.ended allows detection that a sequence expression has ended (matched)
s1
s2
s1 ##1 s2.ended
sequence e1;
@(posedge clk) $rose(ready) ##1 proc1 ##1 proc2;
endsequence
sequence rule;
@(posedge clk) reset ##1 inst ##1 e1.ended ##1 branch_back;
endsequence
Here, sequence e1 must end one tick after inst.
Advanced Verilog
© 2004 Willamette HDL, Inc.
183
Notes:
© 2004 Willamette HDL, Inc. &
Slide 183
Property block
• Property blocks describe behavior in a design, giving it a name for reference
and allowing a range of tools to test/check/cover/etc that behavior
• Properties are often built from sequences (though NOT vice-versa)
• Properties can appear in modules, interfaces, programs, clocking domains
even in $root
7.1
• Properties have special operators: disable iff, not, |->/|=>
• By themselves, properties do nothing… must appear in assert or cover
Optional parameters (reuse?)
Asynchronous reset?
property p1(a,b,c,d);
@ (posedge clk) disable iff (reset)
(a) |-> not ( b ##[2:3] c ##1 d );
endproperty
implication
Reversal: sequence must NEVER evaluate true
Here, when a is true the b/c/d expr. is forbidden.
Advanced Verilog
© 2004 Willamette HDL, Inc.
184
Notes:
© 2004 Willamette HDL, Inc. &
Slide 184
Implication |-> |=>
Using the implication ( |->, |=> ) operators you can specify a prerequisite
sequence that implies another sequence. Typically this reduces failures
that you expect and want to ignore.
7.1
Only boolean antecedents supported
<antecedent seq_expr> |->/|=> ( <consequent seq_expr> );
Think of it this way: If the antecedent matches, the consequent must too.
If the antecedent fails, the consequent is not tested and a true result is forced
(Such forced results are called “vacuous” and will be discussed later).
Two forms of the implication operator are supported:
( a ##1 b ##1 c ) |-> ( d ##1 e );
// overlapping form
• If a/b/c matches, then d is evaluated on THAT tick.
( a ##1 b ##1 c ) |=> ( d ##1 e );
// non-overlapping form
• If a/b/c matches, then d is evaluated on the NEXT tick.
Advanced Verilog
© 2004 Willamette HDL, Inc.
185
Notes:
© 2004 Willamette HDL, Inc. &
Slide 185
Implication Example |-> |=>
sequence s_rst_sigs;
##1 (uart_out && !done);
endsequence
sequence s_rst_done;
(!sys_rst_l) [*1:$] ##1 $rose( sys_rst_l )##1 (done && !xmit) [*1:$] ##1 $rose( xmit );
endsequence
sequence s_rst_pair;
s_rst_done and s_rst_sigs;
endsequence
The property attempts a match on every posedge of sys_clk.
property p_post_rst;
@(posedge sys_clk) ($fell(sys_rst_l)) |-> s_rst_pair;
endproperty
BUT thanks to the implication operator…
$fell(sys_rst_l) (i.e. negedge) is a prerequisite for testing the sequences…
This avoids countless "FAILS" elsewhere in simulation
Advanced Verilog
© 2004 Willamette HDL, Inc.
186
Notes:
© 2004 Willamette HDL, Inc. &
Slide 186
Multi-clock support
7.1
Most systems have more than a single clock and SV assertions allow for
this by supporting the use of multiple clocks, even within a single
property/assert. A new syntax ( ## ) is introduced:
sequence m_clk_ex;
@(posedge clk0) a ## @(posedge clk1) b
endsequence
NOTE: no N
Here, assuming a matches on clk0, b is checked on the next edge of clk1
Implication is supported but ONLY the non-overlapping form |=>
property m_clk_ex2;
@(posedge clk0) a ## @(posedge clk1) b |=> @(posedge clk2) c;
endproperty
property m_clk_ex3;
m_clk_ex |=> m_clk_ex;
endproperty
Advanced Verilog
© 2004 Willamette HDL, Inc.
187
Notes:
© 2004 Willamette HDL, Inc. &
Slide 187
Multi-clock support 2
7.1
A particularly interesting case is detecting the endpoint of a sequence
running on a different clock. For this purpose, use the matched method
which is like the ended method but for multiple clocks.
NOTE: no N
sequence e1;
@(posedge clk) $rose(ready) ##1 proc1 ##1 proc2;
endsequence
sequence rule;
@(posedge clk2) reset ##1 inst ##1 e1.matched [*->1] ##1 branch_back;
endsequence
Here, sequence e1(evaluated on clk) must end sometime after inst (evaluated
on clk2).
NOTE: sequence rule verifies that sequence e1 has ended,
it does NOT start e1 evaluating.
Advanced Verilog
© 2004 Willamette HDL, Inc.
188
Notes:
© 2004 Willamette HDL, Inc. &
Slide 188
Data-use within a sequence
7.1
Sequence verification is very useful, but data must be functionally verified too.
SV allows local variables to be defined/assigned in a sequence or property.
It also allows pure/automatic functions 7.1
All SV types are supported and are dynamic across different attempts on the
sequence.
logic [7:0] d_1, d_2, d_3;
property e1;
logic[7:0] x; 7.1
@(posedge clk) ( valid, x = d_in )
|-> ##4 d_out = ~x;
endproperty
always @ (posedge clk)
if(valid)
begin
d_1 <= #5 d_in;
d_2 <= #5 d_1;
d_3 <= #5 d_2;
d_out<= #5 ~d_3;
end
Here, when valid is true x samples d_in. Sequence e1 matches
4 cycles later, if d_out == ~x
HINT
Until VCS supports local variables in a
sequence or property, use SV variables and
always blocks to sample signals.
Advanced Verilog
© 2004 Willamette HDL, Inc.
189
Notes:
© 2004 Willamette HDL, Inc. &
Slide 189
Verification directives
• A property (or sequence) by itself does nothing. It must appear within
a verification statement to be evaluated
• Two types of verification statement:
[always] assert property - enforces a property as "checker"
[always] cover property - tracks metrics (# attempts, # match, # fail etc)
• Properties can appear in modules, interfaces, programs, clocking domains
even in $root
property p1(a,b,c);
disable iff (a) not @clk ( b ##1 c );
endproperty
7.1
assert_p1: assert property (p1(rst,in1,in2))
$info("%m OK")
else $error("%m Failed");
Advanced Verilog
© 2004 Willamette HDL, Inc.
190
Notes:
© 2004 Willamette HDL, Inc. &
Slide 190
sequence/property/ assert example
sequence s_rst_sigs;
##1 (uart_out && !done);
endsequence
sequence s_rst_done;
(!sys_rst_l) [*1:$] ##1 $rose( sys_rst_l )##1 (done && !xmit) [*1:$] ##1 $rose( xmit );
endsequence
sequence s_rst_pair;
s_rst_done and s_rst_sigs;
endsequence
property p_post_rst;
@(posedge sys_clk) (!sys_rst_l) |-> s_rst_pair;
endproperty
assert_post_rst: assert property ( p_post_rst ) //$display("%m :OK!");
else $display("%m : device did not reset fully");
Advanced Verilog
© 2004 Willamette HDL, Inc.
191
Notes:
© 2004 Willamette HDL, Inc. &
Slide 191
Embedded assertion statements
7.1
Assert / cover statements may be embedded in procedural code.
This aids maintenance AND captures designer intent… executable documentation ☺
sequence s1;
( req && !gnt) [*0:5] ##1 gnt && req ##1 !req;
endsequence
always @( posedge clk or negedge reset)
if ( !reset ) do_reset;
Enabling condition is always current with
else if ( mode )
design changes etc.
…
GOTCHA: Design flaws may be masked
if (!arb)
st <= REQ2;
Must be maintained by hand
PA: assert property (s1);
BUT: implies double-blind checking
property p1;
@( posedge clk ) ( reset && mode && !arb ) |=> s1
endproperty
Advanced Verilog
© 2004 Willamette HDL, Inc.
192
Notes:
© 2004 Willamette HDL, Inc. &
Slide 192
Clock inference
Assertions embedded in procedural code may infer a clock.
property p1;
a ##1 b ##1 c;
endproperty
Inferred clock
always @( posedge clk )
assert property ( p1 );
NOTE
Assertions embedded in initial
blocks
execute just once, at time t0
Variables a,b,c MUST not be
used inside the procedural block
• If the embedded property specifies a clock, it must match the inferred clock
• Variables monitored by a property must not be used within the inferring block
Advanced Verilog
© 2004 Willamette HDL, Inc.
193
Notes:
© 2004 Willamette HDL, Inc. &
Slide 193
Clock specification
The clock a property works from may be specified in several ways.
1.
Specified within the property ( clk1 below )
property p1; @(posedge clk1) a ##2 b; endproperty
ap1: assert property (p1);
2.
Inherited from a sub-sequence ( clk2 below )
sequence s1; @(posedge clk2) a ##2 b; endsequence
property p1; not s1; endproperty
ap1: assert property (p1);
3.
From an embedding procedural block ( clk 3 below )
7.1
always @(posedge clk3) assert property ( not ( a ##2 b ));
4.
From a clocking domain ( clk 4 or clk5 below )
clocking master_clk @(posedge clk4)
property p1; not ( a ##2 b ); endproperty
endclocking
ap1: assert property (master_clk.p1);
Advanced Verilog
© 2004 Willamette HDL, Inc.
7.1
default clocking
master_clk @(posedge clk5);
194
Notes:
© 2004 Willamette HDL, Inc. &
Slide 194
Cover directive
Like assert, the cover statement is a verification directive which identifies
properties or sequences of interest. Where they differ is that cover simply
identifies sequences/properties to be tracked for coverage statistic purposes
NOT enforced as behavioral checks.
In response to a cover directive, the simulator will gather and report metrics
on the specified sequences or properties, including:
# of times attempted
# of passes
# of failures
property p1(a,b,c);
disable iff (a) not @clk ( b ##1 c );
endproperty
cover_c1: cover property (p1(rst,in1,in2))
$display(“Property p1 succeeded");
7.1
Optional statement triggered every time:
- a property succeeds
- a sequence matches
Advanced Verilog
© 2004 Willamette HDL, Inc.
195
Notes:
© 2004 Willamette HDL, Inc. &
Slide 195
Bind directive
As you saw, embedded assertions have advantages/disadvantages.
Another approach is to keep verification code separate from the design
and use the bind directive to associate them.
• bind can connect a module, interface or program instance (with checkers?)
to a module or module instance
• bind may appear in a module or in $root
bind
cpu1
cpu2
cpu_chk
<module>
<module_instance>
<module_instantiation>
<program_instantiation>
<interface_instantiation>
<instance_name>
module cpu_chk (input a,b,c,d);
property p1; @ (posedge clk) a |-> ##1 (b !== (c ^ d)); endproperty
cpu_p1: assert property (p1);
endmodule
bind cpu cpu_chk CHK1(enable, d_out, d_in, op);
Advanced Verilog
© 2004 Willamette HDL, Inc.
196
Notes:
© 2004 Willamette HDL, Inc. &
Slide 196
Assertion Guidelines
Like any new methodology, ABV users can benefit from guidelines:
1. Start with simple assertions and build up to more complex.
2. Use sequences/booleans wherever you can predict/expect reuse.
3. Start by writing assertions that only use a single signal (plus clock).
• Check how long signals are active, etc.
• Easy to write
• Help verify your methodology/structure (embedded or not?)
4. Follow up by writing assertions that only use two signals, plus a
clock (req and gnt, or mut-ex signals).
5. Continue this way before getting to the complex assertions.
6. Complex systems are often described using a flow chart.
In this case, write one assertion for each arrow in the flow chart.
(simpler assertions, easy estimation how many).
7. Consider the Checker Library (SVA Checker Lib) of functions
provided with VCS. These can help with common checker
situations like mutex, one-hot, handshake, fifo, memory etc.
Advanced Verilog
© 2004 Willamette HDL, Inc.
197
Notes:
© 2004 Willamette HDL, Inc. &
Slide 197
SV Assertions and VCS
To control SV assertions, VCS supports a compile-time option:
-assert <enable_diag> / <filter_past>
<enable_diag> enables further options at run-time
-assert <arg>
Some of the supported <arg> values are:
quiet
- disable messages to stdout
filter
- filter “vacuous” matches
success
- report matches in addition to failures
maxfail=N
- limit failures of each assertion to N
quiet
- disable messages to stdout
report[=<path/filename>]
- report file (default is: ./assert.report)
verbose
Advanced Verilog
- verbose form of report
© 2004 Willamette HDL, Inc.
198
Notes:
© 2004 Willamette HDL, Inc. &
Slide 198
Typical VCS run.csh script
It is often convenient to invoke VCS within a simple csh script.
Example
vcs +sysvcs \
-assert enable_diag \
+define+SVA \
<design_files>
simv -assert report+verbose
vcs
Notice the `define for SVA, which might be used as follows:
`ifdef SVA
Conditional compilation of assertion blocks
a_one_enable : assert property ( @ ( posedge clk)
not ( enable_1 && enable_2));
`endif
Advanced Verilog
© 2004 Willamette HDL, Inc.
199
Notes:
© 2004 Willamette HDL, Inc. &
Slide 199
Coverage Reporting in VCS
To enable assertion coverage reporting in VCS try:
vcs +sysvcs \
-assert enable_diag \
+define+SVA \
-cm assert \
<design_files>
simv -assert report+verbose
Notice the usual simulator run-time (simv) but in addition:
assert.report
simv.vdb/
<- SVA assertion report file
<- verification database, showing coverage reports and more
A TCL script assertCovReport is provided to create handy html reports:
simv.vdb/reports/report.index.html
- verification database, showing coverage reports and other files
NOTE
For LOTS more on assertion coverage
reporting, see the VCS User Guide
Advanced Verilog
© 2004 Willamette HDL, Inc.
200
Notes:
© 2004 Willamette HDL, Inc. &
Slide 200
UART Lab: Byte transmit waveform
Signals
Timing diagram
sys_clk
System clock
uart_clk
Serial clock ( sys_clk
sys_rst_l
Reset ( active low )
xmit
Load data and start transmission
data
Byte of data to transmit
done
Done flag (low during transmission
uart_out
Serial bitstream out
16 )
1 uart_clk = sys_clk/16
sys_clk
uart_clk
2
xmit
3
data
XX
xmit pulse lasts 16 sys_clk
5
byte
Data unchanging while xmit hi
XX
4
done
1 sys_clk
uart_out
Start
bit “0”
b0
b1
b2
b3
done stays low
175 sys_clks
or 11 uart_clks
b4
b5
b6
b7
Stop
bit “1”
6 Data transmits LSB first, with 1 start-bit, 1 stop-bit
Advanced Verilog
© 2004 Willamette HDL, Inc.
201
Notes:
© 2004 Willamette HDL, Inc. &
Slide 201
Assertions Lab 3 : assert
Working directory: sv_assertions/u_xmit
Purpose: Continue assertion based verification of the UART...
Instructions:
Edit the design (file: test_u_xmit.sv)
Code up the following assertions:
1. “p_uart_sys16” - Count 16 sys_clk cycles per uart_clk cycle
2. “p_xmit_hi16” – xmit stays hi for 16 sys_clk cycles
3. “p_xmit_done” - One sys_clk after xmit (assert, hi), you see done(de-assert, lo)
& uart_out(lo)
4. “p_done_175” - Transmitting a byte (i.e. done (de-asserted, lo) takes
175 sys_clk cycles.
5. “p_xmit_nc_data” - While xmit is asserted(hi) data value is unchanging ($stable ?)
6. “p_val_bit_stream” – Verify the serial bitstream for each byte!!
7. Verify your assertions in simulation by inserting errors in the design etc.
Extra Credit: Repeat #2, #4 and #6, but this time use uart_clk as reference.
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
202
Notes:
© 2004 Willamette HDL, Inc. &
Slide 202
SVA Checker Library
The SVA Checker Library is a collection of temporal expressions and
assertions for a variety of commonly needed tests.
The library is based upon the OVL checker library but extends upon it…
Using these checkers will reduce coding of your own assertions.
Base SVA Checker Library
assert_always
assert_always_on_edge
assert_change
assert_cycle_sequence
assert_decrement
assert_delta
assert_even_parity
assert_fifo_index
assert_frame
assert_handshake
assert_implication
assert_increment
assert_never
assert_next
assert_no_overflow
assert_no_transition
assert_no_underflow
Advanced Verilog
assert_odd_parity
assert_one_cold
assert_one_hot
assert_proposition
assert_quiescent_state
assert_range
assert_time
assert_transition
assert_unchange
assert_width
assert_win_change
assert_win_unchange
assert_window
assert_zero_one_hot
© 2004 Willamette HDL, Inc.
SVA Advanced Checkers
assert_arbiter
assert_bits
assert_code_distance
assert_data_used
assert_driven
assert_dual_clk_fifo
assert_fifo
assert_hold_value
assert_memory_async
assert_memory_sync
assert_mutex
assert_next_state
assert_no_contention
assert_reg_loaded
assert_req_ack_unique
assert_stack
assert_valid_id
assert_value
203
Notes:
© 2004 Willamette HDL, Inc. &
Slide 203
Using the SVA Checker Library
SVA Checker Library components are available as modules or interfaces.
Module is default, to instantiate as an interface use:
`define SVA_STD_INTERFACE
To use the Library, simply instantiate any number of checkers in the SV
design code, enable them and point VCS to the library install directory as
follows.
Required `define
vcs +sysvcs +define+ASSERT_ON
-y $VCS_HOME/packages/sva +libext+.v
+incdir+$VCS_HOME/packages/sva
<design_files.sv>
Advanced Verilog
© 2004 Willamette HDL, Inc.
\
\
\
204
Notes:
© 2004 Willamette HDL, Inc. &
Slide 204
SVA Checker Library
example
$VCS_HOME/packages/sva/assert_mutex.v
/*
assert_mutex
Ensures that <a> and <b> never evaluate true at the same time. The check
is not enabled unless <reset_n> evaluates true (1). The checks is
performed on the active <clk> edge specification.
module test_design();
….
….
Failure modes:
The assertion assert_mutex will report failure when <a> and <b> are
both sampled 1 at the positive edge of <clk>.
design DUT (dat, addr, rd, wr, enable_1, enable_2, clk, rst_);
assert_mutex mutex_inst( clk, 1, gnt[0], gnt[1]);
….
….
verifies that gnt[0] and gnt[1] are never 1 at the same time as
sampled by posedge of clk. The checker is always enabled because
<reset_n> is constant 1.
*/
// SVA module instantiation
`ifdef SVA
assert_mutex MUTEX ( clk, rst_, enable_1, enable_2);
`endif
endmodule
Example:
`ifdef SVA_STD_INTERFACE
interface assert_mutex(clk, reset_n, a, b);
`else
module assert_mutex( clk, reset_n, a, b);
`endif
parameter
severity_level
= 0;
parameter
edge_expr
= 0;
parameter
msg
= "VIOLATION";
….
….
`ifdef SVA_STD_INTERFACE
endinterface
`else
endmodule
`endif
Advanced Verilog
© 2004 Willamette HDL, Inc.
205
Notes:
© 2004 Willamette HDL, Inc. &
Slide 205
Assertions Lab 4 : checker lib
Working directory: sv_assertions/fsm
Purpose: Test for one_hot state variable...
Instructions:
Edit the design (file: fsm_ex.sv)
Use the "assert_one_hot" checker from the SVA Checker library to test for
one-hot behavior of the state vector state.
Verify your assertion in simulation by changing the states enumeration.
Use the run.csh script to compile/run your vcs simulation (more on this script later).
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
206
Notes:
© 2004 Willamette HDL, Inc. &
Slide 206
Verilog for Test
Advanced Verilog
© 2004 Willamette HDL, Inc.
207
Notes:
© 2004 Willamette HDL, Inc. &
Slide 207
Code Profiling
VCS Tip!
Turn on code profiling with the run-time switch +prof
The profiler produces a report called vcs.prof.
===========================================================
This report identifies:
MODULE VIEW
===========================================================
Module(index)
%Totaltime No of Instances Definition
• Module instances that use the most CPU
----------------------------------------------------------test_sm
(1)
56.73
1
test_sm.v:6.
• The Verilog code in those instances that
sm
(2)
13.46
1
sm.v:7.
use the most CPU time.
sm_seq
(3)
8.18
1
sm_seq.v:8.
beh_sram
(4)
7.92
1
beh_sram.v:3.
-------------------------------------------------------------snip-snip---The file contains a number of views:
===========================================================
TOP-LEVEL CONSTRUCT VIEW
• Top Level View
----------------------------------------------------------• Module View
Verilog Construct
%Totaltime
• Instance View
----------------------------------------------------------Always
65.44
• Module Construct Mapping View
Initial
6.86
• Top Level Construct View
Combinational
6.33
Task
5.54
• Construct View Across Design
Timing Check
1.85
Port
0.26
Module Path
0.00
Function
0.00
Consider rewriting the “greediest” lines/modules
Udp
0.00
Protected
0.00
to make them more efficient and thus speed up
___________________________________________________________
time
Profiler Hint:
your simulation.
Advanced Verilog
© 2004 Willamette HDL, Inc.
208
Notes:
© 2004 Willamette HDL, Inc. &
Slide 208
Testbench - Instantiation
Two ways to instantiate:
• By port order
• By port name
syntax for instantiation by port order:
module_name instance_name (signal, signal,...);
syntax for instantiation by port name:
module_name instance_name (.port_name(signal), .port_name
(signal),... );
Instantiation by port name is usually best, especially if:
• The module is “owned” by a third party
• The module has a lot of ports
Advanced Verilog
© 2004 Willamette HDL, Inc.
209
Notes:
© 2004 Willamette HDL, Inc. &
Slide 209
Testbench – Sparse Memories
Consider a Verilog system model with 64Mx32 memory. reg [31:0] mem [(64*1024*1024) -1:0];
• This would require 2x64M words of workstation memory to model (4 data values: 0,1,x,z)
which is a huge overhead and would slow simulation performance considerably.
• Most simulations of this system will actually access a small fraction of the 64Mx32 array.
• Enter “sparse” memory models (a.k.a. dynamic memory)
• reduce run-time memory usage
• improve simulation speed
New VCS 6.1+ syntax:
reg /*sparse*/ [31:0] mem [(64*1024*1024) -1:0];
• Use only for designs with:
• Arrays larger than 2MBytes
• <50% usage of memory array
• Performance improvement:
• ~97% for memory usage of 1%
• Only 25% improvement for 50% usage
Advanced Verilog
© 2004 Willamette HDL, Inc.
210
Notes:
© 2004 Willamette HDL, Inc. &
Slide 210
Testbench - $system[f] function
$system and $systemf permit OS commands to be executed from within Verilog?
int val;
val = $system(“cp file.1 file.2”);
val = $systemf(“cp %s %s”, ”file1” , “file2”); // $systemf allows string arguments
Caveats:
• $system[f] command interrupts Verilog simulation until it completes
• Only a single command can be active at one time
• e.g.
fork
$system(“cp file1 file2”);
$system(“cp file3 file4”);
join
Advanced Verilog
// DESPITE fork-join
// one cp executes first &
// the other happens after first one completes
© 2004 Willamette HDL, Inc.
211
Notes:
© 2004 Willamette HDL, Inc. &
Slide 211
// Solution to Steganographic decoder problem
//
// Message size stored in pixels 64 -> 79
// Message stored in pixels 80 -> 80+(size * 8)
//
`define PIC_SIZE 61_080
module steg_decode;
integer rfile, i, ifs, j, k;
reg [15:0] siz;
reg [2:0] block;
reg [7:0] byte, tmp;
reg [7:0] mem[0:`PIC_SIZE -1];
reg [13*8:1] rfile_name; // Allow DOS (9.3) filenames
$systemf example
$display("Secret message is %0d characters long",siz);
siz = 8*(siz);
// convert to # of bits
$display("\nMessage Text follows.... \n\n");
block = 0;
for (j=80; j< siz; j=j+1) // Retrieve the message
begin
initial
byte[block] = mem[j][0];
begin
if (block == 7)
block = 3'b111;
begin
$write("%s",byte);
rfile_name = "message.bmp";
// Filename
end
rfile = $systemf(“kview %s”, rfile_name); // halts until kview exits
block = block +1;
end
rfile = $fopen(rfile_name, "r");
// Open the file
$display("\n\n\n");
i = $fread(mem, rfile, 0);
// Read the file into memory
$fclose(rfile);
ifs = $ftell(rfile);
$finish;
$display("Loaded %0d pixels \n", ifs);
end
k = 0;
for (j=64; j<80; j=j+1)
begin
siz[k] = mem[j][0];
k = k+1;
end
// Determine message length
Advanced Verilog
endmodule //
© 2004 Willamette HDL, Inc.
212
Notes:
© 2004 Willamette HDL, Inc. &
Slide 212
VCS Performance – Radiant technology
Radiant Technology applies performance enhancements to your design during
compilation. It benefits all levels of abstraction (beh - rtl - gate) but especially
functional, non-timing simulation. Radiant is optional now but will become the default
in a future release of VCS.
Speedup of 1.5x-5x is typical
There are two levels: (specified by + options on vcs command line)
+rad+1, +radlite,
+radlight :
Level one, simple local optimizations with faster compile times.
+rad, +rad+2 :
Level two, much more optimization, some structural changes
to design and longer compile time.
Remember:
Radiant technology (esp. Level 2) can make debug more difficult
because it can change design structure.
in other words…
“TURN RADIANT OFF FOR DEBUG & ON FOR REGRESSION”
Advanced Verilog
© 2004 Willamette HDL, Inc.
213
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 213
Testbench – Using libraries
• Organize your code into libraries according to abstraction level
• A library is usually organized as either:
• library file
• One file containing all the Verilog modules in that library
• library directory
• A single directory per library
• A separate file for each module in the library
• Let’s look at how to specify a library:
• The wrong way & the right way
Advanced Verilog
© 2004 Willamette HDL, Inc.
214
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 214
Using Libraries - 2
(Only allows a single library (or sequence of libraries) to be used)
Command-line options are used with verilog that scan model libraries and compile
only the components used by the design.
-v <file_name>
-y <directory_names>
Scans a library file and compiles the required modules
Scans a library directory and compiles the required files
+libext+ <extension>+
Appends the <extension> to the module name to find the
file name in a library directory
Example: vcs test_pipe.v pipe_net.v -y /usr/libs/LSI/lsi10K.dir +libext+.v+
(Allows as many unique library references as you want)
`uselib<LIB_REF>
where LIB_REF is one or more of the following:
file=<libfile.v>
dir=<libdir>
libext=<libext>
<empty>
mod_name inst_name (port1, port2 ...);
Advanced Verilog
© 2004 Willamette HDL, Inc.
215
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 215
`uselib<LIB_REF>
where LIB_REF is one or more of the following:
file=<libfile.v>
dir=<libdir>
libext=<libext>
<empty>
mod_name inst_name (port1, port2 ....);
Example `uselib code
`define LIB_ROOT /home/ourlib
`define BEH_LIB dir=`LIB_ROOT/BEH_LIB/source libext=.v
`define RTL_LIB file=`LIB_ROOT/RTL_LIB/rtl.v
module mydesign(portlist...)
`uselib `BEH_LIB
asic1 U1 (portlist...); // Instantiates a Behavioral model of ASIC1
asic2 U2 (portlist...);
asic3 U3 (portlist...);
`uselib `RTL_LIB
asic1 U4 (portlist...); // Instantiates an RTL model of ASIC1
endmodule
`uselib
-or`resetall
Advanced Verilog
// Cancel the current `uselib
// Cancel any current compiler directives
© 2004 Willamette HDL, Inc.
216
Speaker notes:
Notes:
© 2004 Willamette HDL, Inc. &
Slide 216
` Testbench Configuration Exercise - 1
Working directory: TB_EX
• Modify the testbench “test_sm.v” per the directory structure
• Notice the 3 source directories [gat_lib, rtl_lib, beh_lib]
• Find unstructured instantiations at the bottom of the file
• Implement 3 user-selectable configurations (file: “test_choices”)
• GAT: Gate-level models: sm_seq & sm
plus the class_lib simulation library file!
• RTL: RTL models sm_seq, sm and beh_sram
• BEH: Behavioral model sm_func
(Feel free to substitute your “shell” fsm lab solution)
• Create the configuration file “test_choices”
Advanced Verilog
© 2004 Willamette HDL, Inc.
217
Notes:
© 2004 Willamette HDL, Inc. &
Slide 217
` Testbench Configuration Exercise - 2
HINT:
`include “file”
Use for configuration information
`ifdef
Use for structural differences
`uselib
Use for abstraction level selection
beh_lib
sm_seq
beh_sram.v
sm_func
opcode
into
sm
rtl_lib
test_sm.v
beh_sram
rst
sm.v
sm_seq.v
clk
clk
gat_lib
test_choices
inca
a_wen_
wd_wen_
rd_wen_
sm.v
sm_seq.v
sm_seq_DW01_inc_10_0.v
class_lib
Note: The RTL and GAT configurations
are hierarchical:
RTL: sm_seq instantiates sm
GAT: sm_seq instantiates sm & also
sm_seq_DW01_inc_10_0
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
218
Notes:
© 2004 Willamette HDL, Inc. &
Slide 218
Testbench – Clock Generation
Clocks are the single greatest source of simulation
events in your design.
reg clk;
initial
clk = 0;
always
begin
#20 clk = 1;
#20 clk = 0;
end
reg clk;
initial
begin
clk = 0;
forever
begin
#20 clk = 1;
#20 clk = 0;
end
end
reg clk;
initial
begin
clk = 0;
forever
#20 clk = !clk;
end
NOTE: Some RTL clocks are more efficient than others.
Advanced Verilog
© 2004 Willamette HDL, Inc.
reg clk;
initial
begin
clk = 0;
forever
#20 clk = ~clk;
end
219
Notes:
© 2004 Willamette HDL, Inc. &
Slide 219
Testbench - Output (1)
• $display[b/o/h](); // prints messages to screen with <cr>
TIP: You can print the instance name (%m) as part of a message
$display ($time,“%m
• $write [b/o/h]();
Out_reg = %b”, out_reg);
// Same as $display but without <cr>
• $monitor [b/o/h](); // Same syntax as $display, but auto-prints
– outputs whenever a (non-$time) variable it references changes
TIP: only one $monitor can be active at a time
Remember
$monitor ($time,“Out_reg = %b”, out_reg);
• $strobe [b/o/h]();
– like $display, but waits until end of time step
Include your testbench
name or instance name
in every message.
Current simulation-time
is very handy too!
always wait (valid)
@ (posedge clk)
$strobe (“On active clk edge, Data[31:0] = %0h”, data);
Advanced Verilog
© 2004 Willamette HDL, Inc.
220
Notes:
© 2004 Willamette HDL, Inc. &
Slide 220
Testbench - Output (2)
• Write to a file instead of the screen
• Standard System tasks:
$fopen, $fclose
$fmonitor, $fdisplay, $fwrite, $fstrobe
module test_dcm(clk,bus_error_flag,stat_var);
input clk,bus_error_flag,stat_var;
integer errfile; Returns “mcd” handle
initial
errfile = $fopen("error_output");
always @ (posedge clk)
Testbench-name!
Print time in minimum space
if (bus_error_flag)
$fdisplay(errfile,“TB1: Bus error! Time: %0d: status: %d", $stime, stat_var);
endmodule
Advanced Verilog
File handle
32-bit time value
© 2004 Willamette HDL, Inc.
221
Notes:
© 2004 Willamette HDL, Inc. &
Slide 221
Testbench: Self Checking Tests
All tests should be self-checking.
• Never apply a vector if you cannot predict (and check for) the response
• Vector application and response checking should be routine based:
• These routines should use symmetrical sequence generators
• Verilog “$random“ function is ideal for this
• Apply & response routines should always be synchronized:
• This is especially easy in combinational devices
• It can also be easy in sequential devices:
• A simple “repeat(2)@(posedge clk)“ can allow time for outputs to update
• Apply routine can wait for the response “ @, wait() “
• “fork-join” can kick off simultaneous processes
• Totally asynchronous apply/response testing is much trickier (next 2 slides)
• Consider named-events as “remote triggers”
• “fork-join” can kick off AND resynchronize asynchronous processes
NEVER leave error checking to human eyeballing of log files or screenfulls of patterns ☺
Advanced Verilog
© 2004 Willamette HDL, Inc.
222
Notes:
© 2004 Willamette HDL, Inc. &
Slide 222
Testbench – fork-join enhancement
Fork-join is extremely useful in testing because it spawns parallel processes and then
resynchronizes once both processes complete:
fork
apply_task(…);
verify_task(…);
join
SystemVerilog (and Vera) take fork-join much further to make testing complex devices easier.
With a little ingenuity you can come ‘close’ to these capabilities in “old” Verilog :
always begin
fork
begin
@(start_apply);
apply_task(…);
end
always @(start_apply);
apply_task(…);
always @(start_verify);
verify_task(…);
initial
begin
// different start time
#10 -> start_apply;
#10 -> start_verify;
...
// continue on
end
Processes start at different times
and code execution continues in parallel.
Advanced Verilog
Processes start at
different times and you
can detect when both
have completed.
begin
@(start_verify);
verify_task(…);
end
join
-> done;
end
Some delay is
needed to be
sure the always
block has
started
initial
begin
// different start times
#10 -> start_apply;
#5 -> start_verify;
@(done); // wait until both done
...
// both have now finished
end
© 2004 Willamette HDL, Inc.
223
Notes:
© 2004 Willamette HDL, Inc. &
Slide 223
Testbench – Timeout tests
Sometimes you must ensure a stimulus routine doesn’t “hang” or “timeout”
task apply_vector;
input ….
fork
begin : do_block
do_something_task(…);
disable verify_block; // stop verifying when done
$display(“Successfully did something”);
end
begin : verify_block
verify_something_gets_done(…); // verify or timeout
disable do_block; // stop doing it after timeout
$display(“Error: Timed out doing something”);
end
join
endtask
task apply_vector;
input ….
fork
begin
do_something_task(…);
$display(“Successfully did something”);
disable apply_vector; // stop verifying when done
end
Spawn a verify process in parallel with the
test process. Verify process may actually
verify correct vector response or just timeout
if the test process takes longer than it should.
First process to complete shuts down the other
without affecting itself.
Same as above… but…
First process to complete shuts down the parent task
thus stopping itself as well.
begin
verify_something_gets_done(…); // verify or timeout
$display(“Error: Timed out doing something”);
disable apply_vector; // stop doing it after timeout
end
join
endtask
Advanced Verilog
© 2004 Willamette HDL, Inc.
224
Notes:
© 2004 Willamette HDL, Inc. &
Slide 224
Testbench – Vector manipulation
Verilog has poor file read capabilities. Used to be only one way ($readmem{b/h}).
2 different examples of reading vectors from a file will be discussed.
$readmemh system task
Verilog 2001 file routines
Pro:
• Easy, Verilog-native approach
• Fully portable code
Pro:
• Most flexible approach
• Line-by-line access to vectors
Con:
• Must read entire file into memory
• Large vector sets (memory) slows simulation
Con:
• Slower
Advanced Verilog
© 2004 Willamette HDL, Inc.
225
Notes:
© 2004 Willamette HDL, Inc. &
Slide 225
Testbench – Vector manipulation (1)
METHOD 1: Use $readmemh to load an entire vector-set into a memory.
module test_dut;
reg[31:0] test_mem [0:1023];
reg[15:0] send;
wire[15:0] return;
reg clk;
parameter cycle = 40;
event read_mem;
always #(cycle / 2) clk = !clk; // Clock generator
initial
begin
@ (read_mem) $readmemh("vector1.dat",test_mem);
$display("loading vector1.dat");
@ (read_mem) $readmemh("vector2.dat",test_mem);
$display("loading vector2.dat");
end
for (cnt=0; cnt < 1024; cnt = cnt+1)
begin
@(posedge clk);
{send,exp} = test_mem[cnt];
repeat(2)@(negedge clk); // wait to middle of next cycle
if (return !== exp)
$display("Error in memory read");
end
endtask
endmodule // test_dut
inv1 DUT (return, send); // Circuit under test
task do_test;
reg[15:0] stim, exp;
integer cnt;
initial
begin
clk = 0;
repeat(5) @(negedge clk);
-> read_mem;
// Load test-vector array
do_test;
-> read_mem;
// re-Load test-vector array
do_test;
$finish;
end
Advanced Verilog
module inv1 (out, in);
input [15:0] in;
output [15:0] out;
wire [15:0] out;
assign out = ~in;
test_dut
DUT
send
return
endmodule
© 2004 Willamette HDL, Inc.
226
Notes:
© 2004 Willamette HDL, Inc. &
Slide 226
Testbench – Vector manipulation (2)
METHOD 2: Use the Verilog 2001 file routines to load one vector at a time.
`define EOF 32'hFFFF_FFFF
`define NULL 0
`define MAX_LINE_LENGTH 1000
module test_dut;
integer file, r;
reg[15:0] send, exp, clock;
wire[15:0] return;
//reg [`MAX_LINE_LENGTH*8:1] file;
parameter cycle = 20;
always #(cycle / 2) clock = !clock; // Clock
inv1 DUT (return, send); // Circuit under test
test_dut
DUT
send
return
initial
begin : file_block
clock = 0;
file = $fopen("compare.pat", "r");
if (file == `NULL)
// cancel if file not found
disable file_block;
r = 1;
forever
begin
@(posedge clock)
r = $fscanf(file," %h %h \n", send, exp);
if (r == 0) $finish;
repeat(2) @(negedge clock); // wait to middle of next cycle
if (return !== exp)
$display("Error. send: %0h exp: %0h act: %0h",
send, exp, return);
else
$display("Correct. send: %0h exp: %0h act: %0h",
send, exp, return);
end // forever
$fclose(file);
$stop;
end // initial
endmodule // test_dut
Advanced Verilog
© 2004 Willamette HDL, Inc.
module inv1 (out, in);
input [3:0] in;
output [3:0] out;
wire [3:0] out;
assign out = ~in;
endmodule
227
Notes:
© 2004 Willamette HDL, Inc. &
Slide 227
Testbench – Timing Checks
Although designed for primitive level modeling, specify blocks
can also be used behaviorally for setup & hold checking. This
can be done either in a module or in some part of the test fixture.
syntax:
specify
specparam declarations
timing constraint checks
simple pin-to-pin path delay
edge-sensitive pin-to-pin path delay
state dependent pin-to-pin path delay
endspecify
Advanced Verilog
© 2004 Willamette HDL, Inc.
228
Notes:
© 2004 Willamette HDL, Inc. &
Slide 228
Using Specify blocks
Timing checks are useful in “IP” style models which will be shared
or sold. If placed in RTL code make sure synthesis tools do not see
them. ( //synopsys translate_off , //synopsys translate_on )
$disable_warnings
$enable_warnings
$hold
$period
$recovery
$recrem // neg timing checks
$setup
$setuphold
$skew
$width
Remember:
Timing checks may only be applied to the
ports of the module...
Perfect for Bus monitors!
Tip
Most timing check tasks support an optional final parameter, called “notifier”
This is a convenient way to trigger your own code when a timing violation
occurs.
$setup(rd_, negedge clk, 3.5, s_viol);
Just declare a single-bit reg as the notifier (remember to initialize it! ) and if
the timing check is ever triggered the simulator will toggle the notifier reg.
Now, you can trigger your own response to a timing violation easily:
always @ (s_viol)
do_something
Advanced Verilog
© 2004 Willamette HDL, Inc.
229
Notes:
© 2004 Willamette HDL, Inc. &
Slide 229
/* Simple Behavioral SRAM Model */
module beh_sram(clk, dat, addr, rd_, wr_);
Behavioral
SRAM model with Timing
checks beh_sram.v
inout [31:0] dat;
input [9:0] addr;
input clk, rd_, wr_;
parameter M_DLY = 9;
specify
reg [31:0] mem [0:1023];
// memory array
reg [31:0] dat_r;
tri [31:0] dat = rd_ ? 32'bZ : dat_r ;
initial begin
dat_r = 0;
end
always @ (negedge clk)
case ({ rd_ , wr_ })
2’b01: begin
dat_r <= #M_DLY mem[addr];
2’b10:
mem[addr] <= #M_DLY dat;
2’b00:
$display($stime,, "Error: Simultaneous Reads & Writes.");
endcase
Advanced Verilog
© 2004 Willamette HDL, Inc.
specparam ts = 9, th = 5;
$setup(rd_, negedge clk, ts);
$setup(wr_, negedge clk, ts);
$setup(addr, negedge clk, ts);
$hold(negedge clk, rd_, th);
$hold(negedge clk, wr_, th);
$hold(negedge clk, addr, th);
endspecify
endmodule
230
Notes:
© 2004 Willamette HDL, Inc. &
Slide 230
Testbench – A proven approach
Designing a testbench for a new chip/module/system?
Device abcd432
Pkg: jdip
Start from the Functional Spec, or datasheet.
sys_clk
read
READ CYCLE
empty
Thoroughly study & understand the document.
data
data
empty
WRITE CYCLE
Derive a list of basic cycles the device can perform. Usually
the waveform diagrams are a good clue (3 in this example).
read
sys_clk
data
empty
read
DMA CYCLE
sys_clk
datasheet
Design the test fixture:
A. Determine the abstraction level and purpose of your tests.
B. Design an appropriate system for testing:
i. What external devices/circuits will be needed.
ii. What standard interfaces are involved etc.
iii.Obtain/write models of all these.
Create the testbench:
A. Define the clocks, the instantiations and other basics.
B. Start with one task per cycle (i.e. per timing diagram):
i. Model the outside worlds participation in each cycle.
ii. Make the tasks self-checking if possible.
C. Build test sequences using the tasks:
i. Start simple, building up to more complex tests
ii. Carefully document your testbench code
Advanced Verilog
© 2004 Willamette HDL, Inc.
231
Notes:
© 2004 Willamette HDL, Inc. &
Slide 231
Test Exercise – Part 1
Working directory: TEST
Purpose: Write a testbench from scratch
Assignment
Write Verilog code to generate a custom
test-vector file mul4.dat. ($fopen and $fwrite?):
Match the defined format shown here
Multiply together all numbers in the range
0 – 1F hex (0 to 31 decimal )
i.e.
64-bits(16-hex digits)
0001000500000005
0000FADE00000000
1000000200002000
op1
(16-bit)
op2
(16-bit)
expected
(32-bit)
HINT: Nest 2 for-loops
0 x 0 =
0
0 x 1 =
0
0 x 2 =
0
. . . . . .
0 x 1F =
0
. . . . . .
1F x 0 =
0
. . . . . .
1F x 1D = 383
1F x 1E = 3A2
1F x 1F = 3C1
1024
lines
hex data file
mulX.dat
Vector Format
•64-bits wide, comprising three fields
–op1: 16-bit operand
–op2: 16-bit operand
–exp: 32-bit result to be expected
•1024 words deep
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
232
Notes:
© 2004 Willamette HDL, Inc. &
Slide 232
Test Exercise – Part 2
Assignment
1. Design/code a test-fixture for the supplied
multiplier model (see timing on next slide):
Write two tasks one to apply operands,
another to read data from the FIFO
Devise a way to control the rate at which
these tasks apply/verify the vectors
(i.e slow / fast)
2. Your are provided with 3 test-vector files
(mul1.dat, mul2.dat, mul3.dat)
Using these, (plus the one you just created
yourself ) your test-fixture should:
Load, apply & verify all 4 vector-files in
sequence (NOTE: simultaneous apply/verify)
Gather all $readmemh commands together
Be sure to test for conditions where
FIFO is normally-full (apply fast, read slow)
FIFO is normally-empty (vice-versa)
op1
op2
valid
16
16
X
full
clk
FIFO
read
3. Try to identify a “bug” in the multiplier
empty
(32x32)
fifo_out
32
multi.v
16x16 5-cycle multiplier
with integral 32-word FIFO
4. Can you determine your % code coverage?
Advanced Verilog
© 2004 Willamette HDL, Inc.
233
Notes:
© 2004 Willamette HDL, Inc. &
Slide 233
Test Exercise (multi.v)
multi.v
•
16x16 pipelined multiplier (op1 * op2)
•
5-cycles of clk to complete a multiply operation
•
A high (1) on the valid input enables a multiply operation
on a posedge of clk
•
On-board FIFO buffers up to 32 successive multiply
operations before stalling (full goes high).
•
The full flag goes high when FIFO is 5 words from full (27)
•
The empty flag asserts when FIFO is empty
•
The read input allows reading of FIFO on posedge of clk
op1
x
2h
op2
x
4h
multi.v
op1
16
op2
16
valid
X
full
clk
FIFO
empty
(32x32)
read
fifo_out
32
valid
clk
empty
full
read
x
fifo_out
x
WRITE
Advanced Verilog
8h
READ
© 2004 Willamette HDL, Inc.
234
Notes:
© 2004 Willamette HDL, Inc. &
Slide 234
Test-bench (block diagram)
test_multi.v
mul1.dat
multi.v
mul2.dat
op1
op2
mul3.dat
16
16
valid
X
full
clk
empty
FIFO
read
32
fifo_out
RAM
multi (op1, op2, valid, clk, read, fifo_out, full, empty);
SOLN
Advanced Verilog
© 2004 Willamette HDL, Inc.
235
Notes:
© 2004 Willamette HDL, Inc. &
Slide 235
Congratulations!
Go forth unto the Verilog world
Advanced Verilog
© 2004 Willamette HDL, Inc.
236
Notes:
© 2004 Willamette HDL, Inc. &
Slide 236
Samples and Solutions
Advanced Verilog
© 2004 Willamette HDL, Inc.
237
Notes:
© 2004 Willamette HDL, Inc. &
Slide 237
Sample Solution
// Solution to Steganographic decoder problem
//
// Message size stored in pixels 64 -> 79
// Message stored in pixels 80 -> 80+(size * 8)
//
Steganographic decoder
`define PIC_SIZE 61_080
module steg_decode;
integer rfile, i, ifs, j, k;
reg [15:0] siz;
reg [2:0] block;
reg [7:0] byte, tmp;
reg [7:0] mem[0:`PIC_SIZE -1];
reg [13*8:1] rfile_name; // Allow DOS (9.3) filenames
initial
begin
block = 3'b111;
rfile_name = "message.bmp";
// Filename
rfile = $fopen(rfile_name, "r");
// Open the file
i = $fread(mem, rfile, 0);
// Read the file into memory
ifs = $ftell(rfile);
$display("Loaded %0d pixels \n", ifs);
k = 0;
for (j=64; j<80; j=j+1)
begin
siz[k] = mem[j][0];
k = k+1;
end
// Determine message length
$display("Secret message is %0d characters long",siz);
siz = 8*(siz);
// convert to # of bits
$display("\nMessage Text follows.... \n\n");
block = 0;
for (j=80; j< siz; j=j+1) // Retrieve the message
begin
byte[block] = mem[j][0];
if (block == 7)
begin
$write("%s",byte);
end
block = block +1;
end
$display("\n\n\n");
$fclose(rfile);
$finish;
end
endmodule //
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
238
Notes:
© 2004 Willamette HDL, Inc. &
Slide 238
Sample solution - pipe.v
module pipe( input wire[7:0] d_in,
output reg[7:0] d_out,
input wire
clk);
reg [7:0] d_1, d_2, d_3;
always @ (posedge clk)
begin // doesn't matter what order reg's are in
d_1<= #5 d_in;
d_2 <= #5 d_1;
d_3 <= #5 d_2;
d_out<= #5 d_3;
end
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
239
Notes:
© 2004 Willamette HDL, Inc. &
Slide 239
Sample Solution - pipe_behav.v
module pipe( input wire[7:0] d_in,
output reg[7:0] d_out,
input wire
clk);
always @ (posedge clk)
d_out<= #125 d_in; // #120 for 3 clocks +5 more for prop
time
endmodule
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
240
Notes:
© 2004 Willamette HDL, Inc. &
Slide 240
Sample Solution - pipe_behav_var.v
(variable clock)
module pipe( input wire[7:0] d_in,
output wire[7:0] d_out,
input wire
clk);
reg [7:0] d;
assign #5 d_out = d;
always @ (d_in)
@ (posedge clk) d <= repeat (3) @ (posedge clk) d_in;
endmodule
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
241
Notes:
© 2004 Willamette HDL, Inc. &
Slide 241
Sample Solution – beh_sram
module beh_sram(ip,op,clk,rw_);
input packet ip;
output packet op;
input bit clk, rw_;
packet ret_pkt;
bit doit;
reg [31:0] mem [0:1023];
always @(posedge clk)
if(rw_ ) // read
begin
ret_pkt.data = mem[ip.addr];
ret_pkt.addr = ip.addr;
op <= #5 ret_pkt;
end
else
// write
begin
mem[ip.addr] <= ip.data;
end
endmodule
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
242
Notes:
© 2004 Willamette HDL, Inc. &
Slide 242
module baggage;
event SEA, DFW, LAX, SFO, mangled;
event bag_done, new_bag_on_cart;
Sample Solution - baggage.v
reg[7:0] flight98 [0:1023]; // memory declaration to rep plane
reg[7:0] cart;
integer i,SEA_bags,DFW_bags,LAX_bags,SFO_bags, mangled_bags;
initial $readmemh("luggage.dat",flight98); //flight98 lands
initial
begin
SEA_bags = 0;
DFW_bags = 0;
LAX_bags = 0;
SFO_bags = 0;
mangled_bags = 0;
end
initial
begin
#5; //wait for flight98 to land at time 0;
for (i=0;i<1024;i=i+1)
begin
cart = flight98[i];
// get next bag and put on cart
-> new_bag_on_cart;
// signal new one on the cart
@ (bag_done);
//wait for bag to be processed before
// putting new one on cart
end
$display ("\n # of SEA bags = %0d",SEA_bags,
"\n # of DFW bags = %0d",DFW_bags,
"\n # of LAX bags = %0d",LAX_bags,
"\n # of SFO bags = %0d",SFO_bags,
"\n # of mangled bags = %0d\n",mangled_bags);
$finish;
end
always @ (new_bag_on_cart) //wait for next bag
case (cart[3:0])
4'b0000: ->SEA;
4'b0001: ->DFW;
4'b0010: ->LAX;
4'b0011: ->SFO;
default: ->mangled;
endcase
Advanced Verilog
always @ (SEA)
begin
#5 $display ("bag number %0d -> SEA",i);
SEA_bags = SEA_bags+1;
-> bag_done;
end
always @ (DFW)
begin
#5 $display("bag number %0d -> DFW",i);
DFW_bags = DFW_bags+1;
-> bag_done;
end
always @ (LAX)
begin
#10 $display("bag number %0d -> LAX",i);
LAX_bags = LAX_bags+1;
-> bag_done;
end
always @ (SFO)
begin
#10 $display("bag number %0d -> SFO",i);
SFO_bags = SFO_bags+1;
-> bag_done;
end
always @ (mangled)
begin
#5 $display("bag number %0d is mangled!",i);
mangled_bags = mangled_bags+1;
-> bag_done;
end
endmodule
BACK
© 2004 Willamette HDL, Inc.
243
Notes:
© 2004 Willamette HDL, Inc. &
Slide 243
Sample Solution – sm_behav.v
module sm_behav;
integer addr;
reg [31:0] in_reg;
reg [7:0] ctrl_reg;
reg [31:0] mem [0:1023]; // memory
always @ (test_sm_behav.write_in_reg)
begin
case (in_reg[31:28])
0,1: ; // nop - do nothing
2: // wt_wd
begin
@ (test_sm_behav.write_in_reg)
addr = in_reg; // save off address
@ (test_sm_behav.write_in_reg)
mem[addr] <= #5 in_reg; // load mem
end
3: // wt_blk
begin
@ (test_sm_behav.write_in_reg)
addr = in_reg;
repeat (4) @ (test_sm_behav.write_in_reg)
begin
mem[addr] <= #5 in_reg;
addr = addr+1;
end
end
4: // rd_wd
begin
@ (test_sm_behav.write_in_reg)
#5 test_sm_behav.outof = mem[in_reg];
// read memory
->test_sm_behav.write_outof;
end
default:
$display ($time,,"illegal op received");
endcase
end
endmodule
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
244
Notes:
© 2004 Willamette HDL, Inc. &
Slide 244
Sample Solution
- sm_func.v
module sm_func( input wire[31:0] incoming,
output reg[31:0] outof,
input wire
clk);
event write_in_reg, write_outof;
always @ (posedge clk)// Xlation logic
begin
U1.in_reg <= #5 incoming;
#6 -> write_in_reg;
end
sm_behav U1();
// instantiate purely event-driven model
endmodule
module sm_behav;
integer addr;
reg [31:0] in_reg;
reg [7:0] ctrl_reg;
reg [31:0] mem [0:1023]; // memory
always @ (sm_func.write_in_reg)
begin
case (in_reg[31:28])
0: ; // nop - do nothing
1: // ctrl
ctrl_reg <= #5 in_reg[7:0]; // put in reg
2: // wt_wd
begin
ctrl_reg <= #5 in_reg[7:0]; // put in reg
@ (sm_func.write_in_reg)
addr = in_reg; // save off address
@ (sm_func.write_in_reg)
mem[addr] <= #5 in_reg; // load mem
end
3: // wt_blk
begin
ctrl_reg <= #5 in_reg[7:0]; // put in reg
@ (sm_func.write_in_reg)
addr = in_reg;
repeat (4) @ (sm_func.write_in_reg)
begin
mem[addr] <= #5 in_reg;
addr = addr+1;
end
end
4: // rd_wd
begin
ctrl_reg <= #5 in_reg[7:0]; // put in reg
@ (sm_func.write_in_reg)
#5 sm_func.outof = mem[in_reg]; // read memory
->sm_func.write_outof;
end
default:
$display ($time,,"illegal op(%0d) received",in_reg[31:28]);
endcase
end
endmodule
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
245
Notes:
© 2004 Willamette HDL, Inc. &
Slide 245
Sample Solution, Assertion Lab 4
fsm_ex.sv
//typedef enum [2:0] { S0 = 3'h1, S1 = 3'h2, S2 = 3'h4 } states;
typedef enum [1:0] { S0 = 2'h0, S1 = 2'h1, S2 = 2'h2 } states;
module fsm_ex( input logic clk, rst, input_sig_1, input_sig_2,
output logic a, b);
…
…
`ifdef SVA
assert_one_hot #(.width(2), .msg("state variable should be one_hot"))
A1 (.clk(clk), .reset_n(!rst), .test_expr(state));
`endif
endmodule
0 0 clk: 0 ,rst: 0 ,in1: 0 ,in2: 0 ,outa: 0 ,outb: 0
"/work/synopsys/vcs/packages/sva/assert_one_hot.v", 87: test_fsm_ex.u1.A1.assert_one_hot:
started at 100s failed at 100s, "state variable should be one_hot" Offending '$countones(test_expr)==1'
100 0 clk: 1 ,rst: 0 ,in1: 0 ,in2: 0 ,outa: 0 ,outb: 0
200 0 clk: 0 ,rst: 0 ,in1: 0 ,in2: 0 ,outa: 0 ,outb: 0
"/work/synopsys/vcs/packages/sva/assert_one_hot.v", 87: test_fsm_ex.u1.A1.assert_one_hot:
started at 300s failed at 300s, "state variable should be one_hot" Offending '$countones(test_expr)==1'
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
246
Notes:
© 2004 Willamette HDL, Inc. &
Slide 246
Sample Solution, Assertion Lab 2:
test_u_xmit.sv
sequence s_rst_sigs;
##1 (uart_out && !done);
endsequence
sequence s_rst_done;
(!sys_rst_l) [*1:$] ##1 $rose( sys_rst_l )##1 (done && !xmit) [*1:$] ##1 $rose( xmit );
endsequence
sequence s_rst_pair;
s_rst_done and s_rst_sigs;
endsequence
property p_post_rst;
@(posedge sys_clk) (!sys_rst_l) |-> s_rst_pair;
endproperty
assert_post_rst: assert property ( p_post_rst ) //$display("%m :OK!");
else $display("%m : device did not reset fully");
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
247
Notes:
© 2004 Willamette HDL, Inc. &
Slide 247
`ifdef SVA
test_u_xmit.sv
// sys_clk divider checker
Sample Solution
Assertion Lab 3:
property p_uart_sys16;
@(posedge sys_clk) $rose(uart_clk) |-> ##8 $fell(uart_clk) ##8 $rose(uart_clk);
endproperty
// xmit and data checks
sequence s_val_bit_stream(x_byte);
assert_uart_sys16: assert property (p_uart_sys16)
bit[7:0] x_byte;
else $display("%m : uart_clk should = sys_clk/16");
##8 (uart_out == 0) ##16
(uart_out == x_byte[0]) ##16
assert_val_bit_stream: assert property (p_val_bit_stream)
(uart_out == x_byte[1]) ##16
else $display("%m : uart_out bitstream incorrect");
(uart_out == x_byte[2]) ##16
(uart_out == x_byte[3]) ##16
(uart_out == x_byte[4]) ##16
(uart_out == x_byte[5]) ##16
(uart_out == x_byte[6]) ##16
(uart_out == x_byte[7]) ##16
(uart_out == 1) ##16 (uart_out == 1) ##16
(done == 1);
endsequence
property p_val_bit_stream;
@(posedge sys_clk) ($fell(done) && xmit ) |-> s_val_bit_stream(data);
endproperty
Advanced Verilog
© 2004 Willamette HDL, Inc.
248
Notes:
© 2004 Willamette HDL, Inc. &
Slide 248
// xmit and data checks
property p_xmit_hi16;
@(posedge sys_clk) $rose(xmit) |-> ##16 $fell(xmit);
endproperty
Sample Solution
Assertion Lab 3:
property p_xmit_done;
@(posedge sys_clk) $rose(xmit) |-> ##1 $fell(done) && $fell(uart_out);
endproperty
// Serial protocol checkers
property p_xmit_nc_data;
@(posedge sys_clk) $rose(xmit) |=> $stable(data) [*1:$] ##1 $fell(xmit);
endproperty
property p_done_175;
@(posedge sys_clk) ($fell(done) && sys_rst_l) |-> ##175 $rose(done);
endproperty
// assertions
assert_xmit_hi16: assert property (p_xmit_hi16) //$display("%m :OK!");
else $display("%m : Signal xmit should stay hi for 16 sys_clks");
assert_xmit_done: assert property (p_xmit_done) //$display("%m :OK!");
else $display("%m : Posedge xmit should take done and uart_out low.");
assert_xmit_nc_data: assert property (p_xmit_nc_data) //$display("%m :OK!");
else $display("%m : data should not change while xmit asserted");
assert_done_175: assert property (p_done_175) //$display("%m :OK!");
else $display("%m : Byte transmission (done low) should take 175 sys_clk");
Advanced Verilog
© 2004 Willamette HDL, Inc.
249
Notes:
© 2004 Willamette HDL, Inc. &
Slide 249
Sample solution:
Assertion Lab3
// uart_clk checkers
//####################
//
//
sequence s_val_bit_stream_uart_clk(x_byte);
bit[7:0] x_byte;
assert_xmit_hi1: assert property (p_xmit_hi1)
(uart_out == 0) ##1
else $display("%m : Signal xmit should stay hi for 1 uart_clk");
(uart_out == x_byte[0]) ##1
(uart_out == x_byte[1]) ##1
assert_done_11: assert property (p_done_11)
(uart_out == x_byte[2]) ##1
else $display("%m : Byte transmission (done low) should take 11 uart_clk");
(uart_out == x_byte[3]) ##1
assert_val_bit_stream_uart_clk: assert property (p_val_bit_stream_uart_clk)
(uart_out == x_byte[4]) ##1
else $display("%m : uart_out bitstream incorrect");
(uart_out == x_byte[5]) ##1
(uart_out == x_byte[6]) ##1
`endif
(uart_out == x_byte[7]) ##1
(uart_out == 1) ##1 (uart_out == 1) ##1
(done == 1);
endsequence
property p_xmit_hi1;
@(posedge uart_clk) $rose(xmit) |-> ##1 $fell(xmit);
endproperty
property p_done_11;
@(posedge uart_clk) ($fell(done) && sys_rst_l) |-> ##11 $rose(done);
endproperty
property p_val_bit_stream_uart_clk;
@(posedge sys_clk) ($fell(done) && xmit ) |-> s_val_bit_stream_uart_clk(data);
endproperty
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
250
Notes:
© 2004 Willamette HDL, Inc. &
Slide 250
Advanced Verilog
© 2004 Willamette HDL, Inc. &
`define RTL_FSM
© 2004 Willamette HDL, Inc.
////////////////////////////////////////////////////////////////////
// ILLEGAL OP task
//
///////////////////////////////////////////////////////////////////
task ill_op;
begin
$display("TB: Illegal op request");
#5 into = {4'b0101,28'h0}; // op word
end
endtask
// WT_WD task
//
/////////////////////////////////////////////////////////////////////
task wt_wd;
input [31:0] addr,data;
begin
$display("TB: Single Word write of %0h to address %0h \n", data,
addr);
#5 into = {4'b0010,28'h0}; // op_word
@ (posedge clk)
#5 into = addr;
@ (posedge clk)
#5 into = data;
end
endtask
// NOP task
//
/////////////////////////////////////////////////////////////////////
task nop;
begin
$display("TB: Sending NOP \n");
#5 into = {4'b0000,28'h0}; // op_word
end
endtask
reg [31:0] into, outof;
reg rst, clk;
wire [31:0] out_wire, dat;
wire [9:0] addr;
module test_sm;
// Header//
/////////////////////////////////////////////////////////////////////
//
//
// Copyright Willamette HDL Inc.
//
//
//
//
// Name:
test_func_sm
//
// Description:
Test fixture for functional level state machines //
// Creation Date: 1/15/2001
//
// Version:
1.2b
//
// Author:
Tim Corcoran
//
//
//
`define CLK_TGL 10
/////////////////////////////////////////////////////////////////////
`define RTL_LIB dir=../rtl_lib libext=.v
`timescale 1ns/100ps
`define BEH_LIB dir=../beh_lib libext=.v
`include "test_choices"
Configuration Exercise – test_sm.v
251
Notes:
Slide 251
Advanced Verilog
© 2004 Willamette HDL, Inc. &
© 2004 Willamette HDL, Inc.
end
endtask
// RD_WD task
//
////////////////////////////////////////////////////////////////////
/
// Input 0: address to be read
//
////////////////////////////////////////////////////////////////////
task rd_wd;
input [31:0] addr, exp;
begin
$display("TB: Single word read from address %0h, expect %0h\n",
addr, exp);
#5 into = {4'b0100,28'h0}; // op_word
@ (posedge clk)
#5 into = addr;
@ (posedge clk)
#5 into = 0; // nop
repeat(5) @ (negedge clk);
if (outof !== exp)
$display("TB: %0t Read error. expected %0h, received %0h\n",
$stime, exp, outof);
else
$display("TB: Time %0t: Correct data \(%0h\) returned\n",$stime,
outof);
// WT_BLK task
//
////////////////////////////////////////////////////////////////////
/
// Input 0: address to be written
//
// Input 1: data to write
//
////////////////////////////////////////////////////////////////////
task wt_blk;
input [31:0] addr,data;
begin
$display("TB: Block write of \(%0h - %0h\) to addresses \(%0h %0h)\n", addr, (addr+3), data, (data+3));
#5 into = {4'b0011,28'h0}; // op_word
@ (posedge clk)
#5 into = addr; // send address
repeat (4)
begin
@ (posedge clk)
#5 into = data; // send data
data = data +1; // change the data word
end
end
endtask
test_sm.v Part 2
252
Notes:
Slide 252
Advanced Verilog
© 2004 Willamette HDL, Inc. &
////////////////////////////////////////////////////////////////////
// Test sequence
//
///////////////////////////////////////////////////////////////////
initial
begin
into = 0; // set to nop to start off
rst = 0;
#5 rst = 1;
#20 rst = 0;
repeat(3) @ (posedge clk); // wait for 3 clocks
@ (posedge clk) wt_wd('h100,'haa);
@ (posedge clk) wt_wd('h30,'hbb);
@ (posedge clk) wt_blk('h40,'ha10);
@ (posedge clk) rd_wd('h100,'haa);
@ (posedge clk) rd_wd('h30,'hbb);
@ (posedge clk) rd_wd('h40,'ha10);
@ (posedge clk) rd_wd('h41,'ha11);
@ (posedge clk) rd_wd('h42,'ha12);
@ (posedge clk) rd_wd('h43,'ha13);
@ (posedge clk) ill_op;
@ (posedge clk) nop;
#100 $stop;
end
always @ (outof) // any change of outof
$display ("TB: Time: %0t, outof = %h\n",$stime,outof);
////////////////////////////////////////////////////////////////////
// Output checking
//
///////////////////////////////////////////////////////////////////
always @(posedge clk)
outof = #5 out_wire; // put output in register
////////////////////////////////////////////////////////////////////
// System clock generator
//
///////////////////////////////////////////////////////////////////
initial
begin
clk = 0;
rst = 1;
forever
#`CLK_TGL clk = !clk;
end
////////////////////////////////////////////////////////////////////
// ILLEGAL OP task
//
///////////////////////////////////////////////////////////////////
task ill_op;
begin
$display("TB: Illegal op request");
#5 into = {4'b0101,28'h0}; // op word
end
endtask
test_sm.v Part 3
© 2004 Willamette HDL, Inc.
253
Notes:
Slide 253
////////////////////////////////////////////////////////////////////
`define//
CLK_TGL 10
// Instantiations
//
`define//
GAT_LIB dir=../gat_lib libext=.v file=../gat_lib/class_lib
//NOTE
`define//
RTL_LIB dir=../rtl_lib libext=.v
//
For GATE-level Sim: sm_seq and sm from gat_lib,
`define//
BEH_LIB dir=../beh_lib libext=.v
//
beh_sram from beh_lib
//
//
//
`define//
GAT_FSM
//
For RTL-level Sim: sm_seq and sm from rtl_lib,
//
beh_sram from beh_lib
//RTL_FSM
//`define
//
//BEH_FSM
//`define
//
Behavioral Sim requires only sm_func from beh_lib
//
//
//
///////////////////////////////////////////////////////////////////
`ifdef GAT_FSM
initial $display("Configuring for Gate-level Sim");
`uselib `GAT_LIB
sm_seq sm_seq0( .into(into), .outof(out_wire), .rst(rst), .clk(clk),
.mem(dat), .addr(addr), .rd_(rd_), .wr_(wr_));
`uselib `BEH_LIB
beh_sram
sram_0(.clk(clk), .dat(dat), .addr(addr), .rd_(rd_), .wr_(wr_));
`endif
`ifdef RTL_FSM
initial $display("Configuring for RT-level Sim");
`uselib `RTL_LIB
sm_seq sm_seq0( .into(into), .outof(out_wire), .rst(rst), .clk(clk),
.mem(dat), .addr(addr), .rd_(rd_), .wr_(wr_));
`uselib `BEH_LIB
beh_sram
sram_0(.clk(clk), .dat(dat), .addr(addr), .rd_(rd_), .wr_(wr_));
`endif
`ifdef BEH_FSM
initial $display("Configuring for Behavioral-level Sim");
`uselib `BEH_LIB
sm_func sm_seq0( .incoming(into), .outof(out_wire), .rst(rst), .clk(clk));
`endif
endmodule
test_sm.v
Part 4
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
254
Notes:
© 2004 Willamette HDL, Inc. &
Slide 254
/* fifo_monitor.v - sample solution for monitor exercise */
module fifo_monitor ( input [7:0] data_in,
input
read, write, empty, full,
input [7:0] data_out,
input
w_clk, r_clk);
Sample
solution:
fifo_monitor.v
always @ (posedge w_clk)
if (full && write) // check for write of a full fifo
$display ("\n*MON* time=%0d protocol error: write asserted while full asserted\n",$time);
always @ (posedge r_clk)
if (empty && read) // check for read of an empty fifo
$display ("\n*MON* time=%0d protocol error: read asserted while empty asserted\n",$time);
specify
$setuphold (posedge w_clk,data_in,3,3);
$setuphold (posedge w_clk,write,3,3);
$setuphold (posedge r_clk,read,3,3);
$period (posedge w_clk,20);
endspecify
endmodule
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
255
Notes:
© 2004 Willamette HDL, Inc. &
Slide 255
Advanced Verilog
© 2004 Willamette HDL, Inc. &
© 2004 Willamette HDL, Inc.
endmodule
// Generate test-files
integer a,b,c,d;
reg[15:0] j;
reg[31:0] k;
initial
begin
a = $fopen("mul1.dat");
for(j = 0; j<1025; j=j+1) begin
k = ((j+0)*(1024-j));
if ((j+0)==(1024-j))
;//$fwrite(a,"%h%h%h\n",j+16'b0,16'd1024-j,k+32'd1);
else
$fwrite(a,"%h%h%h\n",j+16'b0,16'd1024-j,k); end
$fclose(a);
b = $fopen("mul2.dat");
for(j = 0; j<1025; j=j+1) begin
k = ((j+1024)*(2048-j));
if ((j+0)==(1024-j))
;//$fwrite(b,"%h%h%h\n",j+16'd1024,16'd2048-j,k+32'd1);
else
$fwrite(b,"%h%h%h\n",j+16'd1024,16'd2048-j,k); end
$fclose(b);
c = $fopen("mul3.dat");
for(j = 0; j<1025; j=j+1) begin
k=((j+2048)*(3072-j));
if ((j+0)==(1024-j))
;//$fwrite(c,"%h%h%h\n",j+16'd2048,16'd3072-j,k+32'd1);
else
$fwrite(c,"%h%h%h\n",j+16'd2048,16'd3072-j,k);end
$fclose(c);
d = $fopen("mul4.dat");
for(j = 0; j<32; j=j+1) begin
for(jk = 0; jk<32; jk=jk+1) begin
k = j*jk;
$fwrite(c,"%h%h%h\n",j,jk,k);
end
end
$fclose(d);
$finish;
end
module stim_files;
Sample
solution:
stim_gen.v
BACK
256
Notes:
Slide 256
multi.v- test exercise
`define DELAY 3
module multi (input wire[15:0] op1, op2,
input wire
valid, clk, read,
output wire[31:0] fifo_out,
input wire
full, empty);
reg[32:0] ma [4:0];
integer i;
wire [31:0] prod;
wire v_out;
assign {v_out,prod} = ma[0];
`protect
function integer mul32;
input[15:0] o1,o2;
integer prod;
begin
if (o1 == o2)
mul32 = (o1*o2)+1;
else
mul32 = o1*o2;
end
endfunction
`endprotect
module mult_fifo( data_in, read, write, empty, almost_full,
data_out, clk);
input [31:0] data_in;
input read, write, clk;
output empty, almost_full;
output [31:0] data_out;
reg [4:0] head,tail; // fifo reg's
integer e_count; // fifo reg's
reg [31:0] dfifo [0:31]; // fifo
reg [31:0] data_out;
wire almost_full = e_count >= 27;
wire full = e_count == 32;
wire empty = !e_count;
// deliberately add 1 to a square op.
initial
begin
for(i=0; i<5; i=i+1) ma[i] = 0;
end
always @(posedge clk)
begin
ma[0] <= #`DELAY ma[1];
ma[1] <= #`DELAY ma[2];
ma[2] <= #`DELAY ma[3];
ma[3] <= #`DELAY ma[4];
ma[4] <= #`DELAY {valid, mul32(op1,op2)};
end
mult_fifo f1( prod, read, v_out, empty, full,
fifo_out, clk);
endmodule
/**** init registers */
initial
begin
head = 0;
tail = 0;
e_count = 0;
end
/*** the write ***/
always @ (posedge clk)
if (write & !full)
begin
dfifo[head] <= #`DELAY data_in;
#`DELAY head = head + 1;
e_count = e_count + 1;
end
else if (write & full)
$display ("\n*FF* Attempted to write a full fifo\n");
/*** the read ***/
always @ (posedge clk)
if (read & !empty)
begin
data_out <= #`DELAY dfifo [tail];
#`DELAY tail = tail + 1;
e_count = e_count - 1;
end
else if (read & empty)
$display ("\n*FF* Attempted to read an empty fifo\n");
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
257
Notes:
© 2004 Willamette HDL, Inc. &
Slide 257
`define DELAY 3
`define TRUE 1'b1
`define FALSE 1'b0
Sample solution: test_multi.v
module test_mult;
reg[15:0] op1, op2;
reg[63:0] test_mem [0:1023];
reg valid, clk, read;
wire full, empty;
wire[31:0] data_out;
event read_mem;
integer r_offset, w_offset;
multi m1 (op1, op2, valid, clk, read, data_out, full, empty);
initial
begin
@ (read_mem) $readmemh("mul1.dat",test_mem);
$display("loading mul1.dat");
@ (read_mem) $readmemh("mul2.dat",test_mem);
$display("loading mul2.dat");
@ (read_mem) $readmemh("mul3.dat",test_mem);
$display("loading mul3.dat");
@ (read_mem) $readmemh("mul4.dat",test_mem);
$display("loading mul4.dat");
// repeat
@ (read_mem) $readmemh("mul1.dat",test_mem);
$display("loading mul1.dat");
@ (read_mem) $readmemh("mul2.dat",test_mem);
$display("loading mul2.dat");
@ (read_mem) $readmemh("mul3.dat",test_mem);
$display("loading mul3.dat");
@ (read_mem) $readmemh("mul4.dat",test_mem);
$display("loading mul4.dat");
end
initial
begin
read = 0;
valid = 0;
op1 = 0;
op2 = 0;
r_offset = 0;
w_offset = 0;
clk = 0;
forever #20 clk = !clk;
end
task block_test;
fork
vect_apply;
vect_check;
join
endtask
initial
begin
repeat(5) @(negedge clk);
-> read_mem;
block_test;
// Load test-vector array
r_offset = 1; $display("\n2 writes/read"); // slow down reads by half
-> read_mem;
// re-Load test-vector array
block_test;
w_offset = 1; $display("\n1:1 writes & reads"); // slow writes by half
-> read_mem;
// re-Load test-vector array
block_test;
r_offset = 0;
w_offset = 1; $display("\n2 reads/write"); // fast reads, slow writes
-> read_mem;
// re-Load test-vector array
block_test;
w_offset = 0; $display("\n1:1 writes & reads"); // back to normal
-> read_mem;
// re-Load test-vector array
block_test;
w_offset = 1; $display("\n2 reads/write"); // slow writes by half
-> read_mem;
// re-Load test-vector array
block_test;
-> read_mem;
block_test;
// re-Load test-vector array
-> read_mem;
block_test;
// re-Load test-vector array
repeat(5) @(negedge clk);
$stop;
end
endmodule
Advanced Verilog
© 2004 Willamette HDL, Inc.
258
Notes:
© 2004 Willamette HDL, Inc. &
Slide 258
Sample solution: test_multi.v
(part2 - the tasks)
task vect_apply; // Apply vector file stimulus
reg[63:0] tmp;
integer cnt;
begin
cnt = 0;
forever @(negedge clk)
begin
if (!full)
begin
valid = 1;
tmp = test_mem[cnt];
op1 = tmp[63:48];
op2 = tmp[47:32];
cnt = cnt+1;
@(posedge clk);
#3 valid = 0; // shut it off
end
if (cnt >= 1024)
disable vect_apply;
repeat(w_offset) @ (posedge clk);
end
end
endtask
task vect_check; // Check vector file results
reg[63:0] tmp;
integer cnt;
begin
cnt = 0;
forever @(negedge clk)
begin
if (!empty)
begin
read = 1;
@(posedge clk);
tmp = test_mem[cnt];
#5 if (data_out != tmp[31:0])
$display("Error: Op1:%0d * Op2:%0d != %0d (%0d)",
tmp[63:48],tmp[47:32],tmp[31:0],data_out);
cnt = cnt+1;
read = 0;
end
if (cnt >= 1024)
disable vect_check;
repeat(r_offset) @ (posedge clk);
end
end
endtask
BACK
Advanced Verilog
© 2004 Willamette HDL, Inc.
259
Notes:
© 2004 Willamette HDL, Inc. &
Slide 259
This page was intentionally left blank.
Advanced Verilog
© 2004 Willamette HDL, Inc.
260
Notes:
© 2004 Willamette HDL, Inc. &
Slide 260
Customer Support
© 2005 Synopsys, Inc. All Rights Reserved
Customer Support
© 2005
20041220
CS-1
Synopsys Support Resources
1. Build Your Expertise:
Customer Education Services
www.synopsys.com
Workshop schedule and registration
Download materials (SolvNet id
required)
2. Empower Yourself:
solvnet.synopsys.com
Online technical information and
access to support resources
Documentation & Media
3. Access Synopsys Experts:
Support Center
CS- 2
Customer Support
© 2005
CS-2
SolvNet Online Support Offers
Immediate access to the
latest technical
information
Thousands of expertauthored articles, Q&As,
scripts and tool tips
Enter-a-call online
Support Center access
Release information
Online documentation
License keys
Electronic software
downloads
Synopsys
announcements (latest
tool, event and product
information)
CS- 3
Customer Support
© 2005
CS-3
SolvNet Registration is Easy
1. Go to solvnet.synopsys.com/
ProcessRegistration
2. Pick a username and password.
3. You will need your “Site ID” on
the following page.
4. Authorization typically takes
just a few minutes.
CS- 4
Customer Support
© 2005
CS-4
Support Center: AE-based Support
Industry seasoned Application Engineers:
50% of the support staff has > 5 years applied experience
Many tool specialist AEs with > 12 years industry experience
Access to internal support resources
Great wealth of applied knowledge:
Service >2000 issues per month
Remote access and debug via ViewConnect
Contact us:
Fastest access
Web
“Enter A Call” from solvnet.synopsys.com
E-Mail
Phone
support_center@synopsys.com
1-800-245-8005
Business Hours: Monday - Friday, 7am - 5:30pm PST
CS- 5
Customer Support
© 2005
CS-5
Other Technical Sources
Application Consultants (ACs):
Tool and methodology pre-sales support
Contact your Sales Account Manager for more information
Synopsys Professional Services (SPS) Consultants:
Available for in-depth, on-site, dedicated, custom consulting
Contact your Sales Account Manager for more details
SNUG (Synopsys Users Group):
www.snug-universal.org
CS- 6
Customer Support
© 2005
CS-6
Summary: Getting Support
Customer Education Services
SolvNet
Support Center
SNUG
CS- 7
Customer Support
© 2005
CS-7
This page was intentionally left blank.
Customer Support
© 2005
CS-8
To provide you with the highest quality training and a meaningful
learning experience, your feedback is used to continuously update the
Customer Education course content and training methodologies. Please
take a moment to express if your training needs were met. Thank you!
Course Evaluation
Course Title
Course Start Date
Location
Instructor
Your Name (print)
Company (print)
E-mail (optional)
Phone (optional)
Yes
Did you meet the pre-requisites prior to attending class?
No
Strongly
Agree
Agree
Neutral
Disagree
5
4
3
2
Strongly
Not
Disagree Applicable
Course Content and Materials
1. The course content met my expectations
2. The course met the stated objectives
3. The course length was long enough to cover the content
4. The time allotted for labs was long enough
5. The lab exercises helped in learning the course material
6. The visual aids used by the instructor were helpful
Instructor
7. The instructor was knowledgeable in the subject area
8. The instructor effectively used class time to enable me to
learn the key concepts
9. The instructor encouraged students to ask questions
10. Student questions were answered clearly and completely
11. The instructor was available and helpful during labs
Facilities and Registration
12. The quality of the facilities was conducive to learning
13. Classroom equipment was an effective tool in my learning
14. Registration process made it easy to enroll
Would you recommend this course to others?
Yes
5
No
0
Please provide contact information for any one you feel would benefit from one of our courses.
Name
Name
Phone Number
Phone Number
e-mail
e-mail
Customer Education Services
1
0
Continued Course Evaluation (continued)
What Units were the most valuable, least valuable for you and why?
Most:
Least:
What recommendations can you suggest for course improvement: materials and or presentation?
What topics require more coverage in class? Less coverage?
More:
Less:
Should the lab time be lengthened or shortened? Any lab in particular?
Should the course be made longer or shorter? Any unit in particular?
What suggestions would you offer the instructor to improve his/her delivery of the course?
What suggestions do you have for improving the classroom environment?
What follow up course(s) would you like to see?
What suggestions do you have that would make it easier to do business with us?
Your comments are sincerely appreciated. Please return the completed form to the instructor. Thanks!
8/01
Customer Education Services
Download