• Like
  • Save
Sytem verilog golden reference guide
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Sytem verilog golden reference guide

  • 3,106 views
Published

Sytem verilog golden reference guide

Sytem verilog golden reference guide

Published in Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
3,106
On SlideShare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
0
Comments
1
Likes
9

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. System Veri log GOLDEN REFERENCE GUIDE A concise guide to SystemVerilog IEEE Std 1800™-2005 /�DOULOS
  • 2. SystemVerilog Golden Reference Guide Version 4.0, January 2006 Copyrlghl@1995-2006 by Doulos Ltd. All Rights Reserved The information contained herein is the property of Doulos Ltd and is supplied without liability lor errors or omissions. No part may be used. stored, transmitled or reproduced in any form or medium without the writlen permission or Doulos ltd. Doulos"' is a registered trademark of Doulos ltd. 1800r"' is a trademark and IEEE" is a registered lrademark. Verilog-XLTM is a trademark and Verilog" a registered trademark of Cadence Design Systems Inc. All other trademarks are acknowledged as the property of their respective holders. First published by Doulos Ltd 2006 ISBN 0-9547345-3-X Doulos ltd. Church Hatch 22 Market Place Ringwood Hampshire BH241AW UK Tel +44 (0)1425 471223 Fax +44 (0)1425 471573 Email: info@doulos.com Web: htlp://WWI.doulos.com
  • 3. Contents Page Preface ............................ ....................................................................... Using This Guide .................................. ...... . .... ..................................... A Brief Introduction To SystemVerilog Syntax Summary ................................................................................. Alphabetical Reference Compiler Directives ...................................................................... .......................................................................... 6 8 16 31 339 ......................................................... 353 .......................................................................... . ....................... 395 System Tasks And Functions Index .............................................. 5
  • 4. Preface The SystemVerilog Golden Reference Guide is a compact quick reference guide to the SystemVerilog language as defined in the IEEE Standard Verilog Language Reference Manual, IEEE Sid 1 364-2005 and IEEE Standard for SystemVerilog-Unified Hardware Design, Specification, and Verification Language, IEEE Sid 1800-2005. The intention of the guide is to provide a handy reference. It does not offer a complete, formal description of SystemVerilog. Rather, it offers answers to the questions most often asked during the practical application of SystemVerilog, in a convenient and concise reference format. It is hoped that this guide will help you understand and use SystemVerilog more effectively. This guide is not intended as a substitute for a full training course. and will probably be of most use to those who have received some training. The SystemVerilog Golden Reference Guide was developed to add value to the Doulos range of Training courses, and to embody the knowledge gained through Doulos methodology and consulting activities. For more information about these. please visit the web-site http://www.doulos.com. You will find a set of SystemVerilog tutorials at http://www.doulos.com/knowhow CopyooghlC 11195-2006 by Doulo• Lid 5
  • 5. Using This Guide The SystemVerilog Golden Reference Guide comprises a Brief Introduction to SystemVerilog, a Syntax Summary, the Alphabetical Reference sections and an Index. If you are new to SystemVerilog, you should start by reading A Brief Introduction to SystemVerilog, which follows. The major new areas of SystemVerilog are introduced and explained in more detail in a number of tutorials, which you will find at http://www.doulos.com/knowhow: Data types RTL design • Interfaces • Assertion-based verification • Testbench automation and constraints • The Direct Programming Interface (DPI) Clocking Classes The main body of this guide is divided into three parts: SystemVerilog Alphabetical Reference, Compiler Directives and System Tasks and Functions. Each of these is organised alphabetically into sections and each section is indexed by a key term, which appears prominently at the top of each page. Often you can find the information you want by flicking through the guide looking for the appropriate key term. If that fails, there is a full index at the back. New In SystemVerllog This guide covers the full SystemVerilog language, which is based on Verilog2005. In each section in the main alphabetical reference, the main changes introduced in SystemVerilog are highlighted using the following notation. � This feature was added in SystemVerilog Where there is no such indication, the feature is the same as in Verilog-2005. You will find information about the differences between Verilog-2001 and Verilog-2005, and between the different versions of SystemVerilog in the article SystemVerilog Versions. The Index Bold index entries have corresponding pages in the main body of the guide. The remaining index entries are followed by a list of appropriate page references. 6 Cop)'ighl 0 1995·2006 by Doolos Lid.
  • 6. Key To Notation Used To Define SystemVerllo Syntax g The syntax definitions are written to look like examples wherever possible, but it has been necessary to introduce some extra notation. In brief, square brackets [] enclose optional items, three dots ... means repetition, and curly brackets 0 enclose comments. ltalicNames represent parts of the syntax defined elsewhere. A full description of the notation follows: Curly brackets {} enclose comments that are not part of the SystemVerilog syntax being defined, but give you further information about the syntax definition. Bold curly brackets {} are part of the SystemVerilog syntax (e.g. the concatenation operator). Syntax enclosed in square brackets [ ] is optional. Bold square b rackets ( ) are part of the SystemVerilog syntax (e.g. vector range). . .. means zero or more repetitions of the preceding item or line, or means a list, as follows: Item ... means zero or more repetitions of the Item. , ... means repeat in a comma separated list (e.g. A, B, C) ; .. . means repeat in a semicolon separated list. Words in lower-case letters are SystemVerilog keywords (e.g. module). Capitalised Words (not in italics) are SystemVerilog identifiers, i.e. user defined names that are not keywords (e.g. lnstanceName). Italic Words are syntactic categories, i.e. the name of a syntax definition given in full elsewhere. A syntactic category can be either defined on the same page, defined on a separate page, or one of the special categories defined below. Italics = indicates a syntactic category which is defined and used on the same page. In each article in the alphabetical reference section, the heading "Where" immediately follows the "Syntax" heading. This tells you where the construct can be used. For example. $unit module-<HERE>-endmodule i n terface-<H ERE>-end in terface means that the construct being described can be in the compilation unit (i.e. outside any modules etc. -see the articles Name and Compilation Unit), in modules and interfaces, but not in programs, for example. Copyright C 1995·2006 by Doulos Ltd. 7
  • 7. A Brief Introduction To System Veri log The following paragraphs give a brief technical introduction to SystemVerilog suitable for the reader with no prior knowledge of the language. What Is SystamVarllo ? g SystemVerilog (IEEE Std. 1 800-2005) is set of extensions to the Verilog Hardware Description Language (IEEE Std. 1 364-2005). SystemVerilog is used to simulate and verify the functionality of digital electronic circuits at levels of abstraction ranging from system level, stochastic and pure behaviour down to gate and switch level, and is also used to synthesize (i.e. automatically generate) gate level descriptions from more abstract (Register Transfer Level) descriptions. SystemVerilog is commonly used to support the high level design (or language-based design) process, in which an electronic design is verified by means of thorough simulation at a high level of abstraction before proceeding to detailed design using automatic synthesis tools. SystemVerilog is also widely used for gate level verification of ICs, including simulation, fault simulation and timing verification. g A Brief Histo of Verllo and S stemVerilo ry y g The Verilog HDL was originally developed together with the Verilog-XL simulator by Gateway Design Automation, and introduced in 1 984. In 1989 Cadence Design Systems acquired Gateway, and with it the rights to the Verilog language and the Verilog-XL simulator. In 1990 Cadence placed the Verilog language (but not Verilog-XL) into the public domain. A not-for-profit organisation, Open Verilog International (OVI) was formed with the task of taking the language through the IEEE standardisation procedure, and Verilog became an IEEE standard in 1 995. In 2000, OVI combined with VHDL International to form Accellera. In 2001 the ilog, generally known as Verilog-2001, IEEE released a revised version of Ver with the standard number IEEE Std. 1 364-2001. This version incorporated many useful improvements. In 2002 Accellera introduced extensions for a higher level of abstraction for modelling and verification with the Verilog HDL, under the name SystemVerilog 3.0. An extended version - SystemVerilog 3.1 - and a further revision - SystemVerilog 3.1 a - were introduced in 2003 and 2004 respectively. SystemVerilog 3.1 a formed the basis for the IEEE standardisation of SystemVerilog, resulting in IEEE Sid 1800-2005, which is the subject of this guide. At the same time, Verilog itself was revised to resolve some incompatibilities and inconsistencies with SystemVerilog. This revision of Verilog is IEEE Sid 1 364-2005. 8 Copynght C 1995-2006 by Doulos Ltd
  • 8. A Brief Introduction to SystemVerllog g Sources of SystemVerllo The SystemVerilog extensions come from a number of sources: A subset of the proprietary Superlog language, which was donated by Co-Design Automation (now part of Synopsys); Veralite (testbench) and the DirectC, assertions and coverage APis, which were all donated by Synopsys; Accellera PSL 1 .0 assertions (which were in turn derived from IBM's Sugar language); and proposals from the Accellera SystemVerilog committee. g g Summa of SystemVerilo Extensions to Verilo ry SystemVerilog adds important new constructs to Verilog, including: New data types: byte, shortint. int, longint, bit, logic, string, chandle. Typedef, struct, union, tagged union, enum Dynamic and associative arrays; queues Classes Automatic/static specification on a per variable instance basis Packages and support for Compilation Units Extensions to Always blocks for modelling combinational, clocked processes • latched or Jump Statements (return, break and continue) Extensions to fork-join disable and wait to support dynamic processes. , Interfaces to encapsulate communication Clocking blocks to support cycle-based methodologies Program blocks for describing tests Randomization and constraints for random and directed-random verification • Procedural and concurrent assertions and Coverage for verification Enhancements to events and new Mailbox and Semaphore built-in classes for inter-process communication. The Direct Programming Interface, which allows C functions to be called directly from SystemVerilog (and vice versa) without using the PLI. • Assertions and Coverage Application Programming Interfaces (APis) and extensions to the Verilog Procedural Interface (VPI) - details of these are outside the scope of the SystemVerilog Golden Reference Guide Cq>yright C> 1995-2006 by Dootos Ltd 9
  • 9. A Brief Introduction to SystemVerilog The Language In this section as in the rest of the guide, words given in Capitalised Italics are technical terms whose definitions may be found in the main body of this guide. Source Files SystemVerilog source code is written in one or more text files. These files are grouped into Compilation Units in a tool-specific way. The default is that each file is a separate compilation unit. The source text includes the declaration and use of Modules, Programs, User­ Defined Primitives, Interfaces and Packages, as well as Compilation Unit declarations outside any named Modules etc. Comments may be started with//, ending at the end of the line, or block comments I" ... *I may be used. Hierarchy A hierarchical portion of a hardware design is described in SystemVerilog by a Module. The Module defines both the interface to the block of hardware (i.e. the inputs and outputs) and its internal structure or behaviour. module M (inp ul A, B, Clk, output r); II Functional description goes here endmodule The communication between blocks may be encapsulated in Interfaces. Interfaces allow design refinement from system-level down to RTL and structural levels, totally independent from modules. A number of primitives, or Gates, are built into the SystemVerilog language. They represent basic logic gates (e.g. and, or). In addition User Defined Primitives (UDPs) may be defined. Programs are used to describe simulation tests. Programs are instanced in modules (typically in the top-level testbench), but are themselves leaves in the hierarchy. Like modules, programs may have ports. The structure of an electronic circuit can be described by making Instances of Modules and Primitives (UDPs and Gales) within a higher level Module, and connecting the Instances together using Nets and Variables. These represent simple electrical connections, a wire or a bus. Communication between Modules can be encapsulated using Interfaces. At its simplest, an Interface is a bundle of Nets or Variables. Interfaces may also encapsulate functionality. A list of Port connections is used to connect Nets, Variables and Interface Instances to the Ports of a Module, Interface or Primitive Instance, where a Port represents a pin. 10 COf•jTight C 199�2000 by Doulos Lid.
  • 10. A Brief Introduction to SystemVerllog module AOI ( i nput A, B, C, output r); wire W1, W2; and (1"11 , A, B ) ; assign F � II C); (W2, W1, or Instance of "and" gate II Instance of "or" gate II !W2; Continuous assignment endmodule Nets and Variables SystemVerilog has two classes of data type: Nets and Variables. Nets can be used to form connections and be the target of continuous assignments (Assign). They may have multiple drivers. Variables can also be used to form connections and be the target of continuous assignments. They can also be the target of Procedural Assignments in a process (Initial or Always). If a Variable is driven by a continuous assignment or by being connected to an output Port, it may not be driven or assigned values in any other way. However, a given variable may be assigned values from more than one process. Literal Values Integer literals may be specified using binary, octal, decimal or hexadecimal notation. The size (number of bits) and signing (signed or unsigned) may bo given. Underscores L) may be included to aid readability. SystemVerilog also includes real, lime, string, array and struct literals. 23 II A decimal integer (32 bits) -15 II A negative decimal number 8'bll10 0001 II B'so77 II An 8-bit unsigned binary number An 8-bit signed octal number 'hf[ 11 An unsized, unsigned hexadecimal number 16'bz II lx II lOns II Time literal I { 0 , 1, 21 II Array literal - assignment pattern II Struct literal - assignment pattern String literal (8 bits/char = 40 bits) 1 {0, "llcllo", 2.3) 11Hellon II Same as 16'bzzzz_zzzz_zzzz_zzzz Sets all bits to x Data Types SystemVerilog includes a number of integer data-types. These may be signed or unsigned. These are a hybrid of both Verilog and C data types, to provide for accurate translations to and from C. The 2-state (01 1 ) integer types are: bit, byte, shortint, inl, and longinl. The 4state (0, 1 , X, Z) integer types are: logic, reg, integer and time. Of these, bit, Cop)Tight 0 1 �S.2006 by Doutos Ltd 11
  • 11. A Brief Introduction to SystemVerilog logic and reg have a user-defined size (number of bits). The others have a fixed size. Types logic and reg are identical; in SystemVerilog, logic is preferred. The non-integer Variable data types are shortreal, real and realtime. For a better encapsulation and compactness of code Structs, Unions and Enum types may be used. User defined types may be defined with Typedef. Both Nets and Variables may have data types. Multi-dimensional arrays of Nets and Variables may be defined. II Integers shortint s ; II byle un9igncd b ; 1 6-bit, 2-state, signed II bit [9: 0 ] blO; reg signed [ 7 : 0) r ; II 8-bit, 2-state, unsigned I I 1 O-bit, 2-state, unsigned I I 8-bit, 4-state, signed Arrays logic [3:0) i[l:lO); integer a [ O : I S ] ; II Array of 1 D 4-bit, 4-state II Array of 16 32-bit, 4-state I I Anonymous Struct s t rucl I bit [ 7 : 0 ) Opcode; b i t [ 2 3 : 0 ] Addres s ; Reg; I I Anonymous enum cnum { red, yellow, green} LighL; User-defined type typedef enum START, STOP, WAIT} StaLcType; SLa LeType S L a L e , NextState; II Classes To support object-oriented programs, Classes may be defined. A class has properties (i.e. data members) and methods (i.e. Function and Task members). A Class may be extended to form a new Class (single inheritance). A Class is in effect a user-defined data type. Classes may be instanced to create objects. To support directed-random verification, Class Variables may be declared Random. Classes may also include Constraints, which direct the generation of random values. 12 Copynght o 1ggs 2006 by 0oo1os Ltd
  • 12. A Brief Introduction to SystemVerilog Behaviour The behaviour of an electronic circuit is described using Initial and Always constructs and continuous assignments (Assign). Constructs such as Always_comb, Always_ff and Always_latch are used to describe design intent for synthesisable circuits. Along with UDPs and Gates these represent the leaves in the hierarchy tree of the design. Each Initial, Always, continuous assignment, UDP and Gale Instance executes concurrently with respect to all others, but the Statements inside an Initial or A/ways are in many ways similar to the statements in a software programming language. They are executed at times dictated by Timing Controls, such as delays, and (simulation) event controls. Statements execute in sequence in a Begin-End block, or in parallel in a Fork Join block. Fork-join blocks can be used to create new dynamic processes. A dynamic process executes in a separate parallel thread. Dynamic processes are particularly useful for pipeline modelling. Fine-grained control for Initial, Always and dynamic processes is provided by the built-in process class. ­ A continuous assignment modifies the values of Nels or Variables. An Initial or Always modifies the values of Variables. An Initial or Always can be decomposed into named Tasks and Functions, which can be given arguments. Tasks and Functions may be declared as Automatic or Static, with automatic and/or static variables that may be specified for each variable instance. Jump Statements enable jumping to the end of a loop, or exiting loops Functions or Tasks before completion. I I Continuous assignment assign Sum -A + B; Initial statement II iniLial forever H5ns Clock � -Clock; I I Combinational always always_comb begin Carry - a Sum = b; A a 1 b; end I I Clocked always always_ff @(posedge Clock iff Reset -- 0 if or posedge Reset) {Reset) Q <� 0; else Q <� Q I 1; Copyrighl 0 1995-2006 by Doulos Lid. 13
  • 13. A Brief Introduction to SystemVerllog Interfaces Interfaces are a major new construct in SystemVerilog, created specifically to encapsulate the communication between blocks, allowing a smooth refinement from abstract system-level through successive steps down to lower RTL and structural levels of the design. Interfaces also facilitate design re-use. Interfaces are hierarchical structures that can contain other interfaces. Interfaces may contain Modports. These provide access and directionality for the interface members. Broadcast communication is modelled by extern forkjoin tasks in interfaces, which can be defined in multiple modules and executed concurrently. Assertions and Coverage An immediate assertion is used to test the value of an expression. Immediate assertions are procedural Statements. Prope rties are used to specify aspects of the design's behaviour. Properties may be built from one or more Sequences. Typically Sequences and Properties describe behaviour over time ("temporal behaviour") with respect to a clock. Properties may be checked using Concurrent Assertions. If an asserted property does not hold, the assertion is violated and an error is generated. Assertions may be checked dynamically during simulation, or statically using a property checker, which is a type of formal verification tool. Assertions may also be used to control test bench automation tools. Assume statements act like concurrent assertions during simulation, but property checkers assume they hold. Properties may be used in Cover statements. During simulation, these monitor evaluation of the property, and afterwards a coverage report is created. An Expect statement is a procedural statement that awaits and checks a specified Property. Expect statements are used in testbenches. 1 1 Immediate assertion AEQB : asserL (A •• Bl Sdlsp l ay ( "OK . A equ a ls B . " ) ; e l s e S error (" O h dear! A should equal B . . . " ) ; I I Property property A_lmplies_B_thcn_C ; @ (poscdge Clock) A 1-> B ##1 C; endproperty 11 Concurrent assertions rulel: assert properLy (A_impl ies_D_ then_Cl e l s e Serror ("a , b, c ouL o f sequence " ) ; prop! : cover property (A_ implies_B_ Lhen_C ) ; In addition to property coverage, SystemVerilog includes Covergroups for specifying functional coverage metrics. A Covergroup contains one or more 14 Cop)"n!ll11 0 1995- 2006 by Doolos lid
  • 14. A Brief Introduction to SystemVerilog Coverpoints, which are Variables or Expressions for which functional coverage information is collected. Packages Declarations of Data Types, Classes, Functions, Tasks, Properties and Sequences may be made in Packages and Imported into Modules, Interfaces etc. This provides a means to share common declarations. Built-In Methods, System Tasks and Functions, the DPI and the PLI A number of methods are buill in to the language. For example Array Manipulation methods, Enum methods and String methods. There are also a number of built-in System Tasks and Functions. These cover a range of tasks, including reading and writing from files, stopping simulation, type conversions and stochastic modelling. inilial be g i n $display("Starting simulation ... "); $stop; end There is a built-in package, Std. which contains a number of system types. The Direct Programming Interface (DP/) allows functions in a foreign language (usually C) to be called as SystemVerilog functions. These are known as Imported functions. Conversely, a SystemVerilog function or task may be Exported. and called from tho foreign language. The Programming Language Interface (PL/) is an integral part of the SystemVerilog language, and provides a means of calling functions written in C in the same way as System Tasks and Functions. Com ilation p SystemVerilog source code is usually typed into one or more text files on a computer. Those text files are then submitted to a SystemVerilog compiler or interpreter, which builds the data files necessary for simulation or synthesis. Sometimes simulation immediately follows compilation with no intermediate data files being created. Two interlinked mechanisms, L brary and Configuration, accommodate library­ i based tools. The existence of libraries supports separate compilation of modules and allows different versions of a module to be used in different places in the simulation. Copyright C> 1935-2006 by Doutos Ltd 15
  • 15. Syntax Summary Comp ilation Unit Compilation units contain interfaces, modules, programs and packages as well as declarations that are outside any of these and bind directives. Llmeuni L 1 OOns ; timeprecision lps; I I Compilation unit declarations - same as in a package I I Modules, Interfaces, Programs, Packages module . . . endmodulc interface ... endinterlacc program endp rogram package . . . cndpackage I I Bindings b i n d M Prog TestProg ( . . . ) ; bind M I n t Bus ( . . . ) ; bind M ml , m2 Mon i l o r ( . . . ) ; Packa e g package P; II Anonymous program program; I I Task, Function, Class, Covergroup declarations endprogram II Net, Variable, Type, Import, Virtual, Task, Function, DPI, Class, I I Parameter, Covergroup, Overload, Property, Sequence Declarations endpackage 16 p Cq>ynghtO t99S.2006 by Ooulos llo
  • 16. Syntax Summary Module module Ml # (parameter N - 8) ( i nterface I n t , lnput logic P l , P 2 , outpul r e g [ 7 : 0 1 P3, i nout bit P� ) ; timeunit IOns; t imepreci s i on l p s ; II Net, Variable, Type, Import, Virtual Declarations II Classes ... I I Parameter Declarations . . . localparam . . spccparam . . . defparam . . . . 11 Properties, Assertions, Sequences, Coverage, Covergroups I I Nested modules etc. module . . . endmodul e interface . . . endlnLcrLace program . . . endproqram II Processes... i n itia l . always . . fi na 1 . . . . . • I I Clocking Blocks . . . clocking cbl . . . endclock i ng clocking cb2 . . . cndclocking dc!au l L clocking cbl; II Continuous assignments. . . assign X = A + B; wire (s trongl , weakO) eopynghl 0 1 995-2006 by Dou los Lid [ 3 : 0] # (2 , 3) Y 7.; 17
  • 17. Syntax Summary I I Module instances... COMP Ul (WJ, W4 ) ; COMP U2 ( . Pl (W3) , . P2 ( W 4 ) ) ; COMP I ( 1 0 ) U3 (�13, �14 ) ; COMP I ( . Cl ( 1 0 ) ) U4 ( . Pl (W3 ) , . P2 ( �14 ) ) ; COMP US ( . Pl , . P2 , . PJ ( }) ; COMP U6 ( . • ) ; MOD U7 ( I n Lerf . slavc ) ; MOD UB ( . A ( lnterf ) , . cl k ( c l k ) ) ; 1 I Interface instances... I n t f # ( . DWIDTH ( 1 6 ) ) I n lerf (elk); I I Program instances . . . Prog Pgl (W 2 , W4 ) ; I I Bind bind M2 Prog TestProg ( . . . ) ; bind M2 I n L Bus ( . . . ) ; 1 1 Generated instances, assignments etc . genero!lte gcnvar i ; for (i=O; i < 8 ; i + + ) begin G end endgcnerate Subroutines. . . Lask . . . funclion . . . import "DPI-C" exporl " D P I -C" bind + function . . . 1I I 1 Specify Construct ... specify showcancel l ed Outl, Out2 ; pu l s es tyl e_ondcLccL Out l , Out2 ; ( A => Out l ) u ( 2 , 3 ) ; endspeci f y endmodule : M l 18 Copyoight 0 1995·2006 by Oouloa Ltd.
  • 18. Syntax Summary Interface i n l c r facc Il § (parameter i n t N 7) ( i nput logic Clk, output bil Oul, lnout bit InOut) ; t imc unit lps; 1 I Declarations, Clocking Blocks ... I I Nested interfaces and programs . . . inlerfacc 1 2 ; endlnterface; 11 Interface and program Instances . .. 12 1ntfl ( ) , I n t f 2 ( ) ; I I Tasks, Functions ... Lask . . . endtask funcLion . . . endfunction extern task Tl (inpul i , . . . ) ; extern forkjoin task T2 ( input i , . . . ) ; cxLcrn function inlegcr F ( i npuL i, . . . ) ; I I Modports . . . modport MPl ( input Rcq, Addr output Gnt , inout Data) ; modport MP2 (clocking cb) ; modporL MP3 ( import Read, Wri Lc) ; modport MP4 (exporl Task1) ; modporl MP5 ( import task Taskl (inpul i , . . .)); I I Assertions I I Continuous Assignments, Processes I I Generated instances, assignments etc. ... endinterface : Il Cop)<1911 c 19!15-2006 by Ooolos Ltd 19
  • 19. Syntax Summary Program program P i (parameter int X � 2 ) (input X, output Y, inout Z ) ; I I Declarations ... I I Clocking blocks . . . clocking cb @ (posedge Clock) ; defau l t Input # l ns output ff2n s ; inpul Y; i npuL UlsLcp UpOn output negedge Z ; - Lop.Counter.UpDn; endclocking : cb initial begin 1 1 Clocking Block Drives . .. f#l cb.Z < = 4 ' hz ; cb . Y [ l : O ] < � §#2 Tnt_Y; $exit; end 11 Assertions, Properties, Sequence, Coverage, Covergroups ... 11 Continuous assignments, Initial processes ... endprogram Declarations import a_package: : p a ckagc Lypc; import another_package : : • ; _ w i r e Wl , W2 , W 3 , W 4 ; w i r e i n t �l5; 1-12; alias IV! "This is a string" ; locaJparam Cl var V l ; v a r l ogic V2 ; reg [ 7 : 0 ] R l , Ml [ 1: 1 02 4 ] ; reg sign ed [ 3 1: 0 ] R 2 ; consl longint C 2 = 1 ; ' ( ' (0 , 1 , 2 ) , ' ( 3 ( 4 ) ) } ; i n t n[1 : 2 ] [ 1 : 3 ] • 20 Copynoht c 1995-2006 by Dou� Ltd
  • 20. Syntax Summary byle B; t ypedef logic 11 : 10] Al [!3]; s ho rtin t ST; shorLreal SR; longreal LR; enum {A, B, C) ABC; virLual inlerface an interface vi; typedef struct packed signed { inl a ; shortint b; byle c ; b i t [7 : 0] d ; Pack; Pack Ul; unio n packed Pack a cell; bil 11 : 0 ] TwoBi t ; UnionCell ; u nion tagged bit [1:0] TwoBit TwoVal ued ; logic [1 : 0 ] Tagge dCe 11; II TwoBiL FourValued; _ Associative arrays int Arra yA[']; biL [7:0] ArrayB[sLringJ; event ArrayC[AClass]; II Dynamic Arrays bit [8 : 0] DynArray1[ ] ; i n L DynArray2 I); II Queues byte byte q[S]; string upto ten names[$:9] _ _ • { "Fred", "Bill" ) ; I I Class instances AClass #{4) A; AClass #{.N{4)) B - new; BClass B = new; Bclass # ( real ) BR COpyright C 1995-2006 by Doutos Ltd. new; 21
  • 21. Syntax Summary Subroutines I I Task declaration task automatic Tl { input A l , inout A 2 , output A3) ; I I Statements return endtask : Tl Function declaration function signed [ 7 : 0 ) Fl (input integer A l , inoul A2 , output A3) ; II II Statements F l � Expression; return Expression; endfunction : Fl I I Operator Overloading bind + iunction my_Lype add_my_type {my_type, my_type ) ; I I DPI functions and tasks import import import export "DPI-C" "DPI-C" "DPT -C" "DPI-C" function integer CFunc ( inpul i n t X); pure function real si n ( real ) ; Lask Cfunc2 { i nput in L X); SVFunc fun ction SVtoCFunc; = Classes v i rtual class ParentCl a s s ; i n t X; virtual protected function integer AFunc {byte Y) ; cndclass : ParentClass class AClass # {parameter int P 1 1 Property (data) declarations int X; static i n t Count 0; 1) extends ParentClass; ... = 1 1 Random variables rand b i t [ 1 5: 0 ) R ; randc byte RC; I I Constraints cons tra int cl { R [l : 0 ] 22 - - 2'b00;) Copyright C 1995-2006 by Doulol Ltd
  • 22. Syntax Summary Constructor function ncw ( int X) ; this . X = X � s upc r . X; II c nctfu nc ti on I I Task, function declarations extern protected virtual II function int ExFunc ( in t Z ) ; Nested Class class ClName; endclass : ClName endclass II : AClass Member function declared outside the class functi on i n t Aclass::ExFunc (int Z ) ; e ndf u n cti o n I I C la ss with parameterised type class BClass # ( paramete r type T - inL); local T X; function AFunc ( T Y ) ; end f unc ti on e ndcl a ss Constraints c l a s s WithConstraints; rand biL xl; byte yl ; constrajnt cl ( x l -> yl -= 0;) c ons trai n t order ( s olve xl before y l ; ) c on s t ra int We i ghted { yl dist {0 := 1 . rand [ 1 :7] ·= 2} }; x2, y2 , z 2 ; constraint c { z 2 = = x2 - y2 ; } rand int rand lo gic [4:0] Addr; Copyright c 199S.2006 by Doulos Lid 23
  • 23. Syntax Summary rand enum ( low, high} type; constraint AddrRange ( ( Lype low ) -> Addr inside I ( 0 : 1 5 ] } ; ( type == high) -> Addr inside { [ 1 6 : 3 1 ] } ; endclass : WithConstrainls Processes begin : BlockName I I Statements end : B1ockNamc Forkl.abeJ : fork I I Statements join ForkLabe1 fork FB1ockNamc BcgLabel : begin I I Statements end : BegLabc1 join_any : FBlockName i n i t i al begin : BlockNamc I I Statements end always begin I 1 Statements end a lways_ comb begin I 1 Statements end a1ways_1 atch i( (Enable) begin I I Statements end 24 Cql)'Jight 0 t99S.2006 by Ooulos Ltd
  • 24. Syntax Summary a l ways_ff @ (posedgc Clk i f f Reset -- 0 or posedge Reset) begin end final begin II Statements end Statements #10 #lns @ ( A or B or C) II @ (A , B, C) @ * @ ( *) @ (posedge Cl k) @sequcncc_inst @ (Rl i f f Pl -= 1) wail (Expression) wait (A Sequcncc . Lriggered) expccl ( @ ( posedge Clock) a H#l b #Nl c ) Scrro r ( "Fai l " ) ; Reg = Expression; Reg <= Expression; Vcc LorReg [B it ] = Expression; VectorReg [ MSB: LSB] = F.xpression; VectorReg [MSB-:NBl l s ] Expression; Memory[Address] = Expression; assign Reg = Express i on deassign Reg; = return; break; continue; TaskEnabl e ( . . . ) ; $ root . MyModule . Tas kEnable ; I I Absolute name disable TaskOrBlock; -> EventName; ->>> EventName ; i f (Condit ion) else if (Condit i o n ) Copynghl c 1995-2006 by Ooulos ltd 25
  • 25. Syntax Summary else unique i f priority i f case (Seleclion) Choice] o o 0 0 0 0 Choice2, Choice3 default endcase unique case priority case . . . randcase x - I; I I Probability of executing this is 1/8 I I Probability of executing this is 3/8 3 : X - 2; 4 : X 3; II Probability of executing this is 1/2 endcase randsequence ( F i r s t ) !lead Either_Or T a i l ; First ( $write ( " Thi s is written " ) ; ) ; Head Either :• 2 I Or; E ither_Or $wriLe ( " twice" ) ; } ; E i ther $write ( " once" ) ; l; Or $di splay ( " in every three . " ) ; ) ; Tail endsequence for ( in t I-0, J•O; I*J<MAX; I�Ttl) repeat (8) while (Condit i o n ) do while (Condition) forever foreach ( uplo_Len names ( n ] ) Sdisplay ( "Name %d i s % s " , n , upto_ten_name s [ n) ) ; 26 Copyrtghl 0 1995·2006 by Oouloo Lid.
  • 26. Syntax Summary force X 1; release @ elk X; wait fork; disable fork; A5serLLabel: (All assert $display("%m passed"); else Sdisplay("'m failed"); Sequences, Prop erties and Concurrent Assertions a H#l b [*3] (a g?. b ) H#l [•5] ( a ##2 b) l'l :3] a #11 b 1 * 1 : $ ] Ul c a ##1 b[->1:3] #Hl c a llil b 1�1 : 3) 11 # 1 c (a ##1 b # # 1 c) 1-> (d #Hl c ) sequence sl (arg); @(posedge elk) a i # l b Nil c; endsequence sl and s2 sl intersect s2 sl or s2 first_malch(sl ##11:21 s?.); ['2]); x lhroughoul (##3 ((y==O)&&(z-=0 )) xl*31 within (($felly) ##1 y[*4]); sequence s3 (arg); int v; @(negedge elk) x Hill sl(v) ##1 y ##1 sl.ended #Ill z; endsequence sequence s4; @(ncgedge elk) x ##1 s2.matched [->1]##1 y; endsequence sequence s5; @(poscdge clkl) x ie @(posedge c1k2) sG; endsequence Cop)'ight 0 1995-2006 by Ooutos Ltd 27
  • 27. Syntax Summary property pl ; @ (posedge e l k ) a 1 -> b i i l c # # 1 d ; endpropcrty properly p2 ; @ (e l k ) disable iff (AFunc) not x 1 -> y Ill z; endpropc rLy property p 3 ; s 5 1 -> s5; endproperty check_pr: assert property (pr) $display("Property pr has passed" ) ; else Sdisplay ("Property pr has failed" ) ; a_imp l ies_b : assert property ( @ (posedge clock) a 1 - > b ) ; AssumeProp: assume properly ( prop ) ; CoverProp : cover property (Kesecsequence) Sdisplay ( "A reset has occurred" ) ; Covera ge enum ( Red, Green, Blue } Colour!, Colour2; covergroup cgl @ (posedge c l ock}; coverpoint Colour!; cl c2 : coverpoinL Colour2 iff ( ! Rese L l ; c3 : cross Colour!, Colour2; e ndg roup cgl cgl_jnst - new; cove rgroup cg2 (ref bit [ 9 : 0 ] v) @ (posedge clock); coverpoi n t v ( ( [ 0 : 63 ] ' 65 ) ; bins a bi.ns b [ I ( [ 1 2 7 : 1 50 ] , [ 148 : 1 9 1 ] } ; - [ 2 0 0 , 201,202 ) ; bins c [ 2 ] [ 1 000 : $ ] ) ; bins d bins oLhers [ ] - defaul t ; 28 Cop111ght C 1995-2006 by DouJos Ltd
  • 28. Syntax Summary b i t [ 9 : 0 ) v l , v2; cg2 cg2_in sL_vl cg2_i nst_v2 � new (vl ) , new (v?.) ; bit [ 4 : 1 ] v_a; covergroup cg @ (posedge elk); coverpoint v_a ( bins s a ( 4 = > 5 - > 6), ( [ 7 : 9 ] , 1 0 = > 1 1 , 1 ?.) ; bins sb[) ( 4 => 5 => 6 ) , ( [ 7 : 9 ] . 10->1 1 , 12 ) ; default sequence ; bins a llo t h e r - - endgroup CopyrlglltO 199:;.2006 by Doulos Ltd 29
  • 29. ( ' ( ' ( L L
  • 30. System Veri log GOLDEN REFERENCE GUIDE SystemVerilog Alphabetical Reference /�DOULOS
  • 31. Alias The alias statement is used to model a bi-directional short-circuit. � This feature was introduced in SystemVerilog a l i as NetLValue � NetLValue NetLValue � [= NetLVa l u e - ... ) ; { See Assig n } module-<HERE>-endmodul e l nterface-<HERE>-endi nterface generate-<HERE>-endgenerate Each signal being aliased must have lhe same net type and the same width. For example, they must both be 8-bit wires. The same nets can appear in multiple alias statements: the effects are cumulative. You are not allowed to alias a net to itself, or specify the same alias more than once. • Names need not have been declared - implicit nets are assumed. Exam les p This module reverses the bits of its bi-directional ports. module ReverscBits (inoul [7: 0 ) A, B) ; aJ ias A - {8 [ 0 ) , B [ l ] , 8 [2 ) , 8 [ 3 ] , 13 [ 4] , 8 [ 5 ] , B [ 6], 8 [ 7 ] J; endmodule In the following, semi word is implicitly declared as an 8-bit wire. wire [ 16 : 0 ] word; wi re r 7 : 0 ) halfword; a l i as word = [halfword, scmiword } ; See Also Assign 32 Cop)f;ghl Cl1995-2006 by Doulos Lid
  • 32. Always Each of the various forms of the always construct defines a static processes that contains one or more statements (procedural assignments, task enables, if, case and loop statements), which are executed repeatedly throughout a simulation run, as directed by their timing controls. The always_comb, always_latch and always_ff are used to specify design intent for simulation, synthesis and formal verification: always_comb models combinational logic behaviour; always_ff models synthesisable sequential logic behaviour; always_latch models latched logic behaviour. � always_comb, always_latch and a/ways_ff were introduced in SystemVerilog AltvaysKcyword Sta tement (one of} always always_comb always latch always_ff Al ••aysKeyword = mudule-<IIERE>-endmodule interface-<IIERE>-endtnterface genera te-<HERE>-endgenerale • Only variables may be assigned in an always etc. • Every always starts executing automatically at the start of simulation, and continues executing throughout simulation as specified by any timing controls. When the last statement in the always is reached, execution continues from the top of the always. always_comb and always_latch statements are executed automatically once at the start of simulation, after all initial and always statements have executed. always_comb and always_latch have inferred sensitivity lists, which include all variables read by the procedure and called functions. They may not have blocking timing or event controls. An always_ff must have exactly one event control and no blocking timing controls. The variables on the left-hand side of assignments in an always_comb, always_ff or an always_latch, including variables from the contents of a Copy!ighl C 1995-2006 by Doolos ltd 33
  • 33. Always called function, may not be written to by any other process. (always @* and always @(*) allow multiple processes to write to the same variable.) always_comb and always_latch can include neither statements that block nor fork-join blocks. Gotchasl • An always containing more than one statement must enclose the statements in a begin-end or fork-join block. • An always with no timing controls will loop forever. • In RTL code, use only the always_comb, always_latch and always_ff statements, so that the tools can check the style of the code matches the intent. Exam les p The following example shows an always which describes combinational logic: always @ (A or B or C or D) begin R � { A , B, C , D ) F 0; begin : Loop integer I ; for ( I = 0 ; I < 4 ; I Equiv. to @(*), @*, or @(A, B, C, D) II = I I 1} (R[II ) begin F I; disable Loop; end jf - end end II Loop The following example shows an always_comb: al ways_comb A = 13 & C; always_comb A <- # l Ons 13 & C; 34 COpyrtghl 0 1995-2006 byDoulos Ltd
  • 34. Always The following example shows an always_ff: always_ff @ (poscdge Clk i f f Reset -- 0 or posedgc Reset) begin end The following example shows an always_latch: always_laLch i i (Enable ) Q <= D; The following example shows an always_ff: always_ff @ (posedge Clock i f f nReset or negcdge nRcseL) begin i f ( ! nReset) Count <- 0 ; I I Asynchronous reset else if ( ! Load) Count <- Data; I I Synchronous load else Count <- Count 1 1 ; end See Also Begin, Final, Fork, Initial, Statement, Timing Control Copynght0 199S.2006 b)' Douloo Ltd 35
  • 35. Array SystemVerilog supports fixed-size, dynamic and associative arrays. Fixed-size arrays can have an arbitrary number of dimensions. Dynamic and associative arrays are one-dimensional. Array elements can be of any type and bit-select, part-select and array slicing operations are possible . .,.. Arrays are enhanced in SystemVerilog; dynamic and associative arrays were introduced in SystemVerilog 1 Declaration } Da ta Type PackedDimcns ions . . Nurnc Unpa ckedDimensions . . . [ , Name Unpa ckedDimensions ]; . . . . PackcdDimcnsi on = UnPackcdDimensi on [ Cons LantExpression : Constan tr:xpression] = tone of} [Constan tExpression] [ConsLan tExpression: Constan tExpression] { Use } 1rrayElement [Express ion+ : Cons t a n L Expression] { Whole array} {slice} { Var iable slice } ArrayElemen t [ Expression- : Cons tan tExpressi on] { Variable slice } ArrayName ArrayElemen t [ Cons tan tExpressi on: Cons tan LExpression ] ArrayEl ement = ArrayName [ [ I xpressi on ] [ [ Expression] ·: . . . J] ( Element ) p Packed and Un acked The term "packed array" is used to refer to the dimensions declared before the object name. The term "unpacked array" is used to refer to the dimensions declared after the object name. The packed dimensions correspond to the "vector width" in Verilog. A packed array is guaranteed to be represented as a contiguous set of bits. A single array may have both packed and unpacked dimensions. bit ( 7 : 0 ] B ; I I Packed array real R I I Unpacked array [7 : 0] ; • It is possible to create arrays of nets, var iables, object handles and events. • Both packed and unpacked arrays can be multi-dimensional. 36 Cop)flgl1 0 1995-2006 by Daulos Ltd
  • 36. Array One dimension of an unpacked array can be declared as having a un-fixed (dynamic) size. The size is specified at runtime using the new operator. An unpacked dimension can be expressed as a single number, as in C. E.g. [ s i zc] . This is equivalent to [ O : size-1 ] . I I Equiv. to: b i t A [ 0 : 3 J I 0 : 7 ] ; In a list of dimensions, the right-most one varies most rapidly. However, a packed dimension varies more rapidly than an unpacked one. bit A [ 4 ] [ 8 ] ; log i c [ 0 : 1 5 ] T1 [ 0 : 7 ] ; logic A2 [ 0 : 7 ] l ogic [ 0 : 7 ] • [ 0 : 15 ] ; [ 0 : 1 5 1 A3; 1 I [0: 1 5 ] varies most rapidly 1 1 [0:15] varies most rapidly 1 1 (0:15) varies most rapidly A single element of a packed or unpacked array can be selected using an indexed name. This element may itself be an array. bil [ 3 : 0 ] byte A ; [ 7 : 0 ] PackedArr:ay; B = PackcdArr:ay [ ? ] ; 1 I Select a single 8-bit element • An X or Z in an index expression, or an index which is out of the address bounds, causes a read to return X (for 4-state types) or 0 (for 2-state types). In either case, a run-time warning is issued. Writing to an array with an invalid index will perform no operation. • One or more adjacent elements can be selected using a slice name. A slice is a selection of one or more adjacent elements of an array, whereas a Part-select is a selection of one or more adjacent bits of a single dimension packed array. The size of the slice or part-select must be constant, but the position may be var iable. Slices of an array can only apply to one dimension - other dimensions must have single index values in an expression. • Assignment patterns may be used for array initializers, literals and expressions. The expressions must match element for element and the braces must match the array dimensions. Each element must match the type being initialized. bi. t UnpackedArr:ay1 [ 1 : 0 ] - ' { 1 , 1 J I I No size warning, bit can i n t UnpackedAr:r:ay2 [ 1 : 0 ] I I be set to 1 ' { 1 ' b 1 , 1 ' bl } ; Packed Arra Rules y • If a packed array is declared as signed, then the array viewed as a single vector is signed. A part-select of a packed array is unsigned, and the individual elements are unsigned unless they are of a named type declared as signed. Copyngllt C) 1995-2006 by Doulos ltd 37
  • 37. Array Packed arrays allow arbitrary length integer types. The maximum size of a packed array may be limited, but must be at least 2**16 bits. • Packed arrays can only be made of the single bit types: bit, logic, reg, wire and the other net types and using other packed arrays and structs. • A packed array cannot be assigned to an unpacked array without an explicit cast. A slice name of a packed array is a packed array. • The following operations can be performed on packed arrays only: Assign an integer (e.g. A • • = 8 ' bl l l l l l l l ; ) Treat as an integer in an expression (e.g. ( A + 3)) Integer types with predefined widths (i.e. byte, shortint, int, longlnt, and Integer) cannot have packed array dimensions declared. They can be treated as a single dimension packed array, with the dimension numbered down to 0. byte B ; I I Equiv. to b i L [ 7 : 0 ] B; i n Leger I ; I I Equiv. to 1 ogic signed [ 31 : 0 J r; Unp acked Arra Rules y An unpacked array cannot be viewed as a single vector. Therefore if it is declared as signed, that means that each individual element of the array is signed. • An element of an unpacked array may be a packed array. • Unpacked arrays can be of any type. • A slice name of an unpacked array is an unpacked array. bit Ar.rayl [ 7 : 0 ] inL Array2 Array2 = [15:0] [3:0] ; Arrayl [ 3 : 0 ] ; 1 1 Array of 8 1 5-bit vectors I I Array of 4 ints 1 I Slice from Array1 A number of system functions provide information about arrays: $left, $right, $low, $high, $increment, $size and $dimension. Multiple array dimensions can be defined in stages using a typedef: typedef bil [ 1 : 5 ] fivcb i ts; fivebits [ 1 : 10 ] f ; 1 1 Equivalent to bit [1 : 10)[1 :5] f; typcdef Fivcbits mern_ Lype [ 4 ] ; mem_typc mem ( 8] ; I I bit [1:5] mem [3:0][7:0]; 38 Copyright 0 199!>-2006 by Ooulos ltd
  • 38. Array Exam les p wire [7 : 0 ] A [ 0 : 15] [0 : 15 ] , B [ 0 : 15] [0 : 15] ; I I Two 16x16 array of bytes / [ O J [ 1 ] [ 2 ] B [ 1 ] [2] [ 3 1 ; I I Bit-select A = B; logic [ 1 5 : 0 ] 1rrayl ; l og i c [ 7 : 0 ] Array2; Array2 Array1 1 8 : 1 ] ; � I I Part-select Reading and writing a variable slice of the array A [ x+ : c] = B [y+ : c ] I I c must be constant Multiple packed dimensions defined in stages using typedef typedef b i L [ 0 : 7 ] BB; BB [ 0 : 1 5 ] B8_1 6 ; I I [0:7] varies most rapidly Multiple unpacked dimensions defined in stages using typedef typedef BB Mem[ 0 : 3 ] ; I I Array of four BB elements Mem Mcrn8 [ 0 : 7 ] ; I I Array of 8 Mem elements Sea Also Array Manipulation Methods, Associative Array, Dynamic Array, Generate, Instantiation. Module, System Tasks and Functions, Queue Copyr'!Jhl C> 1 !195-2006 by Ooulos ltd 39
  • 39. Array Manipulation Methods There are a number of built-in methods, which may be used to search, sort and reduce arrays. ""' This feature was added in SystemVerilog 1 Calling a method 1 1J:rayName . MethodName [ (Arguments, . . . ) I [with ( Expression) ] Array Locator Methods Locate specified elements of an unpacked array or queue. These return a queue of the same type as the array being operated on. Prototype: function ArrayType [$] Method ( ArrayType Iterator item) ; The wi Lh clause is mandatory for these: find ( ) Returns all the elements satisfying the given expression find_first ( ) Returns the first element satisfying the given expression f i nd_last ( ) Returns the last element satisfying the given expression The w i t h clause is optional for these: Returns the element with the minimum value or where the ., i th expression evaluates to a minimum min ( ) Returns the element with the maximum value or max ( ) the with expression evaluates to a maximum Returns all elements with unique values or whose uniqu e ( ) with expression is unique Array Index Locator Methods Locate specified elements of an unpacked array or queue. These return a queue of the array's index type, which is always int, except for associative arrays. Prototype: func t i on Type [ $ ] Method ( ArrayType Iterator = item ) ; The with clause is mandatory for these: Returns the indexes of all the elements satisfying the find_index ( ) given expression find_f i rs t_index ( ) Retums the index of the first element satisfying the given expression 40 Copynoht 0 1995-2006 by D0<1tos ltd
  • 40. Array Manipulation Methods find l a s t index ( ) Returns the index of the last element satisfying the given expression The with clause is optional for this: unique index ( ) _ Returns the indexes of all elements with unique values or whose with expression is unique Array Orderin Methods g Reorder the elements of a one-dimensional array or a queue. Prototype: funcLion voi d McLhod (ArrayTypc Iterator - item) The with clause is prohibited for these: Reverses all the elements of the array reverse ( ) shuffle ( ) Randomizes the order of the elements in the array The w i th clause is optional for these: sort ( ) Sorts the unpacked array in ascending order rsort ( ) Sorts the unpacked array in descending order Arra Reduction Methods y Reduce any unpacked array to a single value, whose type is the element type. Prototype: funcLion Type MeLhod (Arra y1'ype ilcrator i Lcm) The with clause is optional for all these: sum ( ) Returns the sum of the array's elements or the sum of the wi th expressions product ( ) Returns the product of the array's elements or the and ( ) product of the w i th expressions Returns the bitwise AND of the array's elements or the or() bitwise AND of the with expressions Similarly, returns the bitwise OR xor ( ) Similarly, returns the bitwise XOR ue in lterator Index Q ry g Method Returns the index of an array iterator in an array manipulation wi Lh expression. The return is always int, except for associative arrays. Prototype: function Type index ( int Dimension Copynght Cl 1995-2006 by Doulos Ltd 1) 41
  • 41. Array Manipulation Methods In the min(), max(), unique() and unique_index() locator methods the with clause and its expression may be omitted if the relational operators (<, >, ==) are defined for the element type of the given array. If the with clause is used, the relational operators must be defined for the type of the expression. • Gotchasl The optional with clause accepts an expression enclosed in parentheses. In contrast, the with clause used by the randomize method accepts a set of constraints enclosed in braces. Exam les p byte b [ 1 = ' { 1, 3, 2l ; i n t ,.; , r [ $ ] ; r � b . fi nd ( x ) w i th r � b . f ind with (x > 2 ) ; ( i tem I I r = (3} i Lcm . index) ; I I find all items equal to their I I index, i.e. (1} r = II r= 1 b . min; II b = b . sort; s = b . sum with = '(2, 3, 1 } '{1, 2 , 3} I I s = 1 8 (i.e. 5 + 7 + 6) I I s= 0 (i.e. 1 " 3 " 2) II b b . rcvers e ; ( i tem + 4 ) ; s � b . xo r ; Find all items in Ar1 that are greater than corresponding item i n Ar2 Ar2 [ 3 : 0 ] [ 3 : 0 1 ; in L r [ S J ; r = Arl . find ( x ) with ( x > Ar2 [ x . indcx ( l ) ] [ x . i ndex ( 2 ) l l ; i n t Ar l [ J : O ] [ J : O ] , See Also Array, Queue 42 Copyright C 1995-2006 by Ooutos ltd.
  • 42. Assert An assertion is a statement that something must be true. assert property can be used as a concurrent or procedural statement. An immediate assertion is evaluated during the execution of procedural code, such as the statements in an always block. For a concurrent assertion, variables are sampled when a specified clock event occurs. II> This f eature was added in SystemVerilog { Immediate assertion J {AsscrtJ.abcl : ] a!lserl (Expression) { Concurrent assertion J [Asscrtl.abel : ] asserl property AcLionBlock ; ActionBJock ( ProperLySpec) ActionB I ock [one of) Sta tement [ S ta t emen t] else SLa temen tOrNull Prope r LySpec ; see Property For Immediate Assertions see Statement. For Concurrent Assertions: always -<IIERE> i n l t i a l-<HERE> module-<IIERE>-endmodulc genera Le-<IIERE>-endgenera le inLerface-<HERE>-endinterface program-<IIERE>-endprogram • Being a statement, the immediate assert can be used anywhere a statement can be used in procedural code. • The expression tested in the immediate assert statement is non-temporal and treated as an expression in the condition of a procedural if statement. • There is a severity associated with the failure of an assertion (see Assertion Severity System Tasks). The default one is "$error". • A named assertion can be disabled. Copynghl C 1995-2006 by Doulos Lid 43
  • 43. Assert assert property statements executed outside procedural code are executed throughout simulation. • The assert property statement is used to enforce a property as a checker. When the property is evaluated as true. the pass statement (if any) of the ActionB/ock is executed. Otherwise, the fail statement is executed. When no action is needed, a null statement (i.e. ;) is specified. If no statement is specified for the else. then $error is used as the fail statement of the ActionBlock. • The ActionBiock of a concurrent assertion cannot include any concurrent assert. assume or cover statement. but it can contain immediate assertion statements. • The clock for an assert property statement is determined as follows: Any explicitly specified clock for the assertion. • Else. it is the inferred clock from the context of the code when embedded. Else, the default clock. if specified. • A multi-clocked assert property statement must not be embedded in procedural code where a clock is inferred. It must have the clocks explicitly specified. • Label all assertion statements. The assertion label can be displayed using the %-m format code. AssertLabcl : assert (Exp) Sdisplay ( " %m passed" ) ; else $displa y ( "%m failed " ) ; • The fail statement can be used to signal a failure to another part of the testbench. • Immediate assertions can be used to document assumptions. while concurrent assertions can be derived from the design's specification and used to verify correct functioning. 44 COpyngl1 C 199S.2006 by Ooulos Ud.
  • 44. Assert Exam les p Immediate assertions always @ (posedge el k) assert (State ! - I llegal_Stale) else $error ( " I l legal state reached" ) ; inilial begin assert ( A -= B ) ; assert (C && D) Sdisplay ( "OK - C and D are both true " ) ; assert (E) else $warning ( " � is NOT true" ) ; end Concurrent assertions module FlipFlop ( inpul logic elk, D, outpul logic Q) ; property P2; inL d ; d) ; @ (posedge e l k ) ( 1 , (d=D) ) 1 -> R 1 1 (Q endproperly Label2 : assert property ( P 2 ) ; always @ (posedge elk) Q <= D; endmodule I I Module Flipfiop above is equivalent to modul e FlipFlop ( input logic e l k , D, output logi c Q) ; properly P2 ; i nl d; d) ; ( 1 , (d=D) ) I -> # H l ( Q endproperty always @ ( posedge elk) begin I�bel 2 : assert property (P2 ) ; Q <= D; end endmodule See Also Assume, Bind, Cover. Disable, Expect, Property, Sequence, System Tasks and Functions, Wait Copynght C> 1995-2006 by Ooutos Ltd 45
  • 45. Assign Assign outside any initial or always statements creates a continuous assignment to one or more nets or variables. Events are created on the assigned nets or variables whenever an expression changes value. Assign in an initial or always is a procedural continuous assignment. When active, this creates a continuous assignment to one or more variables, and prevents ordinary procedural assignments from affecting the values of the assigned variables. Procedural assign and deassign statements may be removed from future versions of the language. Ill- SystemVerilog adds the ability to assign variables { Continuous assignment - one of} assign [ S trength] [ Delay3J NetLValue = NeLLValue . . . Expr-ession, Expressi on , ; f.'xpression, assign [ DelayControl] VariablcLValue Va r:iableLVaZue � Expression . . . ; { See also Net 1 { Procedural continuous assignment - one of} a s s i gn Vari ableLValue ExpLcssion; deassign VariablcLVa l u e ; = Delay3 = { one of} H DelayValue # (Min typmaxExp ression NeLLVa l u e � ( , Min t ypmaxExpression, .. .] ) {one of} NctName NetAr:ray { NetLValue, . . . ) • { Neti.Value, . . . ) NetArray = See Array see Timing Control DelayConLrol - variablci.Val u e = see Procedural Assignment Continuous assignment module-<HERE>-endmodule inter face-<IIERE>-endinterface program-<IIERE>-endprogram genc raLe-<HERE>-endgenera te 46 Cop)Tight 0 1995-2006 by Doulol lld
  • 46. Assign Procedural continuous assignment - see Statement. Continuous assignments can drive nets or variables. The strength specification is not allowed with variables. A variable may be assigned using one continuous assignment or driven from a single output port. Such variables may not be initialized nor assigned using a procedural assignment. They may not be driven from more than one continuous assignment, from more than one output port, or a combination of these. A continous assignment is evaluated at time 0. The nets on the left-hand side of an assign are declared implicitly as wires if they have not been declared explicitly. This can be prevented by using the compiler directive "default_nettype none. Alternatively, a different default net type may be specified. After it is executed, a procedural continuous assignment remains in force on the assigned variable(s) until it is deassigned, or until another procedural continuous assignment is made to the same variable. A force on a variable overrides a procedural continuous assignment on that variable, until it is released, when the procedural continuous assignment again takes effect. Gotchas! Continuous assignments are not the same as procedural continuous assignments, although they are similar. Make sure that you place assign in the correct place. A continuous assignment goes outside any initial or always. A procedural continuous assignment goes where statements are allowed (inside Initial, always, task, function etc.). Use continuous assignments to describe combinational logic that can easily be described using a straightforward expression. Functions can be used to structure expressions. An always is usually better for describing more complex combinational logic, and may simulate more quickly than a number of separate continuous assignment statements. Continuous assignments are useful for transferring variable values to nets, when SystemVerilog requires nets to be used. For example, to apply test stimulus described in an initial to an inout port of a module instance. Cop)<ight c 199:;.2006 by Ooutos Ltd 47
  • 47. Assign • Procedural continuous assignments are deprecated and may be removed in a future version of SystemVerilog - don't use them! Exam les p Continuous assignment 11j re wire cout, c:in; [ 3 1 : 0] as sign sum, b; a, ( c o u L , sum} = a + b + cin; Procedural continuous assignment always @ (posedge Clock) Counl � Count + 1 ; 1 I Asynchronous Reset a l ways @ (Reset) if (Reset) assign Count = 0; 1 1 Prevents counting, until Reset goes low else deas sign C o u n t ; 1 1 Resume counting on next posedge Clock See Also Force, Net 48 Cop)l'lghtC 1995·2006 by Doutos Ltd.
  • 48. Associative Array An associative array implements a lookup table. The index type need not be integral. Storage is only allocated when it is used. Associative arrays are useful when the distribution of the data that is to be stored in an array is sparse. ll> This f eature was added in SystemVerilog Da ta Type Name [Da t a Type] ; Da liJ 1'ype Name [ * J ; 1 Index is any type 1 { Index is arbitrarily-sized integer) ( Methods) in t num ( ) ; funclion void delete ( [ i nput Index ] ) ; function i n t exists ( i np u t Index ) ; function i n L fi r s t ( ref I ndex) ; function i n t last ( r e f Index ) ; funclion i n L nexL ( re f I ndex) ; function i n t pr ev ( r e f Index ) ; function Where Index is an index value of the appropriate type. Methods num() - returns the number of indexes in the array. delete((lndex]) - deletes the specified index or (if an index is not specified) the whole array. exists(lndex) - true if an entry for the index exists. first(lndex), last(lndex) - assigns the first (last) index in the array to Index and returns 1 , or 0 if the array is empty. • next(lndex), prev(/ndex) - assigns the next (previous) index in the array to Index and returns 1 , or 0 if there isn't a next (or previous) entry. There are several other methods that apply to all arrays, including associative arrays (see Array Manipulation Methods). • For an integer or for the wildcard index type, a 4-state index containing X or Z is not allowed. • An empty string is valid as an index of type string. A null index is allowed as an index of a class type. An associative array can only be assigned to another associative array that has a compatible type and the same index type. Cop)1ight c 1995-2006 by Douloo Ltd 49
  • 49. Associative Array Associative array literals use the syntax '{index : value} or '{default : value} (See examples). • Associative array elements are unpacked, meaning that an individual element must be selected out of the array before using it in most expressions (apart from copy or comparison expressions). • An associative array allocates storage for elements individually as they are written. Associative arrays can be indexed using arbitrary data types. Exam les p Create an array of integer, indexed by string integer CounLWords [ s t r i n g ) ; CounLWords [ "one" ] I + ; Sdisplay ( " Therc a r e % d d i f ferent words " , CountWords . num) ; CountWords . delete ( "one" ) ; I I Deletes the "one" entry CountWords . dcJete; I I Clears the entire array Create an array of string, indexed by integers s l r i ng Table [ * ) ; Table ; ' { O : "Zcro " , l : "One " , 2 : "Two " , defaul t : "None " ) ; Sdi splay < " % s %s " , Table [ 0 J , Table [ 3 J l ; I I Displays "Zero None" See Also Array, Array Manipulation Methods, Dynamic Array 50 CopynghtC 1995-2006 by Oootos lld
  • 50. Assume Assume property is used to specify a property as an assumption for formal analysis. In simulation, an assume property is like a concurrent assertion that checks the behaviour of the testbench. Assume property can be used as a concurrent or procedural statement. .,.. This f eature was added in SystemVerilog [ AssumeLabcl : ] assume property PropertySpec ( PropertySpec) ; see Property always-<IIERE> i ni t ial -<IIERE> module-<IIERE>-endmodule gcnerale-<IIERE>-cndqeneralc i nLcrfacc-<HERE>-endi nterface program-<IIERE>-cndprogram For formal analysis, there is no obligation to check that the assumed properties hold. For simulation, the environment must be constrained such that the properties that are assumed will hold and the simulator must report if the property fails. • For random simulation, a dist constraint provides weights for choosing random values. This is called biasing. Gotchasl Assume property does not provide an action block, as the actions for an assumption serve no purpose. Exam les p al : assume property ( @ (poscdge elk) ack 1 -> ! ack) ; a2 : assume prope r l y ( @ (posedge elk) req d i s L ( 0 : -1 , 1 : -9 } ) ; See Also Assert, Constraint, Cover, Property Cop)Tight C> 1995-2006 by Dooloo Ltd 51
  • 51. Attribute Mechanism, not hidden in comments, used to specify properties about objects, statements and groups of statements in the source code. It may be used by various tools, including simulators, to control the operation or behaviour of the tool. Attributes are tool-specific and their meaning cannot be part of the language standard. (• A c c ribuLeSpecs, . . . • ) {one of} AttributeNarnc = Cons tanLExpression AttributeName A L t r i b u ceSpcc - As a prefix attached to ANY declaration, a module item, a Statement, a port connection, or an interface item (including modport). • As a suffix to an operator or a SystemVerilog function name in an expression. NOTE: As attributes may be specified almost anywhere, they are not included in the syntax descriptions in the Golden Reference Guide. All tools are required to process the attributes, so that any tool that does not understand an attribute must at least display a warning message that the attribute has been ignored. • If a value is not specifically assigned to the attribute, then its value is 1 . If the same attribute name is defined more than once for the same language element, the last attribute value will be used and a tool can give a warning that a duplicate attribute specification has occurred. • An attribute with no value defaults to bit, with a value of 1 . Otherwise, the attribute takes the type of the expression. Exam les p ( *s ynthesi s , para l le l_case actionl; 4 ' b? ? O l 4 ' bl ?O ? : acLion2; • ) casez (Opcode) Attribute attached to an operator A = B + ( * mode = "c la " * ) C; 52 Copyright 0 1995-2006 by Doulos ltd
  • 52. Attribute Attribute attached to a function call A - add ( * mode = " c l a " * ) (B, C ) ; Attribute attached to a conditional operator A = B ? ( no g l.i. L ch • ) C : D ; • Attribute attached t o a n interface ( *interface_att = 10 * ) interface I n l l . . . endinterface Attribute attached to a module definition ( ' optimize_power ' ) module Ml (. . . ) ; See Also Statement Cop)T'9111 0 1995-2006 by Doutoo ltd 53
  • 53. Begin Used to group statements, so that they execute in sequence. The SystemVerilog syntax often requires exactly one statement, for example in an always. If more than one statement is needed, the statements may be included in a begin-end block. ..,_ SystemVerilog blocks need not be named if they are to include declarations be gin [ ; Labe l ] [ Declarations . . . ] Statements . . . end [ : r.abel ] Declaration - ( one of} Variable 'l'ypedef Import Vi rtualin tcrface Localparam Parameter Overload See Statement. • A begin-end block must contain at least one statement. • Statements in a begin-end block are executed in sequence. Timing controls are relative to the previous statement. The begin-end block completes when the bottom-most statement has completed. begin-end and fork-join blocks may be nested within themselves and each other. Unlike in standard Verilog, if a begin-end block is to contain local declarations, it does not need be named (i.e. have a label), except in a function. • If a begin-end block is to be disabled, it must be named. • A matching block name may be specified after the end keyword, preceded by a colon. • A begin-end may have a statement label before the block. This is not a block name, because it does not create a hierarchy scope. Labc l B : beg.i.n end : LabclB 54 Copyright 0 1995-2006 by Doutos ltd
  • 54. Begin It is illegal to have both a label before a begin and a block name after the begin. A label cannot appear before the end. Gotchasl The Verilog LRM allows begin-end blocks to be interleaved during simulation. This means that even where a begin-end block contains two adjacent statements with no timing control between them, a simulator may choose to execute part of another process (e.g. statements in another always) between the two statements. This is a source of non-determinism in the language. begin-end blocks can be labelled to improve readability, even if there are no local declarations, and the block is not to be disabled. • Use local declarations for variables that will not be used elsewhere. This makes the intent of the declaration explicit. Exam les p i n i t i al begin Load = 0 ; Enable - 0 ; 0; Reset I I Time 0 #10 Reset = I ; I I Time 1 0 "25 Enable = l ; # 1 0 0 Load end = 1; ini t j a J begin : Assigninputs i n L ege r I ; for (I 0 ; I < 8; I § Period ' ( A, B , C ) end : Assignlnputs = I I Time 35 I I Time 135 I + 1) I; See Also Disable , Fork, Generate, Statement Copyright c 199S.2006 by Doutos ltd 55
  • 55. Bind Feature allowing the user to bind a module, interface, or program instance to a module or a module instance. This feature is intended to be used to associate reusable verification components with a design, without having to edit the source code for the design. For example, you can write a program containing properties and assertions, and bind it to a specific module or module instance, without changing the module's source code. IJil> This feature was added in SystemVeri/og The bind keyword is also used for function overloading - see Bind (Operator Overload). t one of) b i n d Modu 1 eOrinterfaceName [ : Bi.ndTargets, . . . ] Bindins tan L i a Lion; ll.ind Bind'l'arqet Bindins L a n L i a t i on; Dind1�rget - Moduleins LName [ConscBicSelects . . . ] ConstBiLSclect = [Constan tExprcssion] Bindins L a n t i a t .i on ; {one of) Proqram in s t a n t i a Lion Modulcins t a n ti a t i o n I n c e rfa ce insLan Li a t ion $unit module-<IIF:RE>-endmodulc gcnerate-<HERE>-endgenerate in te r face-<HERE>-endln Lerface When a program, module or interface instance is bound to a module or an instance, the instance becomes part of the bound object. If bound to a module, every instance of that module will contain the instance. The first form of the bind syntax specifies that the instance be bound in every instance of the module or interface, or, if a target list is present, to those instances only of the module or interface. • You may bind more than once into the same scope. You may not bind underneath another bound instantiation. 56 Copynght 0 1995-2006 by Doulol lld
  • 56. Bind Exam les p Binding a program to a module and a module instance: program Tcsl (input b it [ 7 : 0 ) Addr, Dala ) ; endprogram program CheckAddr ( i nput b i L [ 7 : 0 ) Addr, Max ) ; I I Immediate assertion Al : assert (Addr <� Max) else $error ( " Address is out or range " ) ; endprogram module RAM ( inpul bit [ 7 : 0 ] Addr, Data, . . .); endmodule module TcsLRAM; RAM RlM inst (Addr, Dala, endmodul e . . .); I I Binds a n Instance of the program Test to the testbench bind TestRAM Test Tcsl_inst (Addr, Dala l ; I I Binds an instance of the program CheckAddr to the RAM instance bind TestRAM . RAM_ins l CheckAddr (Addr, Data ) ; I I Alternative syntax for the above bind TestRAM : RAM insl CheckAddr (Addr, Da ta ) ; See Also Assert. Assume, Cover, Compilation, Instantiation, Module, Program, Property Copy<oght 0 t99S.2006 by Ooutos Ltd 57
  • 57. Bind (Operator Overload) Operator overloading allows the user to use the normal arithmetic and comparison operators with user-defined types, rather than call functions. This improves readability. .,.. This feature was added in SystemVerilog bind Operator funclion Data 1'ype FuncLionName ( Da ca Types , . . ) ; Operator + � (one of) . ' ++ I 't. != < <- > >- $unit module-<HERE>-cndmodule gc ncra le-<IIERE> -endgeneralc interface-<HERE>-cndinterface program-<IIERE>-endprogram begin-<HERE>-end fork-<HERE>-j o i n funct i on-<HERE>-endfunction package- <IIERE>-endpackage task-<HERE>-endLask • The overload declaration must be defined before it is used. • In the overload declaration, the arithmetic operators may be applied to data types that are normally illegal for them, e.g. unpacked structures. • The overload declaration basically links an operator to a function prototype. The arguments are matched, and the type of the result is then checked. Multiple functions may have the same arguments and different return types. • A cast must be used to select the correct function if no expected type exists or if more than one expected type is possible, due to nested operators. An assignment operator such as +- is automatically built from both the + and operators successively, where the = has its normal meaning. � No format can be assumed for 0 or 1 , so the user cannot rely on subtraction to give equality, or on addition to give increment. Also, no format can be assumed for positive or negative, so comparison must be explicitly coded. 58 COj)ynght C 1995-2006 by Ooulos Ltd
  • 58. Bind (Operator Overload) Exam les p typcdef strucL bit A; real 13 ; A Struct; A_Struct X, Y , Z, Q; bi nd � funcLion A_StrucL fadds (A_Struct, A_StrucL ) ; bind + function A_Struct faddr (A Struct, real ) ; bi n d 1 funclion A StrucL faddi (A_Struct, .i n L ) ; X + 2 . 0; assign Q assign y � X I 5; assign z +- X ; Equivalent t o Q = faddr (X, 2.0) Equivalent to Y = faddi (X, 5) I I Equivalent to Z = Z + X, i.e. Z = fadds (Z, X) II II See Also Bind, Function COpynght o t99!i-2006 by Dovtos Ltd 59
  • 59. Case A statement which conditionally executes at most one branch, depending on the value of the case expression. The case keyword is also used for the conditional generate construct (see Generate) and in production statements related to randsequence (see Rand sequence). � SystemVerilog adds the unique and priority prefixes, pattern-matching and set membership I Uni queOrPri ori ty) Expressi on , . . . Rxpress i on , . . . CaseK cy••ord ( f:xprcssion ) { Expression may be variable ) S t a tement : S t a t ement f Any number of case items 1 [default ( : ] 1 Need not be at the end 1 Statemen t ] endcase { Pattern-matching case 1 [ Un i queOrPri ority] CaseKeyword (Expression) Pattern [ &&& f"·xpression) Pattern [ & & & Expression] matches Sta tement Statement [default [ : ] Statemen t ] { Need not be at the end ) endcase {Set membership case 1 [ Uni queOrPri ority] case Val ueOrRange s , . . . V a l ueOrRanges , . . . [default [:] (Expression) inside Sta tement : Statement Statemen t ] { Need not be at the end 1 endcase Case Keyword {one of} case cas ex casez f one of} unique pr lority = Uni queOrPriori ty � Pat tern = see Matches Va l ueOrRange = see I nside See Statement. 60 Co!>!''9hl 0 1995·2006 by Doolot Lid {
  • 60. Case • The statement in the first matching case item is executed. If no expressions or patterns match the case expression and there is no default statement, the case statement has no effect. One default statement at most may be included. default need not be followed by a colon. Where a case item contains a comma-separated list of two or more expressions, the item is matched if the case expression matches any one of the expressions. Xs and Zs in a casex statement . and Zs in a casez statement mean "don't care". • The expression being tested in the pattern-matching case statement must have the same type as the type of the pattern in each case item. • In a set-membership case statement, the expression is compared with the case items using the Inside set membership operator. Gotchasl If more than one statement is to be executed for a particular label. the statements must be enclosed in a begin-end or fork-join block. Case items need not be mutually exclusive. so a SystemVerilog compiler will not report an error where the same expression has erroneously been repeated. The syntax of a casex or casez statement ends with the keyword endcase, not endcasex or endcasez. • An X or Z in the casex expression or a Z in a casez expression is matched with any value in a case label. This may give confusing simulation results. For simulation, always use default as the last case statement, to trap illegal conditions. casez is usually preferable to casex, because the presence of Xs in simulation may give misleading or confusing results. Use the alternative character ? for Z in casex and casez labels. This makes it clear that a "don't care" value and not a high impedance value is intended. Copynghl C 1995-2008 by Dcolo> Lid. 61
  • 61. Case Exam les p case (Addres s ) A <= 1 ; 0 1 : II Select a single Address value begin II Execute more than one statement 1I Pick out several Address values A <= 1 ; B <- 1 ; end 2, 3, 4 : c <= 1 ; default I I Mop up the rest Sdispl ay ( " I l l egal Address value %h in %m a t %L " , Address, $ rea l time ) ; endcase casez ( { A, B, C , D , E [ 3 : 0 ] } ) B ' bl??????? Op <= 2 ' b0 0 ; B ' b0 1 0 ? ? ? ? ? Op <- 2 ' b0 1 ; Op <= 2 ' b1 0 ; B ' b 0 0 1 ? ? ? 00 deiaulL Op <- 2 ' bxx; endcase Pattern-matching case statement: typedef union tagged void Invalid; int Val i d ; VInt; VInt v ; case ( v ) matches Lagged Invalid tagged Valid n $di splay ( " v i s Invalid" ) ; $display ( " v is val id wilh value %d" n ) ; I endcase See Also Generate, If, Matches, Priority, Randsequence, Union, Unique 62 C4pyrightC 199S.2006 by Ooulos ltd
  • 62. Casting Used to change a data type into another data type. Casting prevents warnings/errors being generated when the left and right hand sides of an assignment are different sizes/types of data. ..,. This feature was added in SystemVerilog Casti ngType ' ( Expression) Ca stingType � {one of) byte shorlint inl longinl integer time bit logic reg shortreal real realtime UnsignedNumber { Not 0 ) signed unsigned Name See Expression. A positive decimal number as a data type means a number of bits to change the size. 2 ' (a • + 1) The signedness can be changed. unsigned ' ( a ) The expression inside the cast must b e an integral value when changing the size or signing. When changing the size, the signing passes through unchanged. When changing the signing, the size passes through unchanged. An integer or real variable is cast to a time value by using the integer or real as a delay. # 9 . 1 5 ; II Multiply by time unit and round according to time precision Structures can be converted to bits preserving the bit pattern, i.e. they can be converted back to the same value without any loss of information. The type of the elements in an unpacked structure or array must be valid for a packed representation in order to be cast to any other type, whether packed or unpacked. Copy!1ghl 0 1995-2006 by Dootos ltd 63
  • 63. Casting Bit-Stream Castin g Types that can be packed into a stream of bits are called bit-stream types. A bit-stream type is a type consisting of the following: Any integral, packed, or string type Unpacked arrays, structures, or classes of the above types Dynamically-sized arrays (dynamic, associative, or queues) of any of the above types II is possible to convert freely between bit-stream types using explicit casts. When a dynamic array, queue, or string is converted to the packed representation, the item at index 0 occupies the MSB. When an associative array is converted to the packed representation, items are packed in index-sorted order with the first indexed element occupying the MSB. If A is of bit-stream type BitStrA and B is of bit-stream type BitStrB, it is legal to convert A into 8 by an explicit cast: B - B i t S L r B 1 (A) ; • If both BitStrA and BitStrB are fixed sized unpacked types of different sizes then a cast generates a compile-time error. • If BitStrA or BitStrB contain dynamically-sized types, then a difference in their sizes will generate an error either at compile time or run time. typedef struct [ b i L [ 3 : 0 ) a; shortint b ; } StrucLu re ; Structure S ; inL A � inL ( S ) ; 1 1 1 Illegal conversion from 20-bit structto 32-bit int structure B - Structure (A) ; I I Illegal conversion from 32-bit int 1 I I to 20-bit struct Gotchasl When a s hortreat is converted to an Int. its value is rounded. So the conversion can lose information. • Use the logic type if you want to preserve the X values. The bit data type loses them. System functions $itor, $rtoi, $bitstoreal, $realtobits, $signed, $unsigned may also be used for casting. $cast system task can also be used for casting. 64 Copyright c 1995-2006 by Ooulos Lid.
  • 64. Casting Bit-stream casting can be used to convert between different aggregate types, such as two structure types, or a structure and an array or queue type. This conversion can be useful to model packet data transmission over serial communication streams. typcdef struct bit A; unlon ( lnt j , real f) B; Struct l ; typedef bit [$bl ls ( Struc t l ) - Strucll s [ 7 : o 1 ; II C_Type c - C_Type ' ( S [ l J J ; II s [2] II = Struc l l ' (C) ; 1 : 0 ] C Type; _ Unpacked array of structures Convert structure to array of bits Convert array of bits back to structure See Also Expression, $cast COpyright C> 199S.2006 by Ooulos ltd 65
  • 65. Chandle chandie is a special SystemVerilog type that is used for passing C pointers as arguments to imported DPI functions. � This feature was added in SystemVeri/og chandle Varlabl eName s , . . . ; See Declaration Chandles can be used within a class. Chandles can be passed as arguments to functions or tasks. Functions can return chandle type. Ports cannot be made of chandle data type. • chandle type cannot be used in sensitivity lists, event expressions, packed types. continuous assignments, untagged unions, • chandle type is directly compatible with void* C type. • The size of chandle data type is platform dependent, but must be at least large enough to hold a pointer on the machine in which the tool is running. The default initial value of a chandle variable is null (which is 0 on the C­ layer of the DPI). Only the following operators are valid on chandle variables: equality (==), inequality (!=) with another chandle or with null, case equality (===). case inequality (!==) with another chandle or with null . chandle variables can be tested for a boolean value (0 if the chan die is null and 1 otherwise) Only the following assignments can be made to a chandle: Assignment from another chandle Assignment to null 66 Copyright 0 1995-2006 by OotJios Lid
  • 66. Chandle Exam les p Standard C functions imported in SystemVerilog: import import "DPT-C" function chandle malloc ( i n t s i ze ) ; D PI C f u n c l i on void free ( chandlc ptr ) ; " - " See Also Import "DPI-C" Copyrighlco 1995-2006 by Ooulos Lid 67
  • 67. Class A class is a user-defined data type, SystemVerilog classes support object­ oriented modelling by providing mechanisms for data hiding, abstract classes, inheritance and polymorphism. A class includes data (referred to as properties) and subroutines (i.e. tasks and functions, called methods) that operate on that data. Both properties and methods are called the members of the class. Classes may include random variables and constraints, to support random and directed-random testing . .,.. This f eature was added in SystemVerilog [virtua l ] c l ass [ L i fetime] ClassName [ H ( [ ParameterPortLi s t ) ) 1 [extends ClassType [ ( Lis tofArgumen ts ) ] ] ; [ Timeun i t ] [ ClassiLcms . . . ] endclass 1 : ClassName] ClassiLem - { one of) TypeDef Class ClassProperty ClassMethod ClassConsLraint ClassPrope rty � {one of) [ PropertyQualificrs . . . ] canst Da taDeclara tion [ ClassJtemQualificrs . . . ] DaLa Type ConstName [ - Cons tantl·:xp ression ] ; ClassMcLhod • (one of) [ MethodQual i fiers . . . ] TaskDe c l a ration !MethodQua l i fiers . . . ] FunctionDeclaration extern (MethodQua l i fie rs . . . ] 1'askProto type extern [ Me thodQualifiers . . . ] FuncL i onPrototype Cla ssConstrainL - ( one of) Constrai ntPro totype Cons trai n t Declaration Proper tyQua l i fier - (one of) rand randc Classi temQua lifier Me thodQual ifier - (one of) virtual ClassitemQua l i f i e r ClassiLemQua l i fi er 68 = ( one of) static pr o t e c ted local Copyrtghl c 19!15-2006 by Douloa Lid
  • 68. Class Lifetime = { one of) s t a ti c automatic Da LaDeclara tion {one of) Vadable Cons L a n t Typedef FunctionProto type TaskProto Lype = - See Function See Task $un i t module-<HERE>-endmodule generate- <IIERE> -cndgene rate program-<HERE>-endprogram c l a s s -<HERE>-endclass packagc-<HERE>-endpackage i n t e r face-<IIERE>-endinlerface By default, class melhods have automatic lifetime for their arguments and variables, regardless of the lifetime attribute of the scope in which they are declared. • Class properties can be any data-type, except for net types since these are incompatible with dynamically allocated data. If only one version of a class property is required to be shared by all instances, it can declared as static. Class properties that include an initializer in their declaration are initialized before the execution of the user-defined class constructor. Thus, initializer values can be overridden by the class constructor. • A class method can also be declared as static. A static method can only access static class properties or call static methods of the same class. Access to non-static members or to the this handle within the body of a static method is illegal. Static methods cannot be virtual. Static class properties can be used without creating an object of that type. An object is an instance of a class. In order to use an object, first a variable of that class is declared. (This holds an object handle). Then an object of that class is created using the new function, and is assigned to the variable. The default value of an object handle is null. ACla s s OneC; I 1 Declare a variable of ACiass. I I OneC can hold an object handle. Cop)"ighl C 1995-2006 by Oouk)s ltd. 69
  • 69. Class On eC - n ew ; I I Initialise var iable Or, equivalently, AClass Onec - new; I I Declare and initialise OneC • Every class has a default new method, also called the class constructor. The default constructor first calls its parent class constructor (super. new()), if any, and then initialises each member of the current object to its default (or uninitialized value). The new method may be overridden. • Object methods and properties can be accessed using the handle's name and the name of the property/methods, separated by the dot (.) operator. • Classes can be parameterised in the same way as modules, interfaces, etc. • A parameterized class can extend another parameterized class. Subclasses and Sup erclasses A derived class (or subclass) is an extension of a class. • The superclass (parent class or base class) is the class from which the current class was derived. It is illegal to directly assign a superclass handle to a variable of one of its subclasses. However, it is legal to assign a superclass handle to a subclass variable if the superclass handle refers to an object of the given subclass. $cast can be used to check if an assignment is legal. When a subclass is instantiated, the class method new is invoked. If the initialisation method of the superclass requires arguments, and the arguments are always the same, they can be specified when the class is extended. Another way is to call the superclass constructor is by using the super keyword: cl ass MyCar extends Car (Blue , Limo) ; I I or function new ( ) ; super . new (Blue, Limo) ; I I Must be executed first in function new end function Gotchasl If the new() function of a subclass is overridden, it does not call the parent class's constructor by default. This will almost always need to be called explicitly as the first statement in the overloaded constructor. 70 Copyright C 1995·2006 by Ooutoo Lt4
  • 70. Class • Parameterised classes (also called generic classes) can be particularly useful when using types as parameters. Any class can be set as parameters (e.g. another class, a struct, etc.). • Classes are useful in testbenches, and essential when directed-random testing is used. Exam les p Class definition class Register; I I Properties log i c [ 7 : 0 ] data; I I Methods function new (logic [ 7 : 0 ] d data � d; endlask o ) ; I I Constructor task load (logic [ 7 : 0 ] d) ; data d; endLask � endclass Using the Register class Register accum; I I accum stores a handle to an object of class Register accum � ne1<; I I Create a new Register object; its handle is in accum Regi.sLer accuml - new ; Register accum2 = new ( 8 ' ff ) ; I I Alternative 11 Initialise Register accum3 [ 1 0 ) = new ; I 1 Array of 1 0 Registers Rcgiste r . data � S ' h l f ; I I Store value in data member Regisler . l oad ( 8 ' hl ( ) ; 11 A better way of doing it Parameterised classes class i (parameter n � 8 ) Register; logic [ n- 1 : 0 ) data; endclass Cop)<lght C> 199!;.2006 by Doutos ltd 71 )
  • 71. Class Register H ( 8 ) accum8 - new; I I 8-bit register Register i ( . n ( l 6 ) ) accuml6 � new; I 1 1 6-bit register class # (pa rameter type T) Regis Ler ; T dat:a; endclass I I int register Register # (i n t ) accum8 � new; Register i (b i t ( 7 : 0 ] ) accuml6 new; I I bit[7:0] register Derived class class ShiftRegister extends Register; extern task shlftlefl ( ) ; extern task shiflright ( ) ; endclass 1 I Out of class method definitions task Shi[LRegisler : : shlftlefl ( ) ; data - data << 1 ; endlask Lask ShiftRegister : : s h i ft:right ( ) ; dota = data > > 1 ; end task ShiftRegister SR - new; S R . load ( 8 ' h5 5 ) ; 1 1 Inherited method SR . shi ftleft:; I I data now has 8'aa See Also Canst, Constraint, Extends, Extern, Local, New, Operators, Protected, Rand, Static, Super, This, Virtual 72 Copyright 0 t99S.2006 by Ooulos ltd
  • 72. Clocking A clocking block is a set of signals synchronised to a particular clock. It basically separates the time-related details from the structural, functional and procedural elements of a testbench. Clocking blocks support a cycle-based verification methodology . ..,. This feature was added in SystemVeri/og ( Declaration 1 [default ] clocking [ClockingName ] ClockingEven L ; C l ockingitems . . . endclocking [ : Clocki ngName ] 1 Default clocking block 1 dcfaull c l ocking ClockingName; (one of I default Defaul tSkco1; input [ Cl ockingSkew] ClockingDcclAssigns, output [ ClockingSkcw] Clocki ngDeclAss igns, inpul [ C locki ngSket�] output [ Clocki ngSkew] Cl ockingitem - ClockingDeclAss;.gns, inouL ClockingDcclAssigns, . . . , ProperLy Sequence S i gnal Name [- HierarchicalName) Defaul tSkew ( one of( � input ClockingSkew outpul C l ockingSkew input ClockingSkew output ClockingSkew (one of) posedge [Dcl ayCon trol] ncgedgc [ DelayCon trol) ClockingSkew = Delaycon trol Clocki ngEvenL = ( one of) @ Name @ ( Even tExpressionl {See Timing Control) De layCon t rol { Driving 1 ClockingDrive = {one of) ClockingName . Name <= [ R R CyclcDelay] Expression lA CycleDelay ClockinqName . Nume <� Expression CyclcDelay = see Timing Control Copynght C 1995-2006 by Ooolos ltd 73
  • 73. Clocking modul c-<IIERE>-endmodule program-<HERE>-endprogram generate-<HERE>-endgenerate inter face-<IIERE>-endin Ler face For ClockingDrive see Statement. The clocking construct is both the declaration and the instance of that declaration. Clocking blocks cannot be nested. • Clocking blocks have static lifetime and scope local to their enclosing module, interface or program. • The ClockingSkew is the number of time units away from the clock event a signal is to be sampled (i.e. input) or driven (i.e. output). Input skew refers to a time before the clock, while output skew refers to a time after the clock. A default clocking can be used to specify the default clocking block for all cycle delay operations inside a specific module, interface or program. inputs cannot be driven and outputs cannot be read. inouts can be both read and driven. • A single skew can be specified for the entire clocking block by using the default keyword. If not specified otherwise, the default Input skew is 1 step and the default output skew is 0. An input skew of #1step indicates that the value read by the active edge of the clock is always the last value of the signal immediately before the corresponding clock edge. A step is equivalent to the time precision. • Clocking block outputs and inouts may be used to drive values onto their corresponding signals, at a certain clocking event and with the specified skew. A drive does not change the clock domain input of an in out signal. • The clocking signals are available via the clocking block name and the dot ( . ) operator. A signal from a clocking block can also be specified by its hierarchical name (cross-module reference). • Explicit synchronisation is done via the event control operator @ . All events are synchronised to the clocking block The execution can be delayed by a specified number of clocking events using the ## operator. 74 T '911 Cop) I 0 199!).2006 by 0ouJos ltd
  • 74. Clo cking • If multiple synchronous dr ives are applied to the same clocking block output or inout at the same simulation time, a run-time error is issued and the connicting bits are set to X for 4-state ports or 0 for 2-state ports. Gotchasl The signal directions in the clocking block within the testbench are with respect to the testbench, not the device-under-test (OUT). A OUT input will correspond to a clocking output and a OUT output to a clocking input. If writing two clocking events one immediately after the other, the first one will be overridden. @ ( c) @ (d) x is equiv. to @ (d) X • Use one or more clocking blocks in a testbench to separate driving and sampling timing details from the functional test description. The clocking event of a clocking block is available directly by using the clocking block name, clocking cb @ (posedge Clk ) ; cndclockjng @ (cbJ I I Equivalent to @ ( poscdgc C l k ) Exam les p I n the following example, dr iving and sampling is synchronised to the falling edge of Clk. The default skew is to drive clocking outputs (OUT inputs) 2ns after the falling edge of Clk and sample the clocking inputs (OUT outputs) 1 ns before the falling edge of Clk. The drive skew for the outputs UpOn and Load are overridden. clocking CBl @ ( negedge Cl k) ; default input # l n s output # 2 n s ; j nput Q; output Enable; output Hslep UpDn � top . Counte r . UpDn output posedge Load ; endclocking Synchronisation statements - the events are sampled according to the clock domain timing: COp)<O)hl c 1995·2000 by Doolos Lid. 75
  • 75. Clocking I I Wait for the next change of a from CB1 domain @ (CBl . Q ) ; @ (negedge CBl . Load) ; I I Wait for negative edge of signal CB1 .Load @ (posedge CBl . Load or negedge CBl . UpDn) ; @ (CB l . Q [ 1 ] ) ; @ (CBl . Q [ 2 : 0 ] ) ; I I Wait for the next change of bit 1 of CB1.a I I Wait for the next change of the specified slice Clocking Block Drives CB1 . Q ( 2 : 0 1 <= 3 ' h 3 ; I 1 Drive 3-bit slice of a i n current cycle # # 1 CB1 . Q <c 4 ' h z; I I Wait 1 Clk cycle and then drive a I I Wait 3 Clk cycles, then drive bit 3 of a # # 3 CB1 . Data [ 3 ] <= 1 ' bO ; CBl . Q <- # 11 2 Tnt_Q; I I Remember lnt_a, then drive a after 2 clocks Multiple clocking blocks: interface I l (input b i t clock1 ) ; inlerface J2 ( inpul b i l clock?. ) ; endinterface endi nterface module tf ( I l A, J 2 B ) ; clocking cbl @ (posedge A . clock l ) ; defaull input # 2 output # 5 j npul A . address ; oulput A . da l a ; endclocking clocking cb?. @ (posedge B . clock?. ) ; default input # 1 oulput # 1 ; output B . s ta r t , B . s i z c ; endclocking initial begin Test cbl . A . data <• 1 ; end module CtrlMod; default clocking c b l ; II Clocking blockcb1 set as default I I inside CtriMod module initial begin j f (cbl . A . data U 10; 1) I I Delays execution by 1 0 cycles using the I I default clocking (A.clock1 ) endmodule endmodule 76 CopYiight 0 1995-2006 by Ooulol Ltd
  • 76. Clocking inLcrface ABus (inpuL logic cl k) ; I I Interface with modports wire a , b , c, d ; c l ocking c b @ (poscdge elk ) ; input a ; output b , c ; inoul d; properLy p l ; req # # ( 1 : 3) gnt; endproperty endclocking modport OUT ( input e l k , b , c, l / OUT modport outpuL a , i nout d) ; modport STB (clocking cb ) ; modport TB ( input a , output b, c, I I Synchronous testbench modport I I Asynchronous testbench mod port inout d ) ; endinlerfacc module AModl (ABus . DUT b) ; endmodule program TB ( ABus . STB b l , AAu::; . STO b2 ) ; I I 2 synchronous ports Lypedef virlual ABus . STB SYNCTB; task ATa s k (SYNCTB s ) ; s . cb . a <� 1 ; endlask endprogram module Lop; logic e l k ; ABus b l ( e l k ) ; ABus b2 ( c l k ) ; fiModl Ml (bl) ; TB TesL (bl , b 2 ) ; endmodule See Also Interface, Program Copyrlghl 0 1995-2000 by Doulos Lid. 77
  • 77. Comment Comments may be (should be!) included to document the SystemVerilog source code. {one of) ( Single line comment l II I• . . - •! ( Multi-line comment) Nearly anywhere. but not so as to split operators, numbers, strings, names and keywords. • A single line comment starts with the two slash characters and ends at the end of the line. A multi-line comment starts with I' and continues, possibly across multiple lines, until the next */ Multi-line comments may not be nested. However. there may be single line comments inside a multi-line comment, where they have no special meaning. Gotchasl r ... r *I ... *I - the comment ends at the first */, and the second r is ignored. This would almost certainly give syntax errors. ·-- Use single line comments throughout. Only use multi-line comments where it is necessary to comment out a large section of code, for example during development and debugging of the code. Exam les p II This is a comment I· S o i s this - across Lhree lines 'I module ALU / ' 8 -bl t ALU ' I (A, B , Opcode, F) ; 78 Cop)1KJhl c 1995-2006 by Doulos Ltd
  • 78. Compilation Unit SystemVerilog supports separate compilation using compiled units. A compilation unit is a collection of one or more SystemVerilog source files compiled together. A compilation-unit scope is a scope that is local to the compilation unit. It contains all declarations that lie outside of any other scope. $unit is the name used to explicitly access the identifiers in the compilation-unit scope. II> This feature was added in SystemVerilog Compilation-unit scope is similar to an implicitly defined anonymous package. Because it has no name, the compilation-unit scope cannot be used with an import statement, and the identifiers declared within the scope are not accessible via hierarchical references. However, the special name $unit can be used within a particular compilation unit, to explicitly access the declarations of its compilation-unit scope. Tools must provide a mechanism to specify the files that make up a compilation unit, as well as a mechanism to specify that all of the files compiled together are a single compilation unit. By default each file is a separate compilation unit. • The contents of files included using one or more 'include directives become part of the compilation unit of the file they are included within. • The compilation-unit scope can contain any item that can be defined within a package. These items are in the compilation-unit scope name space. The following items are visible in all compilation units: modules. macromodules, primitives, programs, interfaces and packages. • Items defined in the compilation-unit scope cannot be accessed by name from outside the compilation unit. Compiler directives from a compiled unit will not affect other compilation units. This may result in a difference of behavior between compiling the units separately or as a single compilation unit containing the entire source. Exam le p bit b ; funcLion AFunc; int b ; b $uniL : : b ; endfuncLion = Copyrlghl 0 1995-2006 by D®los Lid. I I $unit::b is the one outside 79
  • 79. Compilation Unit See Also Package, Sid::, $unit 80 Copyrighl0 1995-2006 by Doulos Lid
  • 80. Config Explicit set of rules specifying which module, primitive, interface or program definitions are to be used for any given instance in a design. config ConfigName; design [ L i b ra ryNamc . ] CcllNamcs ConfigRuleSta tements . endconfig . . [ : Conf i gNamc] configRvleSta tement - ( one of) defaul t LiblistClause ; Ins t anceCla use LiblisLClausc Ins tanceClause UseClause Cel l Clause LiblistClavse CellClause UseCl ause ; TnstanceCl ause instance HierarchicalName CellClause cell = [ L ib r a ryName . ] Ce l l Name Li bl i s LCla use = J ibl i s t Libra ryNames . . . UseCl ause use = [ L i b raryName . ] Cel lName [ : co n f i g ] Sunil The design statement names the library and cell of the top-level module or modules in the design hierarchy configured by the config. There will be one and only one design statement, but multiple top-level modules may be listed in the design statement. The cells identified cannot be configurations themselves. The design statement must appear before any config rule statements in the config. If the LibraryName is omitted, then the library containing the config will be used to search for the cell. The default clause selects all instances which do not match a more specific selection clause. The use expansion clause cannot be used with a default selection clause. Copyr;ghlC 1995-2006 by Dou1os Lid 81
  • 81. Config The instance clause is used to specify the specific instance to which the expansion clause shall apply. • The cell selection clause names the cell to which it applies. • It is an error if a library name is included in a cell selection clause and the corresponding expansion clause is a liblist expansion clause. The libllst clause defines an ordered set of libraries to be searched to find the current instance. Liblists are inherited hierarchically downward as instances are bound. • The use clause specifies a specific binding for the selected cell. A use clause can only be used in conjunction with an instance or cell selection clause. It specifies the exact library and cell to which a selected cell or instance is bound. • A configuration must not change the binding of a package. Most config declarations will include a default liblist clause, specifying which library(ies) to search for module descriptions. A use clause may specify a module with a different name from the instantiated module. This is okay so long as the instantiated module and the used module have matching port lists. There is at present no way in Verilog for configurations to patch-up differences in port or parameter listsI There are two possible ways of configuring hierarchically an entire design or testbench: • • 82 Method 1 : Specify all the hierarchy details within a configuration. This is possible because the lnstanceName in a configuration's Instance clause can be a fully hierarchical name. Method 2: Use a ready-configured sub-design, rather than an unconfigured module, in a top-level instance. This is achieved by specifying a configuration (instead of a module) in a use clause. Copyright 0 1995-2006 by Doulos Lid
  • 82. Config Exam les p modulQ Top ( . . . ) ; Ace U l ( . . . ) ; Ace U2 ( . . . ) ; modu l e Ace ( . . . ) ; Adde r Al ( . . . ) ; Adde r A?. ( . . . ) ; con f i g MyCon f i g ; I I Simple config de s ig n MyDesign . Top; default liblist MyDesign; inslancc Top . U2 usc MyGa Lcs . lcc ; endconfig c on fi g MyCon f i g l ; 1 1 Hierarchical config - method 1 des i gn MyDesi gn . Top ; instance Top . U2 . Al u s e MyLib . Adder ; cndconfig con fig M yC on f ig 2 ; I I Hierarchical config - method 2 design My Dc s i g n . To p ; instance Top . U2 . A l u s e MyLib . Addcr; i nstance Top . U l . A2 use MyGates . CarrySel ecLAdder con f i g ; cndconfig con f i g CarrySc lectldder; des i gn MyGa t e s . Ca r r ySe le ctAdder ; endconfig See Also Library Cop)'t'ighl C 1995-2006 by Doukn Lid 83
  • 83. Const A constant calculated after elaboration. Therefore, it can contain an expression with any hierarchical path name or it can be created automatically during simulation . ..,_ This feature was added in SystemVerilog con s L [ Li fetime] DataType Name Lifetime Da taType � = Con s tan t J-:xpressian ; {one of] static automatic see Variable See Declaration A localparam must be set during elaboration, while a canst can be set during simulation (e.g. in an automatic task). An automatic const constant can be set to any expression that would be legal without the const keyword. A static const constant can only be set to an expression of literals, parameters, local parameters, genvars, enumerated names, a constant function of these, or other constants. • The parameters, local parameters or constant functions can have hierarchical names because constants declared as const are calculated after elaboration. • A class property can be made read-only by declaring it as const. There are two forms of read-only variables: global constants and instance constants: Global constant property: includes an initial value as part of its declaration. It is usually also declared as static. Instance constant property: does not include an initial value in its declaration, only the const qualifier. It can be assigned a value at run­ time, but the assignment can only be done once in the corresponding new function. It cannot be declared as static. 84 COpyright C 19952006by OooloS Lid
  • 84. Const Exam les p const int A = 1; class MyClass ; const int G = 1; I I Global constant con st l n l I ; II function new ( i nt Instance constant x) ; I = 10; II Instance constant assigned in constructor. endfunction cndclass See Also Class, Localparam, New, Parameter, Specparam, Static Copyright C 1995-2006 by Doulos L td. 85
  • 85. Constraint Constraints are used to determine the values of random variables. Constraint blocks are class members. ..,. Tllis feature was added in SystemVerilog t Prototype ) ( st a t i c ) constraint Name; t Declaration ) [static ) constraint Name { [ Constrain t/JlockiLems . . . ) } t Extern Declaration ) ( s ta t i c] constraint ClassName : : Name { [ Cons t ra i n t Hlo ck itcms . . . I } Conscra intBlocki tem = tone of) ConstraincExpression solve Constrain tNames , . . . before Conscrain tNames, . . . ; ConstraintExpressi on - t one of) Express ion [ d l s L [ Di s L i tems, . . . }) ; Expression -> Constra i n LSeL if ( P.xprr-.s s i on ) ConstraintSet [else ConstraintSet} foreach (ArrayName [LoopVariables . . . ] ) Cons traintSet Cons LrainLSeL = tone of) ConstraincExpression { [ Constrai n t Expressions . . Di s t it ems = . } } Val ueOrRange [ Di s L Wci gh t ) Di s tWci gh L = tone of) := Expression : / expression ValueOrRange = I one of) Expression [ Expression: Expression] { Methods ) task Obiec t [ . Name ] : : cons t ra i nL mode (bl l on_off) ; function i n t Object . Name : : constra int_mode ( ) ; $unit module-<HERE>-endmodule genera tc-<HERE>-endgeneratc program-<HERE>-endprogram 86 Cop-,lghlC> 1995-2006 by Ooulos L1d
  • 86. Constraint class -<HERE> -endclass pac kagc- < HERE>-e ndpa c kage in t e r face -<HERE> - e ndi n Le rfa ce See also Rand • In a constraint expression, you are not allowed to call tasks or use operators with side-effects (e.g. ++ and --). • In a constraint expression, you are allowed to call functions but only with certain limitations: Functions cannot contain output or ref arguments (const ref are allowed) Functions should be automatic (or preserve no state information) and have no side effects Functions cannot modify the constraints, e.g. calling rand_mode or constraint_mode methods Functions will be called before constraints are solved, and their return values will be treated as state variables • Random variables used as function arguments will establish an implicit variable ordering or priority. Constraints that include only variables with higher priority are solved before other, lower priority, constraints Random variables solved as part of a higher priority set of constraints become state variables to the remaining set of constraints, e.g. class ACl a s s ; rand i n t x , y; constraint Cl (x < = Func ( y ) ; ) constrainl C2 ( y == a ) ; ) I I C2 is solved before C 1 , I I which uses the values o f y and Func(y) a s state variables endclass Circular dependencies created by the implicit variable ordering will produce an error • • Function calls in active constraints are executed an unspecified number of times (at least once), in an unspecified order The inside operator is used to define a set of values. Its negated form means that expression lies outside the set. The to reach construct is used to specify iteration over the elements of an array. The array can be of any type (e.g. fixed-size. dynamic, associative, or queue). Each loop variable corresponds to one of the dimensions of the array. CopyrightC> 1995-2006 by Doulos Ltd 87
  • 87. Constraint Constraint block bodies can be declared outside a class declaration, similar to external task and function bodies. • dlst gives a weighting to a set of values. The distribution set is a comma-separated list of integral expressions and ranges. Each term in the list can optionally have a weight, specified using the := or :/ operators. The default weight is := 1 . • The : = operator assigns the specified weight to the item, or if the item is a range, to every value in the range. The : I operator assigns the specified weight to the item, or if the item is a range, to the range as a whole. If there are n values in the range, the weight of each value is range_weight I n. (See Examples) • The weighting values need not be normalized to 100%. dist cannot be applied to randc variables. A dist expression requires that expression contain at least one rand variable. Constraints support only 2-state values. 4-state values (X or Z) or 4-state operators (e.g., ===, !== ) are illegal and will produce an error. All expression operators are treated bidirectionally, including the implication operator (-> ). In an implication (->) the expression must be integral. if-else constraints are equivalent to implications. Both are bi-directional, i.e. the right-hand ConstrainSet potential constrains the left-hand Expression. E.g. a -> b means that if a is true, then b must be true too. Conversely, if b is false, then a must be false too. In other words !a II b is always true. Only integral rand variables are allowed in solve blocks. There must be no circular solve dependencies • Anonymous or in-line constraints can be specified using the randomize() with construct with random variables. Methods • The constraint_mode() task method can make a specific constraint active (on_off = 1 ) or inactive (on_off = 0). If applied to a class object it affects all the object's constraints. If a constraint is defined as static, all instances of the constraints are affected by a call to the constraint_mode() method. • Object is any expression that yields the object handle in which the constraint is defined. The constraint_mode{) function method returns the constraint's current active state. It returns 1 if the constraint is active (ON), and 0 if the constraint is inactive (OFF). 88 Copynght C 1!195-2006 by OOulos Ltd
  • 88. Constraint Calling the randomize() method of a class that has no random variables causes the method to behave as a checker, i.e. to assign no random values, and only return a status: 1 if all constraints are satisfied, 0 otherwise. • An inactive constraint is not considered by the randomize() method. All constraints are initially active. Gotchasl A solve constraint block forces the solver to partially order random variable evaluation and may affect the relative probability of certain value combinations. However, it does not change the solution space, and so cannot cause the solver to fail. Exam les p consLrainL c1 { a -- 4 ; ) constraint c2 {b > 3 ; c > c o n s t r a i n t valid_parity 10; ) { p a r i t y_ok d i s L { 0 : -1 , 1 : =9 ) ; ) { s i ze = = B I G => l en > 2 0 ; l constra j n t c3 { 1, {2: 3J l ; } II c o n s t r a i n t c4 { i inside c o n s l r • l n l cS Equiv. to i==1 II i==2 ll i==3 { solve c1 before c2 ; ) x I I x can't be 1000 ! = 1000 ; x dist 1 10 0 11 := 1 , 1 000 : - 2 , 2 0 0 0 := 5 } II x is equal to 1 00 or 2000 with weighted ratio of 1 - 5 x d i s t { J OO : = 1 , {4:6] : I 2, 2000 := 5} I I x ls equal to one of I I 100, 4, 5, 6 or 2000 with a weighted ratio of 1 - 2/3 - 2/3 - 2/3 - 5 See Also Class, Inside, Rand, Std:: Cop)<ighl Q 1995-2006 by Doulos �td 89
  • 89. Cover Similar to a concurrent assertion, cover property is used to monitor sequences and properties of the design for coverage. cover property can be used as a concurrent or procedural statement. The cover property statement is not related to functional coverage using the covergroup. construct. � This feature was added in SystemVerilog [ Cove rLabel : ] cover property ( PropertySpcc) Sta temen tOrNul l PropertySpec - see Property S t a tementOrNull - ( one of) Statement SuniL always-<IIERE> ini tial-<HERE> OiOdulc-<HERE>-endmodule generate-<HERE>-endgenerale interface-<HERE>-endinterface package-<HERE>-endpackaqe p roqram-<HERE>-endprogram Pro e p rty Coverage • The results of coverage statement for a property contain: • Number of times attempted • Number of times succeeded • Number of times failed Number of times succeeded because of vacuity • • • 90 Each attempt with an identifier (attempt/D) and time Each success/failure with an identifier (attempt/D) and time The StatementOrNu/1 is executed every time a property succeeds. The pass statement cannot include any concurrent assert, assume or cover statement. Copi"QhtO 1995·2006 by Doulos Ltd
  • 90. Cover Se uence Coverage q The results of coverage statement for a sequence contain: Number of times attempted • • Each attempt with allemptld and time • • Number of times matched (each attempt can generate multiple matches) Each match with clock step, attempt/0, and time StatementOrNu/1 is executed for every match in the sequence. Exam les p module Top ( i nput b i t elk) ; logic a , b ; sequence s l ; @ ( posedge e l k ) a # # 1 b; endsequence Labe l : cover properly ( � 1 ) ; endmodu l e See Also Assert, Assume, Bind, Expect, Property, Sequence C<l!>Y'•Jhl 0 1995-2006 by Oouloo Lid 91
  • 91. Covergroup The covergroup construct i s a user-defined type that encapsulates the specification of a coverage model. Covergroup is not related to property coverage using the cover property statement. .,. This feature was added in SystemVerilog 1 Declaration l covcrgroup CovergroupName [ ( [ Por�s, . . . ] ) 1 [ CovcrageEven t 1 ; CoverageSpecOrOptions . . . endgroup [ : CovergroupNamc 1 1 Instantiation 1 new [ ( Arguments, CovcrgroupName [Va riablcName) . . .) 1; { Options for covergroup instances} {one of} T nsLanceNarne . option . OptionName CoverageOp ti onAssignment = - Expression; = I nstanceNamc . I LcmName . option . OptionName Expression; { Options for covergroup types ) CovergroupName : : type_opti on . TypeOpLionName Expression; CovergroupName : : I LcmNarne : : type_option. TypeOpti onName = Expression; CoverageEvent { one of} = ClockingEvcn L @@ (Bl ockEven tExpression) coverageSpecOrOp tions = { one of) CoverageSpec CoverageOption Clocki ngEven t = {one of} @Name @ (EventExpression) Bl ockEven L Expression = { one of) Bl ockEven tExpression or Bl ockEventExpressi on beg in Name [of Block, Task or Function 1 end Name {of Block, Task or Function 1 CoverageSpec [one of} CoverPoint Cross = {one of) option . OptionName Expression; Lype op tion . TypeOptionNamc Expression; CoverageOpt i on = - - Even cExpression = { See Timing Control l Port 92 - { See Port) Copyrigh1 C 1995-2006 by OouiOs Ud
  • 92. Covergroup Covera ge O tions p { Instance Specific Coverage Options 1 weight - Number goal Number name - String (de.fa u l L 1 ) (90) ( Unique name) comment String ( " ") at least Number (1 ) detec t_overlap Boolean auto bin max Number (64) Number (0) cross num_p ri n t_m i s s i ng _ (0) (0) per_i nstance Boolean { Coverage Group Type Options ) weight Con s t a n tNumber (1) goal Constan tNumber ( l 00) comment S tringLiteral - ConsLan tNumber s lrobe ( " ") (0) Coverage Methods void sample ( ) real get_coverage ( l re f in t , ref i nt i ) real get_ i n s t_coverage ( [ ref i n t , ref i n t ] ) v o i d set_inst_name (string) v o i d sta r t ( ) void s lop ( ) $unil c l a s s - <HERE> -endc l a s s inter face-<HERE>-endinterface generate-<IIERE>-endgenerate pa c kage- <HERE>-endpackage modu le-<IIERE>-endmodule p r og ram-<H ERE >- e ndprogram The covergroup can be defined once and multiple instances of that type can be created in different contexts, using the new() operator. If the clocking event is not specified in a covergroup, users must procedurally trigger the coverage sampling, via the built-in sample ( ) Copynght C !995-2006 b, Doolos Ltd. 93
  • 93. Covergroup method. Alternatively, the strobe option can be used to modify the sampling behaviour. If the strobe option is not set (default), a coverage point is sampled the instant the clocking event takes place, as if the process triggering the event were to call the built-in sample ( ) method. covergroup can be used to cover a subset of members of a class, by embedding the covergroup in the class definition. It can define a coverage model for protected and local class properties without any changes to the class data encapsulation. If a covergroup is defined within a class, the variable of that covergroup can be declared in the class either explicitly, or implicitly. In the latter case, the variable will have the same name as the covergroup. A class may contain only one variable for each embedded covergroup. An embedded covergroup must be explicitly instantiated in the new method, otherwise it is not created and data is not sampled. Declaring an argument of a covergroup as ref allows a different var iable to be sampled by each instance of a covergroup. Input arguments will not track value of their arguments; they will use the value passed to the new operator, e.g. covergroup CG ( ref lnl X, int Y, int Z) @ (posedge e l k ) ; coverpoint X 1 1 Generic covergroup with signal to be sampled 11 specified as argument of type ref en dgroup int a, CG cgl b; new ( a , 0, 7 ) ; I I Cover variable a, Y= O, Z = 7 CG cg2 - new ( b , 8 , 1 5 ) ; II Cover variable b, Y= 8, Z = 1 5 Covera ge O tions p • weight is the weight of a covergroup instance/ coverpoint (or cross) for computing the overall instance coverage of the simulation/ of the enclosing covergroup, respectively. • goal specifies the target goal for a covergroup instance, or a coverpoint or a cross of an instance. name (the default is a unique name for each instance automatically generated by the tool) specifies a name for the covergroup instance. • 94 comment is a comment that appears with the instance of a covergroup, or a coverpoint or cross of the covergroup instance. The comment is saved in the coverage database and included in the coverage report. Copynght C> 1995-2006 by Oo<Jios ltd
  • 94. Covergroup al_least is the minimum number of hits for each bin. A bin with a hit count that is less than Number is not considered covered. detect_overlap generates a warning if it is set to 1 and there is an overlap between the range list (or transition list) of two bins of a coverpoint. auto_bin_max is the maximum number of automatically created bins when no bins are explicitly defined for a coverpoint. cross_num_print_missing is the number of missing (not covered) cross product bins that must be saved to the coverage database and printed in the coverage report. per_instance If set to 1 , coverage information for every instance is recorded separately, as well as coverage for the whole covergroup. The per_instance option can only be set in the covergroup definition. All the other instance specific options can be set procedurally after a covergroup has been instantiated. All options set at the covergroup syntactic level, except for the weight, goal, comment, and per _instance options, act as a default value for the corresponding option of all coverpoints and crosses in the covergroup. Individual coverpoints or crosses can overwrite these default values. Coverage Type O tions p • weight specifies the weight of the covergroup for computing the overall cumulative (or type) coverage of the saved database, if set at the covergroup syntactic level. If set at the coverpolnt (or cross) syntactic level, it specifies the weight of a coverpolnt (or cross) for computing the cumulative (or type) coverage of the enclosing covergroup. goal specifies the target goal for a covergroup type, or a coverpoint or cross of a covergroup type. When the goal is reached, the covergroup, coverpoint or cross is considered to have been covered. • comment is a comment that appears with the covergroup type, or a coverpolnt or cross of the covergroup type. The comment is saved in the coverage database and included in the coverage report. strobe If set to 1 , all samples happen at the end of the time slot, like the $strobe system task. The type options can only be initialized as constant expressions, therefore different instances of a covergroup cannot assign different values to them. Covergrou Methods p All methods can be invoked procedurally at any time. sample () triggers sampling of the covergroup. Cop)'lighl C 1995·2006 by Doulos Lid 95
  • 95. Covergroup get_coverage() calculates type coverage number (0 ... 1 00). get_inst_ coverage( calculates the coverage number (0 ... 100). ) set_inst_name(string) sets the instance name to the given string. start() starts collecting coverage information. stop() stops collecting coverage information. If get_coverage or get_inst_coverage is called with the two optional ref arguments, these are assigned to value and number of the covered bins respectively - in other words the numerator and denominator of the coverage value that the these functions return as a real number. Exam les p Covergroup containing options covergroup CG (inl w , string Commen t ) @ (posedge e l k ) ; option . commcnl � I I Comment for each instance of CG Co�nen t ; I I Sample at the end of the time slot type_opti on . s trobe - 1 ; CPl : cover poi n t A ( I I Create 8 automatic bins for opti on . auto_bi n_max - 8 ; I I coverpoint CP1 for each instance endgroup Setting options and type options procedurally after instantiating a covergroup coverg roup CG @ (posedge e l k ) ; CPl : coverpoint A ; CP2 : cove rpoint A ; endg ro up CG Cl - new; C l . opt i on . comment • "A commen l scl for Lhc ins lance C l " ; C l . CPl . option . auto_bi n_max - 8 ; II Create 8 automatic bins for I I coverpoint CP1 of instance C1 CG: : type_op t io n . c omment " A comment set for C l " ; 10; CG : : CPl : : type_option . weight = = 96 Cop�ighl C 1995-2006 by DouiOS LIC
  • 96. Covergroup Covergroups in classes class C l a ss l ; b i t AnEv; endclass class Class2; I I Object of Class1 Classl C l ; int Var; b i l X; local logic Y , Z ; cove rgroup C G l @ (C l . AnEv) ; cover p o i n t Var; endgroup I I Sampled on data member of C 1 covergroup CG2 ( i nt /rg) @ X ; I I Second covergroup in the same I I class, now having arguments option . at least = Arg; I I Sets a coverage option of CG2 covcrpoinL Y ; endgroup function new ( inL p ) ; CG?. new (p) ; • Cl = new; I I C 1 must be instantiated before CG1. because CG1 I I uses it CGI - new; endfunclion endclass i n i t i a l begin C2 Obj end � ncw ( 7 ) ; See Also Class, Coverpoint, Cross, New Cop)"oghtC 1995-2006 by Douloo Lid 97
  • 97. Coverpoint Coverpoints are integral variables or expressions for which coverage information is collected. They are defined in a covergroup. A coverpoint includes a set of bins associated with its sampled values or its value-transitions . ..,. This feature was added in SystemVeri/og (one of) [CoverPo i n tNarne : ] coverpoint Expression [ i f f (Expression) l [CoverPointName : ] covcrpoint Expression [ i f f (Expression) ] ( [ Bi nsOrOptions; . . . i} . . . ; 1 BinsOrOptions = (one of) CoverageOption [wildcard] TJinsKeyword B inName [ [ [ Expression ] ] ] RangeList [ i f f ( Expressi on) ] [ w i ldcard] BinsKeyword Bi nNamc [ [ ] J = Trans i t i on L i s t [ i f ( ( Expressi on) ] [ [ [ ':xprc.!ision i ] I = l default [ i f f (Expression} ] BinsKeyword BinName = default sequence [ i f f (Expres s i on ) ] BinsKcy1vord BinName (one of} bins i llegal_b ins ignore_b ins BinsKey1o�ord = RangeLi s t ( Va l ueOrRanges, = . . . } 'l'ransi tionList - ( 'l'ransi L i onScLs) , . . . Transi tionSet = TransRangeL i s t => 7'ransRangeLi s t [ => TransRangeLisL - ( one of) Va 1 ueOrHangcs , Repea t Range] Val ueOrRangcs, . Va l ueOrRanges, . . . [-> RepeatRange] Val ueOrRangcs , . . . [= . - [' Repea tRange] Va lueOrRange = ( one of) Ex pression [ Expression: Expression] RepeatRange - (one of) Expression Expression : Expression CoverageOption = see Covergroup cove rg roup-<IIERE>-endg roup 98 Ccpynght0 199S-2006 by Ooolos ltd
  • 98. Coverpoint • A coverpolnt creates a hierarchical scope. If it is labeled, this label becomes the name of the coverage point, and can be used to add this coverpolnt to a cross coverage specification, or to access the methods of the coverage point. If the label is omitted and the coverpoint is associated with a single variable then, the variable name becomes the name of the coverpoint. • The expression within the iff construct is optional and specifies a condition that disables coverage for that coverpoint, i.e. if the expression evaluates to false at a sampling point, the coverpoint is ignored. • The bins for a coverpoint can be automatically created by SystemVerilog or explicitly defined using the bins construct. The bins construct creates bins as follows: bins bin name 1 1 - creates a separate bin for each value bins binname [ n 1 - creates n bins, with values distributed uniformly between the bins, any "left-overs" going in the last bin. Duplicate values are retained. If the bins are not explicitly defined, they are automatically created by Sys­ temVerilog. Automatically created bins only consider 2-state values; sampled values containing X or Z are excluded: For an enum coverpoint, the number of automatic bins is the cardinality of the enumeration For any other integral coverage point, the number of automatic bins is the minimum between 2M and the value of the auto_bin_max option, where M is the number of bits used to represent the coverpoint Each automatically created bin will have a name auto[Va/ue], where Value can be: a single coverage point value • the range of coverage point values: low : high the named constant associated with a particular enumerated value The RangeList used to specify the set of values associated with a bin may be constant expressions, instance constants (for classes only) or non-ref arguments to the coverage group. • A TransitionList specifies one or more sets of ordered value transitions of the coverage point. The list can be of any arbitrary length. • Transitions that specify sequences of unbounded or undetermined varying length cannot be used with the multiple bins construct (i.e. using [ 1 ) ; e.g. the length of a transition using non-consecutive repetition is unbounded and Cop)right C !995-2006 by Doulos Ltd 99
  • 99. Coverpoint can vary during simulation. An attempt to specify multiple bins with such sequences will produce in an error. A set of values or transitions associated with a coverage point can be explicitly excluded from coverage by specifying them as lgnore_bins. A set of values or transitions associated with a coverage point can be marked as illegal using illegal_bins. If so, they are excluded from coverage. illegal_blns values or transitions occurrence will produce a run-time error, even if they are also included in another bin. The default bin catches the values of the coverage point that do not lie within any of the defined bins. The default sequence specification does not accept multiple transition bins (the [ ] notation is not allowed). • It is an error for bins designated as lgnore_bins to also specify a default or default sequence. • By default, a value or transition bin definition specifies 4-state values. A wildcard bin definition only considers 2-state values; sampled values containing X or Z are excluded. The wildcard bins definition causes all X, Z. or ? to be treated as wildcards for 0 or 1 (similar to casex and the ==? operator). Gotchasl • The coverage calculation for a coverage point does not take into account the coverage captured by the default bin. Ignored values or transitions are excluded even if they are also included in another bin. Use the default construct to catch unplanned or invalid values. Use the default sequence form to catch all transitions (or sequences) that do not lie within any of the defined transition bins. Exam les p Simple example bit [ 3 : 0 ] X , Y ; covergroup C G @ (posedge Clk) ; Pl: coverpoint X; 100 Copyrli)ht 0 1995-2006 by Doulos Ltd
  • 100. Coverpoint ? 2 : coverpo i n l Y ; en dg ro up Example showing bins and transitions bit [ 5 : 0 ] V; @ (posedge e l k ) ; covergroup CG coverpoint v bins a = ( [0:3J , 5); bins b [3] = I I One bin for these values I I of V - 0, 1 , 2, 3, or 5 I I 3 bins: <6,7>,<8,9>,<1 0,11 > { [6: 1 1 ] } ; I I 2 bins: <13,14>,<15,16,17> b ins c [ 2 ] = ( [ 1 3 : 1 7 ] ) ; d[] = bins c [ ] = bins bi n s f = [ 18, I I 2 bins: d[18]. d[19) 19); ( [ 20 : 3 0 ] , ( 4 1 => 4 3 ) , [ 25 : 40 ] ) ; II Overlapping values - OK ( { [ 5 0 : 52 ] , 5 5 } => { 5 6 , 5 7 } ) ; I I Associates the following sequences with bin f: 41 =>43, or 50=> 56, II 51=>56, 52=>56, 55=>56, 50=>57, 51 =>57, 52=>57, 55=>57 = ( [ 60 : $ ] ] ; II bin h: values from 60 to 63 ($ is maxofV) bins h ignore_bins ig_vals = { 1 8 , 191; I I ignores values, even though included in bin d i l legal_bins i l 1_trans = ( 47 => 4 8 => 4 9 1 ; I I This sequence will produce a run-time eror w i l dcard bins wb = [ 5 ' bl l ? ? l } ; I I 1 1 001 1 101 1 1 1 10 1 1 1 1 1 1 bins others [ ] = default ; I I Any value not maching a, b[2), c[2], dO, eO, f,gO. h, wb, etc. endgroup More examples of transitions 1 => 2 I I Single value transition: value of coverage point at 2 I I successive sample points 1 �> 3 �> 5 1 1 Sequence of transitions 1,2 = > 3, 4 II Set of transitions, equiv. to: 1 =>3, 1 =>4, 2=>3, 2=>4 2 [* 3] I I Consecutive repetition. equiv. to 2=>2=>2 2 [* 2: 41 I I Range of repetition, equiv. to . 2=>2, 2=>2=>2, 2=>2=>2=>2 2 [ �> 3 ] 2 [= 3 ] II Non-consecutive occurrence, equiv. to ...2=>...=>2...=>2 I I where ... is any transition that does not contain the value 2 I I Non-consecutive repetition, equiv. to 2=> ... =>2 ... =>2 . . . =>2 II excluding the last transition See Also Covergroup, Cross CopynghlCl 1995-2006 by Doolo< Lid. 101
  • 101. Cross The cross construct specifies cross coverage between two or more coverage points or variables. It is used in a covergroup. ..,. This feature was added in SystemVerilog [CoverPointName : ] cross CrossTtem, CrossiLcms, . . . [iff ( Express ion) ] .SelecLBi nsOrEmpLy Cross item - CoverPointName VariablcNamc SclcctBinsOr/:mpty : {BinsSelectionsOrOptions; . . . } BinsSelecti onsOrOption CoverageOption BinsKey1vord BinName = SelcctExpression [iff (Expression ) ] Selec tExpression SelccLCondi tion ! SelectCondi tion SelectExpression & & SelectExpression SeleccExpression I I Selec tExpressi on (SelectExprcssion) Selec tCondi tion - binsof (Bi nsExpression) ( intersect. { ValueOrHanges, . . . ) ] BinsExpression VariableName CoverPo.i. n L Namc [ . B .i.n sName J Va l ueOrRange = ( one of) Expression [ E"xpression : Expression] [ $ : Expression] ( Values <= Expression ) 1 Values >= Expression 1 {one of) bins i l legal bins ignore b i ns [ Expression : $ ] BinsKey�Yord = cove rgroup-<HERE>-endgroup 102 Cop)Tight 0 199!>-2006 by Ooulos Lid
  • 102. Cross The cross coverage of a set of coverpoinls is the coverage of all combinations of all bins associated with the coverage points, i.e., the Cartesian product of the sets of coverpoint bins. • Cross coverage is allowed only between coverage points defined within the same covergroup. A cross involves only coverage points. A coverpoint having the same name as the variable is created implicitly if a variable is used in a cross. • Expressions cannot be used directly in a cross. A coverpoint must be explicitly defined first. • All cross products that satisfy the SelectExpression used with ignore_bins are excluded from coverage, even if they are included in other cross­ coverage bins of the enclosing cross. All illegal cross products that satisfy the SeleciExpression used with illegal_bins are excluded from coverage, and a run-time error is issued. Illegal cross products take precedence over any other cross products. The optional label also creates a hierarchical scope for the bins defined within the cross. • If the expression within the optional iff evaluates to false at any sample point, the cross coverage is ignored. • Cross coverage bins can be specified in order to group together a set of cross products. A cross coverage bin associates a name and a count with a set of cross products. The count of the bin is incremented every time any of the cross products match, i.e., every coverage point in the cross matches its corresponding bin in the cross product. The blnsof construct yields the bins or its expression, which can be either a coverpolnt or a coverpoint bin. Exam les p [ 3 : 0 ] A, B; covergroup CGl @ (posedge e l k ) ; biL llxf3 : cross A, B ; I I Coverpoints are implicitly created for a and b I I Each coverpoint has 1 6 bins, auto[O) to auto[15] I I llxl3 has 16.16 cross products, and each cross product is a bin of llx£l BC coverpoint B + C; I I Expression defined as coverpoint AxB : cross A, BC; I I Cross of an implicit coverpoint and an expression endgroup eop,..lght C> 199!..2006 b Doolos Ltd y 103
  • 103. Cross covergroup CG2 @ (posedge e l k ) ; CP_A: coverpoint A I bins CP Al - 1 [ 0 : 4 ] ) ; bins CP A2 I [5:8] ) ; CP B : covcrpoint B bins CP Bl bins CP__,B2 Cr I [ 1 : 51 l ; I [7 : 12] } ; cross A, B 1gnorc_bins EB = binsof (CP_A) intersect 1 5 , [ 1 : 3 ] } ; i l l egal_bins I B binso f ( a ) intersect [ 1 2 } ; bins Cr1 ! b i n s o f (CP_A) inlersect 1 [ 6 : 9] } ; • b i n s Cr2 I I 2 cross products: <CP_A1 , CP_81>, <CP_A1 ,CP_82> b insof (CP_A . CP A2) & & b i n sof (CP_B . CP_B l ) ; I I 1 cross product: <CP_A 1 , CP_81 > endgroup See Also Covergroup, Coverpoint 104 Copyughl C 1995-2006 by DO<Jioa Ltd.
  • 104. Data Type SystemVerilog includes a number of data types. They may be grouped into two main categories: net types and variable types. The data type defines the values that an object may take and (sometimes) how it may be used. In SystemVerilog, nets have a (variable) data type as well as a net type. � SystemVerilog introduces a number of new data types and the ability to use data types with nets Variable Types bit, logic, reg, • byte, shortinl, int, longint, integer, time shortreal, real, realtime • Typedef • Struct, Union Enum • String Event Chandle Class Covergroup Virtual interface yp Net T es supplyO, supply1 tri, triand, trior trireg triO, tri1 wire, wand, wor uwire See Also Declaration, Net, Variable Copy<�ghl C> 1995·2006 by Doolo$ Ud. 105
  • 105. Declaration A data declaration defines a name to have a specified type. In many cases, a data declaration also creates a variable or net with the name. Where this is not the case, an object is created using the new operator or method. Other declarations define names for tasks, functions, modules etc. For details of the different declarations, see the relevant article. � SystemVerilog adds a number of new types of declaration Declara Lion = (one of} Net Variable ConsL Typedef Imporc Genvar Vi rtua l Tn tcriacc Import "DPI-C " Export "DPI-C" Parameter Localparam Specparam Event Rand Constraint Task f'unction Class Cl ocking Covcrgroup Bind (Operator Overload) Property Sequence $unit modu J e-<HERE>-endmodule interface-<HERE>-cndin Lcrfacc package-<HERE>-endpackage program-<HERE>-cndprogram gcncrate-<HERE>-endgenerate class-<HERE>-cndcl a s s 106 Copynght 0 1995-2006 by Ooutos Ltd
  • 106. Declaration begin-<IIERE>-cnd for k-<HERE>-j o i n f un c l lon -<HERE> -endfucntion tas k-<HERE>-endtask for ( <HERE> ) Copynght 0 1995-2006 by Douk>s ltd. 107
  • 107. Defparam Overrides parameter values at compile time. Using hierarchical names, idden from anywhere inside or outside a design's parameter values can be overr hierarchy. The defpa ra m statement may be removed from future versions of the language. defparam ParameterName - Const.antMinTypeMaxExpression, ParamelerNamc - ConstantMinTypeMaxExpression, Con s L a n tMinTypeMaxJ::xpression - { one of} ConsLantExpression Cons tantExpress ion : Cons t an t Expression : Constan tExpressi on module-<HERE>-endmodule generaLc-<HERE>-endgenerate It used to p rovide a useful way of back-annotating layout delays, but this is now normally done using specify blocks and the Programming Language Interface. To override the values of parameters, use the # syntax in a module instantiation. Exam les p ' t imescale lns I lps module LayoutDel a y s ; defparam Deslgn . Ul . T_ f dcfparam Design . U2 . T f � 2 . 7; 3. 1; endmodule module Design ( . . . ) ; and_gale U l ( f , a , b ) ; and gate U2 ( f , a , b ) ; en dmodule module and_gate ( f , a, b ) ; output f ; 108 Cop)Tight C 1995.-2006 b y Ooutos Ltd
  • 108. Defparam inpu l a , b; parameter T f and I (T_f) • 2; (f , a , b ) ; endmodu le Sea Also Instantiation, Name, Parameter Copyright C 1995--2006 by Ooulos Ltd. 109
  • 109. Delay Delays may be specified for instances of UDPs and gates, for continuous assignments, and for nets. These delays model the propagation delay of components and connections in a nellis!. .,._ SystemVerilog adds the ability to include a unit (e.g. #1ns)and the step unit ( one of) N DelayVal ue # (Min 1'ypMaxExpression [ , Mi n'I'ypMaxE:xpression [ , Min TypMaxl- xpl"ession) ) ) : Del ayVa l ue = { Rise, Fall, Turn-Off) (one of} Uns i gncdNumbcr [ Uni t l RealNumber [ Uni t ] Name Uni t � { one of} s ms us us ps fs step Unsi gnedNumber, Rea I Number Min TypMaxExpression = - See Number See Expression See Assign, Instantiation, Net, Statement • The time unit step is equivalent to the global simulation precision. • Where only one delay value is given, it represents both the rising and falling propagation delays (i.e. transition to 1 or 0 respectively), and the turn off delay (if applicable). Where two delay values are given, the first is the rise delay and the second is the fall delay, except for tranifO, tranif1, rtranifO and rtranif1, where the first value is the turn on delay, and the second is the turn off delay. Where three delay values are given, the third delay is the turn off delay (transition to Z), except for trireg nets, where the third delay is the charge decay lime. Delay to X is the smallest of the specified delays. • 110 For vectors, a transition from non-zero to zero is considered to be a "fall", a transition to Z is considered to be a "turn-off", and any other transitions are considered to be a "rise". Copyright c 1995-2006 by Douloo lld
  • 110. Delay Gotchasl There is no space between time and the time unit when the delay has a time unit specified (e.g. #10ns). specify block delays (path delays) are usually a more accurate way of modelling delays, and provide a mechanism for delay calculation and back-annotation of layout information. Exam les p and # ( 5 ) al (oul, bufifO # ( 1 , 2 , 3 ) inl , b1 I I Only one delay in2 ) ; (out , in, ctr 1 ) ; II Rise, fall and turn-off I I delays not #Sns n l (ndata, bufifl # ( 1 : 2 : 3 , data ) ; 4 : 6 : 8, 5 : 1 0 : 12 ) b2 (io2, i o 1 , di r ) ; See Also Assign, Instantiation, Net, Specify, Timeunit, Timing Control Copynghl 0 1995-2006 by Doulos Ltd 111
  • 111. Disable Causes the execution of an active task or named block to terminate before all its statements have been executed. The keyword disable is also used in property specifications (disable iff), where the meaning is unrelated to that described here. II> disable fork was added in SystemVerilog disable TaskOrBlockName ; disable fork; See Statement. • Disabling a named block (begin-end or fork-join) or a task disables all tasks enabled from that block or task, and downwards through the hierarchy of enabled tasks. Execution continues with the statement following the disabled task enable statement or named block. • A named block or task may be self-disabled by a disable statement inside that named block or task. The following are not specified when a task is disabled: the values of any outputs or inouts; events scheduled by nonblocking assignments that have not yet taken effect; assign and force statements. • Any statement may be preceded by a block name, so any statement can be disabled. In particular, named assertions can be disabled. Functions (except DPI functions) cannot b e disabled. disable fork terminates all descendants of the process (initial, always, fork-join) from which it is called including their descendants, if any. It is used in conjunction with fork-join_any and fork-join_none. , disable may be used to disable DPI tasks and functions. When disabling a DPI import task or function, the C code has to follow a disable protocol that allows the C code to perform resource cleanup (e.g. closing open file handles, closing open VPI handles, etc.): • • 112 When an exported task returns due to a disable, it must return a value of 1 . Otherwise it must return 0. The simulator handles this. When an imported task returns due to a disable, it must return a value of 1 . Otherwise it must return 0. Cop)Tighl 0 1995-2006 by Ooulos Ltd
  • 112. Disable • Before an imported function returns due to a disable, it must call the API function svAckDisabledState ( ) . Once an imported task or function enters the disabled state, it is illegal for the current function invocation to make any further calls to exported tasks or functions. If an exported task is the target of a disable, its parent imported task is not considered to be in the disabled state when the exported task returns. When a DPI imported task or function returns due to a disable, the values of its output and inout parameters, as well as function return values are undefined. Gotchasl • If a task disables itself, this is not the same as returning from the task, as the outputs will not be defined. If disable is applied to an immediate assertion at the same simulation time step as the last clock step of a sequence, there will be a race, but a concurrent assertion is always disabled. Where possible, use break, continue and return in preference to disable. Exam les p Using disable to break a loop externally: i n it i a l begin : Clockgen Clock � 0 ; fo reve r # ( Period/2) Clock end : Clockgen -Clock; ini t i a l begin : S timulus disable Clockgcn; end : Stimulus I I Stops the clock Using disable fork to terminate spawned processes. initial fork I I Spawns two processes by calling two tasks in parallel Copyrighl 0 1995-2006 by Doulos Lld 113
  • 113. Disable a_Lask; anolher_task; joln_any I I Blocks until first process completes disable fork; I I Terminates the other process See Also Assert, Fork, Jump Statements, Statement, Wait 1 14 Copynght C 1995-2006 by Ooulos ltd
  • 114. Do-While Loop with a test at the end . .,... This feature was added in SystemVerilog do Statement while (Expression) See Statement. The Expression can be any expression that can be treated as a boolean. It is evaluated after the Statement. Do-while loop saves duplication of the loop body. Exam ple int N = 1 0 ; do beg i n N++; end while (N < 1 0 0 ) See Also For, Forever, Repeat, While Cop)'llghl Q 1995-2006 by Doulos Lid 115
  • 115. Dynamic Array A dynamic array is any dimension of an unpacked array whose size can be set or changed during simulation . .,.. This feature was added in SyslemVerilog l Declaration 1 DataType Name [ ] ; l Create or resize 1 DynamicArrayNamc = new[Size] [ ( Arra yName) ] ; Size • l non-negative integral expression } { Methods} function i n l size ( ) ; function void delete ( I ; { Declaration } module-<HERE>-endmodule i nterface-<HERE>-endinterface program-<HERE>-endprogram generaLc-<HERE>-endgenerate • The new[ ) operator is used to set or change the size or the array. The optional ArrayName argument is the name of an array, which is used to initialize the dynamic array. It must have the same type as the dynamic array, but it need not be the same size. • Dynamic arrays may have unsized dimensions. Methods size() - returns the length of the dynamic array. • 116 delete() - deletes a dynamic array, resulting in an array of zero size. Copj<ighl C 1995-2006 by Ooulos l1d
  • 116. Dynamic Array Examples l ogic [7 :0] array array array [); new [ lO O ] ; = new [ 2 0 0 ] (array ) ; I 1 Declare a dynamic array 1 1 Create an array of1 00 elements I I Double the size, preserving the I I existing elements S di sp lay ( " array has %d elcmcn L s " , a r r a y . delete ( ) ; arra y . s i z e ( ) ) ; I I Array now has no elements See Also Array, Associative Array, New Cop�Tighte 1995-2006 by Doulos Ltd. 117
  • 117. En urn An enumerated date type consists of a set of named constants of an integer type. � This feature was added in SystemVerilog enum [ EnumBaseType J { EnumNameDecl a ra tions , . . . } EnumBaseType - [one of} IncegerlLomType [ Signing) In LegerVec cor7'ype [ S i gn i ng] TypeName [ PackedDimensionJ [ Pa ckedDi mensi on I EnumNameDeclaration - EnumName [ [ In t egra lNumber [ : In tegralNumber] ] ] [- Cons cancExpression] { one of) byte shorcint i n t l ongint inLeger Llme IncegerVccLorType = {one of} bit logic reg IncegerAtomType Signing � � {one of} signed unsigned Pa ckedDimension = [ConstantExpression: ConstantExpression] = (one of) (See Number) BinaryNumber OctalNumber DecimalNumber llexNumber IncegralNumber [ Methods} function enum f i r s t ( ) ; f u n c l i o n enum l a s l ( ) ; function en urn next ( i nt uns igned N function enum prev l int unsigned N function int num ( ) ; funcLion string name ( ) ; 1) ; 1) ; module-<HERE>-endmodule begin : Lclbel-<HERE>-end fork : Label -<HERE>-j oin ta s k-<HERE>-endlask interface-<HERE>-endinterface program-<HERF.>-endprogram functi on -<HERE>-endfunction 118 Copynghl 0 1995·2006 by Ooulos Lid
  • 118. Enum Enum values are strongly typed - you must assign enum variables using values in the enumeration set. You can assign arbitrary expressions to an enumerated variable with an explicit cast, or if the enum variable is member of a union. Enumerated variables in expressions are automatically cast to the specified integer type, or to int if none is specified. The default data type used with enum types is int. enum {Cold, Ho t ) II int type by default Tap; An enum declaration that includes one or more names with X or Z assignments must have an explicit 4-state data type declaration. enum integer [ I d l e , XX= ' X , S l =2 ' b l l ) State, NextState; II Idle = 2'b00, XX = 2'bXX • If an enum value includes X or Z, the next value must be specified explicitly. • The values can be cast to integer types, and assigned an increment of the value of the previous name. First name gets the initial value of 0 if not set otherwise. enum { A , 8=5 , C, D ) ABCD; II A=O, C=6, D = 7 • The values assigned in an enum must be unique. Enum names may not be overloaded - two en urns in the same scope must have non-overlapping sets of names. • The size of a type may be set by using a sized constant. All sizes must be the same. enum { S l =3 ' h 5 , S2 , S 3 } S t a t e ; • II S2=3'h6, S3=3'h7 (all 3-bitwide) The size of a type may also be set by adding a constant range to the en urn declaration. It is a syntax error if any of the en urn members are defined with a different sized constant. enum [ 2 : 0 ] { red, enum [ 2 : 0 ) [ red = ' hl , ye l l ow=3 ' h 7 , blue ) Flag; ye l l ow= 3 ' h7 , blue ) Flag; II OK; I I red is unsized The optional value of an enum named constant can include references to parameters, local parameters, genvars. other enum named constants, and constant functions of these. Hierarchical names and cons! variables are not allowed. Gotchasl The default value of an enum variable is the default initial value of its base type, not the first value of the enum. Cop�ht C> 1995-2006 by Doolos Lid. 119
  • 119. Enum Methods first() - returns the value of the first member of the enum. • last () - returns the value of the last member of the enum. next (N) - returns the value of the Nth next (default - the next) member of the enum. • prev(N) - returns the value of the Nth previous (default - the previous) member of the enum. num() - returns the number of elements in the enum. name() - returns the string representation of the enum value. If you want to use an enum type in more than one place, use a typedef. typedef enum { A , A, C ) ABC; ABC Var ; I I Named type Exam les p This example shows how some of the enumerated type methods are used. enum States { Reset, Go! , Go2 ) State ; Sdisplay ( "The enum SLates has %0d values : " , State . num) ; State = State . fi r s t ( ) ; do begin $display ( " % s ( %0d) " , State . name , StaLe ) ; State = SLate . ne x t ; end while (State ! = State . f i rs t ) I I next() wraps atthe end See Also Canst, Typedef, Var iable 120 Copynghl 0 1995·2000 by Doulos Lid
  • 120. Event Events can be used to describe communication and synchronization in behavioural models. Event variables don't have values, but they can be triggered and walled for using an @ or wait timing control. ,... SystemVerilog enhances events 1 Declaration J event Name [ = EventOrNul l ] , Name [ = Even LOrNul l ] , . . . ; Even tOL·Nul l = {one of} EventName null { Arrays of events may be declared - see Arrays J -> EventName; l Trigger the event J ->> [ Timi ngCon trol] EventName l Nonblocking event trigger} ( Property} . Lriggcrcd ( 1 if event triggered in current timestep J See Statement for -> and ->>. Event declarations are allowed in the following places: modulc-<HERE>-endmodule gcnc ra Lc-<liERE>-endgenerate begin : Label-<!IERE>-end fork : Label-<HERE>- j o i n task-<IIERE>-cndlask interface-<HERE>-endi n terfacc program-<HERE>-endprogram function-<HERE>-endfunction An event can be triggered with -> or-» and waited for with @, wait or wait_order. When an event is triggered, the triggered state lasts throughout the time step and can be tested using the .triggered property. null.triggered is false. Coc>Y';ghl 0 1995-2006 by Doolos ltd 121
  • 121. Event • Triggering a null event has no effect; the effect of using a null event in a timing control is undefined. • Event variables can be assigned to other event variables or to null. When one event variable is assigned to another, the two event variables are in effect merged - they refer to the same synchronisation event. Events can be compared using ==, !=, === and !== Events can be passed as arguments to tasks. Gotchasl The triggered state of Verilog named events has no duration, whereas in SystemVerilog this state persists throughout the time-step in which the event triggered. • Named events are useful in testbenches and system level models for communicating between concurrent processes in the same module, or in different modules (using hierarchical names). By using the .triggered event property in conjunction with the wait construct it is possible to unblock the waiting process whether the wait executes before or at the same simulation time as the trigger operation. This helps to eliminate a common race condition that occurs when both the trigger and the wait happen at the same time. Exam les p event SLar LClock, StopClock; alway!; fork begin : ClockGenerator 0; Cl ock @SLartClock forever # H a lfPeriod C l ock - ! Clock ; end @ StopClock disable C lockGenerator ; = join i n i t ial begin : stimulus -> 122 StartClock ; Copynghl c 199S.2006 b y Doutos Lid
  • 122. Event -> StopClock; -> StartCJock; -> StopC l oc k ; end See Also Timing Control, Wait Cop)";ghl Q 1995-2006 by Dooloo Lid 123
  • 123. Expect The expect statement is a procedural blocking statement that allows waiting on a property evaluation . ..,.. This feature was added in SystemVerilog expecL ( Property8pec) AccionBlock = see Property = ( one of) ProperLySpec ActionB1ock S t a t cmcn LOrNul l ( S ta temen t ) else Sta t emcnLOrNu 1 1 Any procedural code (e.g. tasks, class methods, etc. ) When executed, the expect statement starts evaluating the property on the next clocking event. • An expect statement causes the executing process to block until the given property succeeds or fails. If the property fails at its clocking event, the optional else clause of the action block is executed. If the property succeeds the optional pass statement of the action block is executed. Gotchasl The syntax is expect (property_spec), not expect property (property_spec), as might be expect by analogy with the concurrent assertion statements: assert property, assume property and cover property. 124 Copyrlghl C 1995·2006 by OotJios Lid.
  • 124. Expect Exam les p In this example, the expect succeeds if the sequence a ##1 b matches starting on posedge elk immediately after time 1 OOns program Tesl; l n i l i a l begin # l OOns expec t ( @ (posedge e l k ) a # # 1 b ) else $error { "expect failed" ) ; end endprogram Test Sea Also Assert, Assume, Cover, Property, Sequence Copynght C 1995-2006 by Doulos Ltd 125
  • 125. Export "DPI·C" SystemVerilog functions and tasks can be exported to the foreign language layer of the DPI using export "DPI-C". This enables them to be called from a C (or other foreign language) program, for example. .,.. This feature was added in SystemVerilog export " D P T - C " [ Forei gnNamc � J function SVFunclionName ; export "DPI-C" [ ForeignName � J function SVTaskNarnc; See Function • The ForeignName is the name that is used to call the exported task or function in C. If not specified, i t will be the same as SVFuncName or SVTaskName. • Several SystemVerilog tasks and functions can be mapped to the same foreign function by supplying the same ForeignName for several SVFuncNames, with the condition that they are i n different scopes and have identical signature (i.e. same return type, same number, order and type for each argument). DPI exported functions/tasks can be declared in any place where normal SystemVerilog functions can be declared (e.g. module, program, interface, generate constructs). • DPI exported functions/tasks must be declared in the same scope that contains the export "DPI-C" declaration. • The export "DPI-C" declaration and the definition of a SystemVerilog function/task can occur in any order. Only one export "DPI-C" declaration is permitted per SystemVerilog function/task. • Class member functions cannot be exported, but all other SystemVerilog functions can be exported. All exported functions are always context functions (see Import "DPI-C"). The formal argument types of exported tasks or functions are restricted to a subset of SystemVerilog types (see Import "DPI-C"). Result types of DPI exported functions are restricted to small values (see Import "DPI-C"). Export tasks may be disabled using the disable statement (see Import "DPI-C"). 126 COpyright C 1995·2006 by Ooutos Ltd.
  • 126. Export "DPI-C" It is illegal to call an exported task from within an imported function. It is legal for an imported task to call an exported task only if the imported task is declared with the context property. • One difference between exported tasks and exported functions is that SystemVerilog tasks do not have return value types. The return value of the C function corresponding to an exported task is an int value which indicates if a disable is active or not on the current execution thread. (see Import "DPI-C"). Gotchasl • The export "DPI-C" statement does not include the function or task prototype or the function return value - just the function or task's name. SystemVerilog 3.1 a used the syntax, import "DPI" and different argument passing semantics. These semantics are deprecated in IEEE SystemVerilog. While import "DPI" is still part of the IEEE SystemVerilog language, the LRM states that compilers shall generate a compile-time error. Exam les p Exported DPI Functions: module Bus ( input I n l , output Out! ) ; export "DPI-C" [u n ction read; 1 1 This SystemVerilog function can be called from C [ unc tion void read (int data ) ; endfu nct i on endmodule C: # i n c l ude "svdpi . h " extern void read ( i nt ) ; 1 1 Imported from SystemVerilog See Also Function, Import "DPI-C", Module, Task Cop)'li<;hiCI 1995-2006by0cxoloo Lid 127
  • 127. Expression An expression calculates a value from a set of operators, names, literal values and sub-expressions. A constant expression is an expression whose value can be calculated during compilation. A scalar expression evaluates to a one-bit value. Delays may be expressed using a MinTypMax expression . ..., SystemVerilog includes new expression types and operators Expression = { one of} Primary Opera tor Primary 1 ( unary operator } • va riableLVal ue - - Variabl eLVa l uc VariableLVa l ue 1 1 VariableLValue-- ( binary operator! Expression Operator Expression CondPredicace ? Expression : Expression Express ion inside { Val ucOrRangcs . . . } tagged MemberName [ Expression) (Opera corAssignmcn L ) Primary - (one of} Number ( Of parameter, net, or variable } { Bit select} Name [ Constan tExpression: Constan tExpression] ( Part select} Name Name [ Expression] : Cons tan tExpression] { Indexed part select} Name [ Expres s i on - : Cons t a n tl-:xp ression] { lndexed part select } ArrayName ( Expression] ( [ Expression] . . . } ( Unpacked element} Name ( t:xp ress ion i ArrayName ( l,"xpress ion] ( [ Expression] . {1- :xpressi ons, . . . } (Expression] { Etc. ) { Concatenation} { Replication } . .} ( Expressi on( Expressions, . . . } } ' ( Expressions, . . . } 1 Assignment pattern J ' ( Cons t a n tExpression( Expressions, . . . } } 1 Assignment pattern} ' ( MemberLabel : Expression, ( Assignment pattern 1 ( EmptyQueue } . . .} '{} (Min1'ypMaxExpression) FunctionCa l l Cast ( SL reamOperator [Sl iceSizeJ ( Expression (wlLh ArrayRangc ] , . . . }} SequenceMethodCa l l $ 128 Copyrk;hl C 1995-2006 by Oou1oa Lid
  • 128. Expression null CondPredi caLe - see lf ValueOrRange ; {one of) Expression [Expression: Expression) Opera torAssignment ; Vari ableLva l u e Assi gnmen tOpera Lor Expression llssignmentOpe rator = tone of} ; += -; *= /; �; &� I ; �; <<- >>- <<<- >>>= MemberLabel ( one of) = dcfaull 'l'ypeName VariableName MinTypMaxExpression � ( one of) t used for delays 1 Expression Expression : Expression : Expression SLreamOpcraLor = t one of) >> << SliceSize = (one of) TypeName Constan tExpression ArrayHange = {one of) [r :xpression) [ Expression [ Expression Expression] +: [Expression -: Va riubleLValue = Expression] Expression] see Procedural Assignment ScqucnccMe LhodCa l l = see Sequence An indexed part select of a vector net, vector re g Integer variable or time variable must have constant width but may have dynamically variable position , • Bit select results, part select results and concatenate results are unsigned, regardless of the operands. When an integer constant is used as an operand in an expression, a signed integer with no base (e.g. -5) is treated differently from a signed integer with a base (e.g. -'dS). The former is treated as a sign ed number; the latter as an unsigned number. If the unpack operation (streaming operation using «) includes unbounded dynamically-sized types, the first dynamically-sized item is resized to accept all the available data (excluding subsequent fixed-sized items) in the stream; any remaining dynamically-sized items are left empty. The unpack operation allows a with expression to explicitly specify the extent of a variable-sized field within the unpack operation. ��ht C 1995-2006 by Doolos Ltd. 129
  • 129. Expression • The Expression before the with can be any one-dimensional unpacked array (including a queue). • Assignment patterns are used to assign values to arrays and structures. They are preceded by an apostrope ( ' ). The nesting of braces must match the number of dimensions. The replicated form of assignment pattern ( { { } } ) can be nested. The inner pair of braces in a replication is removed. A replication expression only operates within one dimension. ' int A [ 1 : 2 ] [ 1 : 3 J ' ( ' ( 7 , 8 , 9 ) , ' ( 3 ( 10 ) ) ) ; int 8 [ 1 : 2 ] [ 1 : 3 ] - ' { 2 ( ' { 3 { 1 } ) ) ) ; Assignment patterns may use their index or type as a key, and a default key value (see Array). int A [ 1 : 3 I ; A - ' { 1 : 1 , defau l t : O ) ; • I I Indexes 2 and 3 assigned 0 Assignment patterns may be used as the left-hand side of an assignment­ like context. Gotchasl • Many tools require the minimum, typical and maximum delay values in a constant MinTypMaxExpression to be ordered (e.g. min <= typ <= max). An indexed part select uses +: or-:. Reversing these in error to :+ or :- may give legal syntax and thus be difficult to debug. • The SystemVerilog LRM contains examples where assignment patterns are not used for queues. Implementations may or may not decide to implement assignment patterns for queues. Indexed part selects are ideal for describing barrel shifters and similar functions Exam les p A + B !A (A & & B) A [ 7 : 0] B[l] I I C - 4 ' d12 1 3 I I A large positive number " Ii e l l o " ! - "Goodbye" I I This is true (1) $ r e a l tobi ls ( r ) ; 1 1 System function call 130 Copyrw 1 0 1995-2006 by Doulos Lid. .)l
  • 130. Expression { A , B, C [ l : 6 ] ) I I Concatenation (8 bits) 1:2:3 I I MinTypMax logic [ 7 : 0 ] Byte7_to_O ; logic [ 0 : 7 ] nyte0_to_7 ; Byte7_to_ 0 [ 2 + : 3 ] I I Same as Byte?_to_0[4:2] ByteO_ to_7 [ 2 + : 3 ] I I Same as ByteO_to_7[2:4] Byte7_ to_0 [ 6 I I Same as Byte?_to_0[6:4] 3] 3] B yte 0_t o_ 7 [ 6 i nput [ 4 : 0 ] s h i f t ; input [ 3 1 : 0 ] operand; output [ 7 : 0 ] result; assign result = operand [ sh i f t I I Same as ByteO_to_7[4:6] 8J ; Multi-Dimensional Arrays wire [7: 0] A [0: 15] [0 : 15] ; assign A [ O ] [ O J - 8 ' bl ; assign A [ 1 ] [ 5] [7 : 4 ] - A [ 5] [ 1 ] [ 3 : 0 J ; assign W = A[l] [2] [3] ; I I 16x16 array of bytes I I Element select I I Part-select I I Bit-select See Also Delay, Function Call, Name, Number, Operator C<>pyright c 1995-2006 byDovtos Ltd 131
  • 131. Extends Extends a class by creating a new derived class that inherits the members of the parent class . ..,_ This feature was added in SystemVerilog See Class • All methods and properties of ParentCiassName are part of ClassName and ClassName has additional properties and methods. The parent's members can be overridden. To call a method from the parent class that has been overridden by the derived class, the super keyword must be used. • The handle of a derived class object can be assigned to a variable whose type is a base class of that class. If so, the overridden members of the derived class are hidden. To call an overridden method via a parent class object, the method must be declared as virtual. When a subclass is instantiated, the class method new is invoked. If the initialisation method of the superclass requires arguments, and the arguments are always the same, they can be specified when the class is extended. class ExtendedClass extends ParentClass ( 9 ) ; Exam les p class ParcnLClass ; int X = 1; function i n t AFun c ( ) ; AFunc = X 1; end function endclass class ExtendedC1ass extends Pa rentClass ; - int X 2; function int AFunc ( ) ; get = X + 1 ; end function endclass E xlendedClass EP - 132 I I Overridden variable I I Overridden method Copyright 0 1995-2006 by Doutos Lto.
  • 132. Extends ParentClass P = E P ; I I Overridden members of ExtendedCiass are hidden Y P X; I I Y = 1 , not 2 - Y - . P . AFunc ( ) ; I I Y = 0, not 3 or 1 Sea Also Class, Super, Virtual Copyright 0 1995-2006 by Doutos Ltd 133
  • 133. Extern Indicates that the definition of a class method resides outside the declaration of the class. It can also indicate that the tasks or functions declared in an interface (but not a modport, where export would be used instead) are defined in a module using a hierarchical name. Programs, interfaces and modules may have extern declarations to support separate compilation of source files . ..,.. This feature was added in SyslemVerilog { In Classes l extern [ McthodQualiliers . . . I MethodPro t o type; . . . ] MethodPrototype; { In Interfaces 1 extern [MeLhodQualificrs extern forkj oi n '!'ask Prototype; MethodQual i fier - { one of) v i r L ua l ClassitemQualifier • {one of) static protected local { one of) TaskPro t otype FunccionProto type Func t i onProLo Lypo - See Function TaskPrototype = See Task ClassitemQua l i f i e r McL!JodPrototype = See also Interface, Module and Program. class-<HERE>-endclass interfacc-<HERE>-cndin Lerface In order to tie the method declared outside a class back to its class, the method name must be preceded by the class name and the class scope operator. • In order to tie the task or function defined outside an interface back to its interface, the task/function name must be preceded by the interface name and a dot ( . ). • Tasks can be defined in more than one module and executed concurrently, or defined in a module that is instantiated multiple times, using a forkjoln extern declaration in the interface. • Out of block declarations must be declared in the same scope as the class declaration. 134 CopyrlghtC 1!195-2006 Oy Doulos Ltd
  • 134. Extern Exam les p Extern in classes c l a s s AClass; II Extern declaration extern protected vi rtua l function i n t AFunc ( i nt x ) ; endclass function int AClass : : Afunc ( i n t x ) ; I I Removed protected, virtual, added ACiass:: II The rest of the declaration matches exactly the prototype II Method body end function Extern in Interfaces inlcrfacc circbuff_i f ; extern f u n c t i o n read extern function write endinterface: ( i n L d a la ) ; ( i nt data ) ; circbuff i f module ci r cbu f f # ( parameter i n t s i z e ) ( circbuff i f T n t e r f ) ; f unc l ion void Interf . write ( i n t data ) ; cndfuncLion endmodu l e See Also Class, Forkjoin, Interface, Operators, Protected, Virtual Copyo;ght C> 1995-2006 by Doutos Ud. 135
  • 135. Final A final block is like an initial block, but it executes once, in zero time (i.e. like a · function), at the end of the simulation. The final block is useful for displaying information at the end of simulation, such as coverage information. Ill- This feature was added in SystemVerilog final Sta tement module-<HERP.>-endmodu l e generalc-<HERE>-endgenerate interface-<IIERP.>-endi nterface program-<HERE>-endprogram Final blocks execute at the end of simulation, i.e. when the simulator has no more events to simulate, or a $finish has been executed, or all program blocks have finished. A final block may only include statements that are allowed in functions. A final block executes in zero time, like a function call. • There may be several final blocks in a design. They are executed in an arbitrary, but deterministic order. Use one or more final blocks to display statistical information at the end of simulation. For example, a testbench could summarise the number of errors it has detected. Exam les p final begin $displa y ( " Simulation has ended ac I t " , $ realtime) ; $displa y ( "There where % 0 d errors . " , error count ) ; end See Also Cover, Initial 136 Cop)'O!lht C 1995-2006 by Ooulos Ltd.
  • 136. For General purpose loop statement. Allows one or more statements to be executed iteratively. The for keyword is also used in the generate construct (See Generate). .,.. SystemVerilog adds the ability to declare the loop variable locally for ( Initial assignment(s)) (Forin i t i a l i z e , Expression; 1 Loop condition 1 F'orStepAssi gnments , . . . ) { Iteration assignment(s) ) Sla tement F"orin i ti a l i 7. e = (one of) VariableLVa l u e = Expressi on , DataType VariableLVa l u e = Expression, ForS Lcpllssignmen Ls - (one of) ++VariableLVa l ue --Variabl eLVa l ue Vadabl eLVaJ ue ' + VariableLVa l u e - ­ O pera torAssignment VariableLVa l ue = see Procedural Assignment Opera LorAssignment = See Expression See Statement. When the for loop is executed, the initial assignment or assignments are made. Before each iteration, including the first, the expression is tested: if it is false (i.e. zero, X or Z) the loop terminates. After each loop iteration, the iteration assignment or assignments are executed . The for loop control variable may be declared locally within the for loop. If so, it is equivalent to declaring an automatic variable in an unnamed block. Declared for loop variables are by default automatic, regardless of the lifetime attribute of the scope in which they are declared. Copynght c 1995·2006 by Doulos Lid. 137
  • 137. For Gotchasl Beware of using a logic with a small width as a loop variable. Beware also of testing for a logic having a negative value. Addition and subtraction operations roll round and logic values are treated as unsigned, so the loop expression may never become false. is always between 0 and 7 logic [ 2 : 0 ] i ; II i for ( i= O ; i<8; i + + ) II Never stops looping for ( i=-4 ; i < O ; i- i t l II Does not execute In situations like these, use an integer for the loop variable i. for statements may be used by generate statements, but in this context they are not procedural control structure; instead they determine the form of repetitive instances and processes. Exam les p v � 0; for ( i nt I = 0 , int J begin F[IJ = A [ I J & B [J] ; V - V � A(I] ; 3 ; I < 4 ; I = I + + , J = J--) I I 4 separate and gates I I 4 cascaded xor gates end See Also Begin, Do-While, Foreach, Forever, Generate, Repeat, While 138 Copyright C 1995-2006 by DOtJioS Ltd.
  • 138. Force Similar to a procedural continuous assignment, force overrides the behaviour of both nets and variables. It is used to aid debugging. 1 one of) force NcLLValue - Expression; force Vari ableLValue = Expression; { one of} release Ne tL Va l ue; release VariableLValue; NctLValue = see Assign VariableLValue = see Procedural Assignment See Statement. Bit or part selects of nets or variables cannot be forced or released. force takes precedence over a procedural continuous assignment (assign as a procedural statement) A force stays in effect until another force is executed on the same nets or variables, or until the nets or variables are released. When a force on a variable is released, the variable does not necessarily change value at once. The forced value is maintained until the next procedural assignment takes place, unless a procedural continuous assignment is active for the variable. When a force is released on a net, the value of the net is determined by the drivers of that net, and the value may be updated immediately. Use in testbenches to override behaviour for the purposes of debugging. Do not use to model behaviour (use continuous assignments instead). Examples force f = a & & b ; C<>p),lght c 1995·2006 by Douk>$ Ltd. 139
  • 139. Force release f ; See Also Assign 140 CopyrlghlC 1995-2006 by CO<Jios ltd.
  • 140. Foreach The foreach construct specifies iterations over the elements of an array. foreach may also be used to generate iterative constraints (see Constraint). Jl> This feature was added in SystemVeritog foreach (ArrayName [ [ VariableName ] , IVariableName ] , . . . ]) Sta tement See Statement. • The array can be of any type: fixed-size, dynamic, or associative. A loop variable cannot have the same name as the array. • Loop variables are automatic and read-only, and their scope is local to the loop. The type of each loop variable is implicitly declared to be consistent with the type of array index. • Multiple loop variables correspond to nested loops that iterate over the given indexes. The nesting of the loops is determined by the dimension cardinality; outer loops correspond to lower cardinality indexes. • The number of loop variables must match the number of dimensions of the array variable. Empty loop variables can be used to indicate no iteration over that dimension of the array. The mapping of loop variables to array indexes is determined by the dimension cardinality; higher cardinality indexes to change more rapidly. 2 2 int A [ 2 ] [ 3 ] ; bit foreach (A [ i, j ] ) foreach ( B [ i , , m) ) -> Dimension nos 3 [ 3 : 0 ] [ 7 : 0] B . . . [4]; 1 1 i iterates (0: 1 ) and j iterates (0:2] • 1I i iterates [0:3), m iterates [7:0] II . . . [3:0] index is skipped If loop variables are used in expressions other than as indexes to the designated array, they are cast by default as follows: • For fixed-size and dynamic arrays the cast type is int. For associative arrays indexed by a specific index type, the cast type is the same as the index type. Cop)T'9hl c 1995-2006 by Dootos Ltd 141
  • 141. Foreach • For associative arrays indexed by a wildcard index (•), the cast type is unsigned longint. Exam les p string Lc lters [ 4 ] ;:....:. ' { " a " , forcach (Letters [ i ) ) "b'' , " c " , "d " } ; $displ a y ( "T.eller s [ %0d) - % s " , i , Lcllers f i l ) ; i n l Mult [ 0 : 3 ) [ 0 : 7 ) ; foreach (Mult [ i , j ] ) Mu1 t [ i I [ j I = i * j ; II Initialise See Also Constraint, Do-While, For, Forever, Generate, Repeat, While 142 Copyright C 1995-2006 by Douloa Ltd
  • 142. Forever Causes one or more statements to be executed in an indefinite loop. forever Sta tement See Statement. Gotchasl A forever loop should include timing controls or be able to disable itself, otherwise it may loop infinitely. Useful for describing clocks in testbenches. Use break to jump out of the loop. Exam les p initial begln : Clocking Clock = 0 ; forever W l O Clock - ! Clock; end inj t i al begin : Stimulus disable C l ocking; end 1 1 Stops the clock See Also Disable, Do-While, For, Jump Statements, Repeat, While Copyright C 1995-2006 by Ooulos Ltd. 143
  • 143. Fork Groups statements into a parallel block, so that they are executed concurrently. � SystemVerilog adds join_any and join_none and std::process ( Labe l : ] fork [ : Labe l ] [ Decl a ra Lions . . . ] St a temen t s . . . JoinKeyo�ord [ : Labe l ] JoinKeyo�ord • {one of) j o i n j o i n any j o i n none Decl aration � {one of) Variable Typcdef ImporL Virtualinterface Localparam Parame ter Overload See Statement. A fork-join block must contain at least one statement . • A concurrent process is created for each statement in a fork-join. The join keyword (one of join, join_any and join_none) specifies when the parent process (i.e. the process that contains the fork-join) resumes execution: fork-join blocks until all child processes are complete • fork-join_any blocks until any one child process is complete • fork-join_none doesn't block. The parent and child processes all execute concurrently • The order of statements within a fork-join block does not matter. Timing controls are relative to the time at which the block was entered. • begi n-end and fork-join blocks may be nested within themselves and each other. A statement label may be specified before a fork-join block. Labe l r : fork j o i n : LabelF A matching block name may be specified after the block join keyword, preceded by a colon. This is useful when documenting nested pairs of fork­ join. Block names create a hierarchy scope. 144 Cop1fighl Cl 1995-2008 by Doulos Lid
  • 144. Fork • It is illegal to have both a label before a fork and a block name after the fork. A label cannot appear before the join. If a fork-join block is to be disabled, it must be named. The lifetime of a fork-join, fork-join_any, or fork-joln_none block encompasses the execution of all processes spawned by the block. The lifetime of a scope enclosing any fork-join block includes the lifetime of the fork-join block. • Automatic variables declared in the scope of a fork-join are initialised whenever execution enters their scope, before any processes are spawned. (See examples) fork-join statements are useful for describing stimulus in a concurrent fashion. Exam les p initia l : s limulus #20 D a t a = 8 ' ha e ; fork # 4 0 D a L a = 8 ' hxx; Reset - 0; I I This is executed last I I This is executed first # 1 0 Reset = 1 ; join I I Completes at lime 40 initi a l fork f i. rsl_p rocc s s ; second_proces s ; wa i t ( interrupt ) ; j o i n_a n y I I Completes when either process completes, or I I an interrupt occurs Copyright c 1995·2006 by Ooulos ltd. 145
  • 145. Fork In the following example, the automatic variable k is initialized to the value of the loop variable j, at the start of each loop iteration: initial for (i n t j fork � 0 ; j < = 3 ; j++) automalic int k = j ; processl : begin process2 : begin . . . end end j oin_none See Also Begin, Disable, Statement, Timing Control 146 Cop�Tight c 1995-2006 by Ooutos Ltd
  • 146. Forkjoin Tasks must be declared a s extern forkjoin in an interface i f they are defined i n more than one module and executed concurrently, o r defined i n a module that is instantiated multiple times. .,.. This feature was added in SystemVerilog extern forkjoin TaskProto type; TaskProto type ; See Task i n t e r face-<HERE>-endinterface The tasks declared as extern forkjoin may be used to model broadcast communication. Exam les p i n t e r face bus # (parameter N extern ; 0) ( input logic clock ) ; forkjoin Lask slavc_wri le (bi t [ 7 : 0 ] Addr, b i t [ 7 : 0 ] Data ) ; extern forkj oin task slave_read (bit [ 7 : 0 ] Addr ) ; modpo r l slave i f (exporl Lask slave write (bi t [ 7 : 0 ] A d d r , _ bit [ 7 : 0] Data) , expor l L a s k s la vc_ r e ad (b i l [ 7 : 0 ] Addr) ) ; endinter face module mem ( bus busport ) ; Lask busport . slave_wri te (bit [ 7 : 0 ] Addr, bit [ 7 : 0 ] Data ) ; end task endmodule See Also Extern, Interface, Modport �ynght C 1995-2006 byDouto< L1d. 147
  • 147. Function Used to group together statements to define new mathematical or logical functions. ..,.. In SystemVerilog, functions have been enhanced in a number of ways 1 Declaration 1 function [Lifetime] [ Signing] [ RangeOrType ] [ rnte rfaceOrCl ass] FunctionNamc [ (Ports, . . . ) I ; [ Declarations . . . ] [ S ta temen t s . . . ] endfunction [ : FunctionName] 1 Prototype } funcLion T ypeOrVoid FunctionName ( [ Po r t s , . . . ] ) ; Lifetime � (one of) automatic s ta t i c Signing - (one of) :.;igned unsigned RangeOr'l'ypc - ( one of) Ranges . . . Data Type void InterfaceOrCl ass = (one of} Inter-faceNamc . ClassName [ # ( ParameterAssi gnmen ts, . . . ) ] : : TypeOrVoid Range = = (one of) DataType void [Constan tExpression: Cons tantExpression) $unit c l a s s -<IIP.RF:>-endc l ass module-<HERE>-endmodule generate-<IIERE>-endgenerate i nterface-<IIERE>-endlnlcriace package-<HERE>-endpackage program-<IIERE>-endprogram • A function type or range must be given. Functions can be declared as type void but not as event. A function may be declared "ANSI-style" with the ports declared in brackets after the function name. Alternatively, the ports may be declared inside the function. 148 Copyright CO 1995-2006 by Ooolos ltd.
  • 148. Function • A function must have at least one Input port. It may also have inouts and outputs. The default direction is Input and the default port data type is logic. A function prototype specifies the types and directions of the arguments and the return value of a function defined elsewhere. • If a function has default argument values, so must the prototype. • A function may return a value by assigning the function name, as if it were a variable, or by using the return keyword. The return statement overrides any value assigned to the function name. A function may return a structure or union. In this case, a hierarchical name used inside the function and beginning with the function name is interpreted as a member of the return value. A function need not contain any statements. If a function contains more than one statement, there is no need to enclose them in a begin-end. Functions may not contain timing controls (delays, event controls or waits); may not enable tasks; nor be disabled. Functions may be declared as static or automatic. If the lifetime is not specified, the default lifetime may be specified in the enclosing module, interface or program declaration. If not, the default is static. automatic functions dynamically allocate formal arguments and local variables when the subprogram is called. In a static function specific data may be explicitly declared as automatic. If so, data has the lifetime of the call or block, and is Initialized on each entry to the call or block. Similarly, in an automatic function specific data may be explicitly declared as static. If so, data has a static lifetime and a scope local to the block. A static function may not have ref arguments. • A constant function is a function whose value can be completely evaluated at compile time or during elaboration. A constant function must be called with actual arguments that are constants. A constant function is not allowed to call any other tasks or functions. Gotchasl Note that the signing keyword (i.e. signed or unsigned) appears before the return type: funclion signed logic ( 7 : 0 ) func; This is different to the declaration of a variable, for example, where the signing appears after the type: logic signed ( 7 : 0 ) loqic var; Copyright C 1995-2006 by Ooulos ltd. 149
  • 149. Function automatic functions can be used recursively and can be re-entrant. Constant functions may be used in expressions where a constant is expected. For example, to initialise a parameter. To protect arguments passed by reference from being modified in the function, use const ref. Exam les p funct ion [ 7 : 0 ] ReverseB i Ls ; i npul [ 7 : 0 1 Byte; i n teger i ; Lor ( i = 0 ; i < 8 ; i - i + 1 ) B y tc ( i ] ; ReverseBi ls [7 -i ] endfunction function [ 1 5 : 0 ] [ 7 : 0 ] AF'unc ( 1 I A is input by default i n t A, ouLpuL [ 1 5 : 0 ] [ 7 : 0 ) 8, C [ 15 : 0 ] ) ; endfunclion function automatic integer fibonacci ( i nput integer n ) ; if ( n <= 2 ) fibonacci else fibonacci endfunclion 1; - fibonacci ( n - 1 ) + fibonacci ( n -2 ) ; module decoder (A, Y ) ; parameter NumOuts 16; localparam Numins = BitsToFit (NumOuts ) ; input [Numlns-1 : 0 ] A ; funcL i on i n L egcr Bi LsToFiL ( i nLeger n ) ; 1 I Depends only on constants = endfunction endmodule s- Aiso Class, Function Call, Interface, Modport, Task 150 Cop)"lght C 1995-2006 by Doolos Ltd.
  • 150. Function Call Calls a function, which returns a value for use in an expression, or, if the function has the type void, is a statement. II> SystemVerilog adds named argument association and cast to void FuncLionNamc [ ( Argumen ts, . . . ) ] ; Argument � tone of) [ Expression] . PorLNarnc ( [ Expressi on 1 ) See Expression See Statement (void functions) Function calls are expressions unless of type void, which are statements. Non-void functions may also be called as statements, by casting to void: void ' ( non_void_func ( ) ) ; Arguments may be passed by name or position or both. If some are passed by position and others by name, the ones passed by position must be the first ones in the list. • An empty argument list () may be omitted altogether. • Arguments that have default values may be omitted from the call. Empty arguments can be used as placeholders when calling the function. Arguments that are passed by reference must match exactly - no type conversion or casting occurs. Arrays must match exactly in type and dimensions. • It is illegal to call a function with output, lnout or ref arguments in an event expression, in an expression within a procedural continuous assignment, or in an expression that is not within a procedural statement. However, a canst ref function argument will be legal in this context. It is possible to call functions in a constraint expression, but only with certain limitations (see Constraint). See Also Function, Task Enable Cop)T;ghl 0 199S.2006 by Oouloo Lid. 151
  • 151. Gate SystemVerilog has a number of built in logic gate and switch models. These gates and switches can be instanced in modules to create a structural description of the module's behaviour. Logic Gates and nand or nor xor xnor (Output, (Output, (Output, (Output, (Output, (Output, Input, Input , Input, Inpul, Input, I nput , . . . . . . . . . . . . .) .) .) .) .) .) Buffer and Inverter Gates buf not (Output, . . . , Input) (Output, . . . , Input) Tristate Logic Gates bufifO bufi (l notifO noti fl (Output, Input, Enable) (Output, Input, Enable) (Output, Tnput, P.nabl e ) (Output, Input, Enable) MOS Switches nmos pmos rnmos rpmos (Output, (Output, (Output, (Output, Input, Input , Input, Input, Control) Control) Control) Control) CMOS Switches cmos rcmos (Output, Input, NEnable, PEnab l e ) (Output, Input , NEnablc, PEnablc) Bi-directional Pass Switches tran rtran ( I noutl, Inout2) ( Inoutl, Inou t2) BI-directional Pass Switches with Control tranifO ( Inoutl, Inout2, Control ) trani f l ( Inou t l , Inout2, Control) rtarnifO ( I noutl, Inout2, Control) rtranifl ( I noutl , Inout2 , Control) 152 Copj!o<Jhl C 1995-2006 by Ooulos Ltd
  • 152. Gate Pullup and Pulldown Sources pullup (Oulpul) pulldown (Output) Truth Tables The logic values L and H in these tables represent results that have a partially unknown value. L is either 0 or Z. and H is either 1 or Z. and 0 1 X z nand 0 1 X z 0 0 0 0 0 0 1 1 1 1 1 0 1 X X 1 1 0 X X X 0 X X X X 1 X X X z 0 X X X z 1 X X X or 0 1 X z nor 0 1 X z 0 0 1 X X 0 1 0 X X 1 1 1 1 1 1 0 0 0 0 X X 1 X X X X 0 X X z X 1 X X z X 0 X X xor 0 1 X z xnor 0 1 X z 0 0 1 X X 0 1 0 X X 1 1 0 X X 1 0 1 X X X X X X X X X X X X z X X X X z X X X X not buf Output Input Output Input 0 0 0 1 1 1 1 0 X X X X z X z X For buf and not gates with more output, the outputs all have the same value. Copyrighl Q 1995-2006 by Ooulos Lid 153
  • 153. Gate bufifO Enable co 1 X z 0 iii a 0 0 z L L 1 1 z H H bufif1 X X z X X z X z X 1 X z z 0 L L 1 z 1 H H X z X X X z co iii a 0 0 X nolifO z X X X Enable notif1 1 X z 1 z H H 0 1 0 z L L 1 X X z X X z iii a 0 0 co X z X X pmos rpmos 0 Control 0 1 X z 0 z L 1 z H H X X z X X z z z Enable 0 1 X z z 1 H H z 0 L L X z X X X z co iii a z X X X nmos rnmos Control z co iii a 0 1 X z 0 L 1 z co iii a Enable z 0 L L 1 z 1 H H X z X X X z z z z z cmos (W, Datain, NControl , ?Contro l ) ; is equivalent to nmos (W, DaLain , NContro l ) ; pmos (W, Data i n , PConLrol ) ; 154 Copyrighl C'I 199S.2006 by Doulos Lid
  • 154. Gate The switches nmos, pmos, cmos, tran, tranifO and tranif1 , when open, do not change the strength of the input when it is propagated to the output. The resistive switches rnmos, rpmos, rcmos, rtran, rtranifO and rtranif1 reduce the strength of the propagated value as follows: Strength Reduces to supply pull strong pull pull weak large medium weak medium medium small small small highz highz See Also Instantiation, User Defined Primitive Copy>;ght c:> 1995-2006 by Doulos Ltd. 155
  • 155. Generate generate constructs facilitate the repeated and conditional creation of parameterised models. A genvar is an integer that may only be used within a generate loop that uses it as an index variable. { Genvar declaration ) genvar Name s , . . . ; { Generate Region ) generate { see Module ) Modulei tems . . . endgen e rate 1 Generate Constructs} 1 one of) GcncrateLoop GenerateTf GenerateCase GenerateLoop for ( [genvar ] GcnvarNamc - Constan tExprcssion; ( Initial) I Loop condition ) Cons can tExpressi on ; { Iteration assignment ) GenvarllssignmcnL GenerateBl ock Genera teif = i f (Constan tExpression) Genera LeBlock [else GenerateBlock] GenerateCase = case ( ConsLan tExpressi on) ConstantExpressions, . . . Genera teBlock ConstantExpressi ons , . . . GenerateBlock (Any number of cases) ( Need not be at the end) [default [ : ] Gene�·a teBlock] endcase Genera toBlock : ( one of} Modul e! tern begin [ : Name] [Modul e i tems . . . ] end ( only allowed in Generateloop ) 156 CopYfi!Jht c 199S.2006 by Doulos Ltd
  • 156. Generate GenvarAssignment = { one of} GenvarNamc Assi gnmentOperator Constan tExpression ++GenvarName --GenvarNamc GenvarName++ GenvarNameAssignmenLOperator = = + = -= *= /= %= &= {one of) I = A= <<= >>- <<<- >>>= {Genvar} modu le-<fiERE>-enclmodule generale-<HERE>-endgenerate program-<IIERE>-endprogram interface-<HERE>-interface {Generate Region} modulc-<HERE>-endmodule program-<IIERf;>-endprogram inlertace-<HERE>-inlertace {Generate Constructs} modu l e-<IIERE>-endmodule generale-<HERE>-endgenerate program-<IIERE>-endprogram interface-<HERE>-interface A generate region (enclosed by generate-endgenerate) is optional. It does not create a new scope or level of hierarchy. Generate regions may not be nested. • The controlling values in the generate constructs must constants whose values are determined elaboration time. • The generate loop variable must be a genvar. A genvar may not be referenced except in a generate loop. • Within a generate loop, there is an implicit localparam, which has the same name as the loop's genvar. It may only be referenced in that loop. It may be referenced using a hierarchical name. Copyright e 1995-2000 by Doolos Ltd. 157
  • 157. Generate Two generate loops using the same genvar as an index variable may not be nested. Each instance of a generate block - even if the begin-end keywords are absen t - creates a new level of hierarchy, similar to a module instance, except that declarations in the enclosing scope can be referenced directly. The exception to this is that a generate block in a generate If or case that is not enclosed in begin-end does not create a new level of hierarchy - this allows you to have a nested if-else-if scheme where all the generate blocks have the same name. Names in a named generate block may be referenced using hierarchical names. The name of the generate block is declared as an array, the index values being the genvar values. The names of generate blocks in the same scope must be unique, except within a generate if or case. • Generate blocks in programs must obey the rules that programs impose, for example instances are not allowed. Gotchasl In the generate context for, if and case statements determine the form of repetitive and optional instances, initial and always. They are not procedural control structures, which must occur within initial, always,.task or function. • Within the generate case and if statements, begin and end may be used as statement brackets, but in this context they group procedures, instances and continuous assignments to be generated. Use generate regions to enclose declarations that are used only in generated instances. generate for is useful to replace repeated instances of the same module. • generate if provides for controlled optional insertion of code according to the value of a localparam, parameter or genvar. A generate case statement may be more descriptive and elegant than an generate if ... else If chain with the same effect. 158 Copyright C 1995-2006 by Ooulot ltd
  • 158. Generate Exam les p modul e TriStateSclcctor # (parameter N (input [N-1 : 0 ) D, 4) E, output Y ) ; generate genvar I ; for ( 1= 0 ; I<N; I - I + l ) beg i n : B assign Y = E [ I l ? D [ I I : 1 ' b z ; end endgeneratc endmodule module FF # (parameter ClkPo l a r i l y ( i n put C l k , D , output logic 0 ) ; i f (CJ kPol ar ity) always @ (posedge C l k ) 1) I I generate is not needed Q <- D ; else a l ways @ ( negcdgc C l k ) Q <= D ; endmodulc See Also Begin, Case, For, If, Instantiation C<lpjTight 0 1995-2006 by Doulos Ltd 159
  • 159. If A statement which executes one of two statements or blocks of statements dependent on a condition expression. The if-else construct is also used for the conditional generate construct (see Generate) and randsequence production (see Randsequence). ..,.. SystemVerilog adds the unique and priority prefixes and pal/em-matching i f ( CondPredi cate) Sta tement [ e J se S t a temen t ] [ UniqueOrPri ority] if ( CondPredi cate) Sta temen t [ else if ( CondPredica te) Sta tement " .l (else S t a temen t ) UniqueOrPriori ty = ( one of} unique p r i o r i t y CondPredicate ExprOrCondPa ttern ( & & & ExprOrCondPa tcern & & ExprOrCondPa t tern - . . . ] { one of} Expression Expres s i on matches Patt ern Pat tern = see Matches See Statement. The Expression is considered to be true if it is non-zero, and false if it is zero, X or Z. Gotchasl If more than one statement is required to be executed in either the if or the else branch, the statements must be enclosed in a begin-end or fork-join block. 160 Copynght 0 199$-2006 by Ooulos ltd
  • 160. If Take care with nested if-else statements when the else part is omitted. An else is associated with the immediately preceding if, unless an appropriate begin-end is present. Verilog compilers do not understand indentation in the source code! • A set of nested if-else statements can be used to give priority to the conditions tested first. To decode a value without giving priority to certain conditions, use a case statement instead. • Pattern matching is possible using the if-else construct (see Matches). Exam les p if (Cl && C2) begin V = ! V; �I � if 0; ( 1C3) X - A; e l se i f ( ! C1 ) X = B; else X = C; end See Also Case, Generate, Matches, Operators, Priority, Unique Copyrighl C 1995-2006 by Ooulos Lid. 161
  • 161. Import Used to make declarations in a package directly visible within other scopes. Imported names do not require the package name qualifier (PackageName::). In mod ports, the keyword Import is used, and has a similar meaning (See Modport). ..,. This feature was added in SystemVeri/og import PackageiLems, . . . ; Pa ckagei tem - {one of) PackagcName : : Name PackaqeName : : ' See Declaration It is illegal to import names that are already declared in the same scope. This includes names imported from another package. You may import the same name from the same package multiple times. • A wildcard (•) potentially imports all names declared within a package, provided they are not already defined. A wildcard import of a name is overridden by a subsequent declaration of the same name If the same name is wildcard imported into a scope from two different packages, it is an error if the name is used. Gotchasl Importing an enumeration type does not import the enumeration literals; these must be imported explicitly, or using a wildcard import. Exam les p import MyPackage : : • ; import MyOtherPackage : : AName ; 162 Copjright C 1995-2006 by Douloo Ltd.
  • 162. Import See Also Modport, Package, Std:: Cop)Tighl 0 199S2006 by 0ou1os Lid 163
  • 163. Import "DPI-C" Functions implemented in C (or other foreign language) can be called from SystemVerilog using import D P I C declarations. " - " Ill> This feature was added in SystemVerilog import " DPI -C " [ ProperLy] import "DPI-C" [ contex t ] P rope r L y = [ Forej gnName - ] FuncLionProto type [ ForelgnNamc - ] TaskProLo Lypc {one of) context pure Funct ionProLo Lypc TaskProto type = See Function See Task See Function The formal input arguments of imported functions cannot be modified. In the C code, they must have a const qualifier. The imported function can access the initial value of a formal inout argument. Changes made by the imported function to a formal inout argument are visible outside the function. • Imported tasks always return a void value, and thus can only be used in statement context. Imported functions can return a result or be defined as void functions. DPI imported functions can be declared in any place where normal SystemVerilog functions can be (e.g. module, program, interface, generate constructs). • Formal argument types of import and export tasks or functions are restricted to the following subset: • void, byte, shortint, int, longint, real, shortreal, chandle and string • scalar values of type bit and logic all packed types (all end up being one dimensional arrays) of type bit and logic enumeration types • 164 types constructed from the supported types struct, unpacked array and typedef Copyright C 1 995·2006 by Ooutos ltd.
  • 164. Import "DPI-C" • Formal arguments of imported functions only can be specified as open arrays. • Result types of DPI imported functions are restricted to small values. Small values include: void, byte, shortint, lnt, longint, real, shortreal, chandle, and string • • • packed bit arrays up to 32 bits and all types that are eventually equivalent to packed bit arrays up to 32 bits scalar values of type bit and logic Declaring a DPI imported function as pure allows for more optimisations. This may result in improved simulation performance. A function can be specified as pure only if: • Its result depends only on the values of its inputs and it has no side­ effects. It is a non-void function with no output or inout arguments. It does not perform any file operations, read/write anything (including objects from the OS, from the program or other processes, etc.), access any persistent data (like global or static variables). 110, A DPI imported function that is intended to call exported functions or to access SystemVerilog data objects other then its actual arguments (e.g. via VPI or PLI calls) must be specified as context. If it is not, it can lead to unpredictable behaviour. Calling context functions decreases simulation performance. Every task or function Imported to SystemVerilog must eventually resolve to a global symbol. Global names of imported tasks and functions must be unique and follow C conventions for naming. The same global task or function can be referred to in multiple import declarations in different scopes or/and with different SystemVerilog names. A disable statement may be used to disable a block that is currently executing a mixed language call chain. When a DPI import task or function is disabled, the C code follows the following protocol: When an exported task returns due to a disable, it will return a value of 1. Otherwise it will return 0. (This is guaranteed by SystemVer ilog simulators.) When an imported task returns due to a disable, it must return a value of 1 . Otherwise it must return 0. Before an imported function returns due to a disable, it must call the API function svAckDisabledState(). Cop)''9hl c 1995-2006 by Doulos ltd 165
  • 165. Import "DPI-C" • • Once an imported task or function enters the disabled state, it is illegal for the current function invocation to make any further calls to exported tasks or functions. The last three steps are mandatory behaviour for imported DPI tasks and functions. It is the responsibility of the DPI programmer to correctly implement this behaviour. When a DPI imported task or function returns due to a disable, the values of its output and inout parameters are undefined. Same applies to imported functions return values. Gotchasl SystemVerilog 3.1 a used the syntax, import "OPt" and different argument passing semantics. These semantics are deprecated in IEEE SystemVerilog. While import "DPI" is still part of the IEEE SystemVerilog language, the LRM states that compilers shall generate a compile-time error. Exam les p SystemVerilog: module Bus ( ) ; import "DPI-C" funclion void slave_write ( input int data ) ; function void write ( in t data ) ; I I Call C function slave_write (data ) ; endfunction endmodu l e C: h n clude " s vdpi . h" void slave write (canst int 12) (. . .} Sea Also Export "DPI-C", Function, Task 166 Copyrlghi C> 1995·2006 by Doulo$ lld.
  • 166. Initial Contains a statement or block of statements which is executed only once, starting at the beginning of simulation. It defines a static process. initial Sta tement module-<HERE>-endmodule lnLcr1ace-<HERE>-endi nterfacc program-<H�RE>-cndprogram gcncraLc-<HERE>-endqenerate Gotchasl An Initial with more than one statement needs a begin-end or fork-join block to enclose the statements. Use initials in testbenches to describe stimulus. Variables may be initialised in their declarations, instead of in a separate Initial statement. The difference is that an event is generated when using Initial, while no event is generated when a static variable is initialised in its declaration, because the initialisation will occur before any initial or always blocks are started. Gotchasl In Verilog, initializing a variable when it is declared is semantically the same as declaring the variable and assigning it separately in an initial block. In SystemVerilog these are not the same - such variables are initialized before any initial blocks are executed. Copyright 0 1995-2006 by Ooulos Ltd 167
  • 167. Initial Exam les p The following example shows the use of initial to generate vectors in a testbench: logic Clock , Enable , Load, Reset; l og i c [ 7 : 0 ] Data; parameter HalfPeriod = 5 ; i nitial begin : Cl ockGeneralor Clock � 0 ; forever # ( llalfPcrlod) Clock ! Clock; end initial begin Load 0; Enable 0; Reset 0; ff 2 0 Reset = 1 ; 11 1 0 0 Enable = 1 ; # 1 0 0 Data - 8 ' ha a ; Load 1; 810 Load 0; - = - = - #500 disable ClockGenerator; 11 Stops clock generator end See Also Always, Final, Variable 168 Copynghl C'l l99!>-2006 by Douos Lid.
  • 168. Inside Inside is the set membership operator. It is used to determine whether an expression is included in a list of expressions or ranges. It is also used in the set membership case .. inside statement. ..,. This f eature was added in SystamVarilog Expression inside { ValueOrHange s , . . .} ; ValueOrRange = { one of) I::xpression [ Express i o n : Exp ression ] The inside expression is true (1 'b1 ) if the left-hand expression is a member of the set of values or ranges in braces, or false (1 'bO) if not. It may also be unknown (1'bx) - see below. The Inside operator uses the equality operator ( == ) to perform the comparison. This means that the result may be unknown (1 'bx) if the set values contain Xs or Zs. For integral set members, a Z value is treated as a don't care (like a casez or wildcard equality ==?). Note that, as in wildcard equality, but unlike in a casez statement, Z values in the expression on the left-hand side are not treated as a don't-care! If an expression in the list is an aggregate array, its elements are traversed by descending into the array until reaching a singular value. The order of evaluation of the expressions and ranges is non-deterministic. Expressions and ranges may overlap. In the set, a range must be ascending. e.g. [1:2], otherwise it is empty ­ [2:1] contains no values. Gotchasl Unlike comparisons performed by the casez statement, Z values in the expression on the left-hand side of the inside operator are not treated as a don't-care; the don't-care is unidirectional. Copyught 0 1995·2006 by Doulos Ltd. 169
  • 169. Inside Exam les p Given logic I sAMembe r ; logic [1:0) T s AMember a; a i n side { 2 ' b 0 1 , 2 ' b 1 0 ) ; then a = 2 ' bOO a = I I Result = 1 'bO Result = 1'b1 2 ' b01 II 2 'hl0 I I Result = 1 'b1 2 ' bll a - 2 ' b0 x I I Result = 1 'bO a - 2 ' b1x II a = 2 ' bzO II Result = 1'bx a - 2 ' bz l II Result = 1'bx a inside ( 2 ' b ? 1 ! ; II Matches 2'b01, 2'b1 1 , 2'x1, 2'bz1 II Equiv. to {a, b, c, d} a a = inl array I I Result = 1 'bx [$ ] = ' (c, d } ; i f ( V inside ( a , b , a < < ay } ) a Result = 1 'bx inside ( [ 0 : 5 ] . [8 : 15] ) ; string I ; I insi de ( [ "abc" : " def" l l I I I between "abc" and "def' See Also Constraint, Expression, Operators 170 Copyolghr C 1995-2006 by Ooulos Lid
  • 170. Instantiation Instantiation of modules, interfaces, UDPs and gates creates a hierarchical design description. Programs are instanced (usually in a testbench) to provide clear separation and race-free interaction between a design and its testbench. An instance creates a unique copy of a module, interface, program, UDP or gate. ..,. SystemVeri/og adds a number of enhancements including wild-card port connections (. *) { UDP or Gate instance 1 UDPOrGateName [ S t rength) Primi ti veinsLance [ Del<Jy) Primi tivelnstance!J, . . . ; = [ InstanceName [ Range ) ) Termina lConnection ( TerminalConnecti ons) ( one of) = NetLVa l ue ( Outputs, inouts 1 Expression ( Inputs} { Module instance 1 ModuleName [ I ( ParameLerAssignmen ts, . . . ) ) Instances, . . ; . ( Interface instance 1 Inter faceName [ I ( ParameterAssignment.<;, . . . ) ) Tnstanccs, . . . ; { Program instance 1 ProgramName ( B ( ParameterAssignmen ts, . . . ) ] Instances, . . . ; ParameLcrA!JsignmcnL = (one of) ( Ordered assignment 1 OrderedParamAssign, NamedParamAssign, OrderedParamAss i gn NamedPa ramAssign = ... ! Named assignment) - (one of) MinTypeMaxExpress ion Da ta Type (one of} . Pa ramclcrName (MinTypeMaxExpress i o n ) . Pa rameterName ( Va t a Type) Instance 1 = ( one of} n s L a nccName ( [ PortConnecti o ns ] ) I n s tanceName UnpackedDimensions . . . ( ( PortConnec t i o ns ] ) ( Array of instances 1 PortConnections - { one of} 1 Ordered connection 1 [ Por tExpression ] , . . PorLName ( [ PortExpression ] ) . Por LNamc , . . . , . . . ( Named connection) { Implicit named connection 1 ( Implicit connection } UnpackedDimension - (one of) [ ConstantExpression] Copl"!lhl c 1995-2006 by Dooloo Lid 171
  • 171. Instantiation [ ConsLan t Expression : Con s tan tExpressi on ] NetLValue � See Assign PortExpress ion - See Rules module-<HKRE>-cndmodule inter face-<HERE>-endlnlcrface ( Interface instances only} gencrate-<HERE>-endgenerate ( Not program instances ) If an undeclared name is used in a port expression, that name is implicitly declared as a scalar wire. The default net type for implicit declarations can be changed using the 'default_nettype directive. Where an ordered port connection list is given, the first element connects to the first port of the module or gate, the second element to the second port etc. Where a named port connection list is given, the names must correspond to the module's ports, but the order of connections is irrelevant. Module ports may be left unconnected in an ordered port connection list by omitting an expression, leaving two adjacent commas. Ports may be left unconnected in a named port connection list, either by omitting the name altogether, or by leaving the bracketed expression blank. I mplicit .name (and .*) port connections may be used if the instance port name and size match the connecting variable port name and size. Moreover, the connecting variable data type must be compatible to the port data type of the instantiated module. Using .name and : does not create implicit nets. Implicit port connections (both .name and . *) may be used in the same instantiation with named port connections, but not with positional connections. Where a range is given as part of an instance name, this indicates an array of instances. When the bit length of a port expression is the same as the bit length of the corresponding port of the module, UDP or gate being instanced, the entire expression is connected to that port of each instance. If the bit lengths are different, each instance gets a part select of the expression, as specified in the range, starting with the right-hand index. It is an error if there are too many or two few bits to connect to all instances. • 172 The # notation is used in two different ways. It is used both to assign the values of one or more parameters in a module, interface or program instance, and to specify delays for a UDP or gate instance. CopynghtC 199S.2006 by0oulos ltd.
  • 172. Instantiation • Parameters may be assigned using positional or named association, but not both in the same instance. Nested programs with no ports, or top-level programs that are not explicitly instanced are implicitly instanced once. The instance name is the same as the program's (declaration) name. Instances of the gates pullup, pulldown, tran and rtran are not allowed to have a delay. Strengths may not be specified for switches (nmos, pmos, cmos, rnmos, rpmos, rcmos, tran, rtran, tranifO, tranif1, rtranifO and rtranif1). Port Connection Rules If the port has a variable data type, then: An input can be connected to any expression of a compatible data type. Unconnected inputs take the type's default initial value (e.g. 'x for 4-state variables). An output can be connected to a variable (or a concatenation) of a compatible data type. An lnout is not allowed to be connected to a variable. • If the port has a net type, then: An input can be connected to any expression of a compatible data type. If unconnected, it has the value 'Z. An output can be connected to a net type (or a concatenation of net types). a compatible variable type, or left unconnected. An inout can be connected to a net type (or a concatenation of net types) or left unconnected, but not to a variable type. If a port has an interface type, It must be connected to an interface instance or to a higher-level interface port. It may not be left unconnected. If it has a generic interface. it can be connected to an interface of any type. If it has a named interface, it must be connected to an interface of the same interface type. If a port is an unpacked array, The port and the array connected to the port must have the same number of unpacked dimensions, and the same size for each dimension. (The number of packed dimensions may differ.) In an array of instances, Copyright Cl 1995-2006 by Doulos Ltd 173
  • 173. Instantiation If the size and type of the port connection matches the size and type of the port, it is connected to each instance in the array. If a port connection is an unpacked array and the dimensions match exactly in size the dimensions of the array of instances, each remaining element of the port connection is matched to the corresponding element of the port (left index to left index, right index to right index). • If the port connection is a packed array, each instance gets a part­ select of the port connection, starting with all right-hand indices to match the right most part-select, and iterating through the right most dimension first. Too many or too few bits to connect all the instances is an error. Gotchasl It is easy to swap two ports accidentally in an ordered list. If the ports are both the same width and direction, the first indication that anything is amiss may be when incorrect results are seen in simulation. Such errors can be difficult to debug. Use named port connections to avoid this problem for module instances. • Positional and named port connections may not be mixed in the same instance. This differs from task and function calls, where named and positional port (argument) connections may be mixed. An initial value change event may be caused at time zero when the data types differ between the port declaration and connection. • Implicit declarations may be forbidden by the compiler by using compiler directive "default_nettype with argument value none. Use named connections for module ports to improve readability and reduce the likelihood of errors (See above). • Do not use port expressions, other than bit or part selects and concatenations. Use a separate continuous assignment instead. • You can generate block-level testbenches more quickly, if you chose all variables in the testbench so that they match the instantiated module port names and sizes and then use implicit • port connection. . Exam les p UOP instance Nand2 174 ( "ea k l , pu l l O ) # (3,4) ( F , P.., B) ; Copyriuht 0 1995-2006 by Doutos Ltd
  • 174. Instantiation Module instance Counter U 1 ?. 3 ( . Clock (Cl k ) , . Re set ( Rs L ) , . Count (Q ) ) ; In the two following examples, the port QB is unconnected . D ( D) , . Q (Q ) , Equivalent to DFF Ffl ( . Cl k , . D, . Q , . QB ( ) ) ; I I or DFF F fl ( . * , . QB ( ) ) ; DFF F(2 (Q, , C l k , D ) ; DFF Ffl ( . Clk (Cl k ) , . QB ( ) ) ; I1 The following is an and-nor, showing an expression in port connection list nor ( F, A & & B , C ) II Not recommended The following example shows an array of instances module Tristate8 ( ou L , i n , cn a ) ; oulpul [ 7 : 0 1 o u t ; input [7 : 0 ] i n ; input ena; bufiCl Ul [ 7 : 0 ] (out, in, ena ) ; 1 • Equivalent (except the instance names) to ... buf i C l Ul -7 (out [ 7 ] , Ul - 6 (OUL [ 6 J , b u f H I U l 5 (OU L [ 5 ] , b u f i f l Ul- 4 (out [ 4 ] , btl f i f l Ul- 3 (out [ 3 1 , bu f i f l lJI 2 (Olll [ 2 ] , b u f i f l Ul- 1 ( o u t [ l ] , bu fi fl Ul -0 ( o u L [ O J , b u fi f1 i n [ 7 ] , ena ) ; in [ 6 ] , ena ) ; in [ 5 J , cna ) ; i n [ 4 ] , ena ) ; in [ 3 ] , ena ) ; in [ 2 ] , ena ) ; in [ I ] , ena) ; in [ 0 ] , ena ) ; 'I endmodule See Also Bind, Gate, Generate, Interface, Module, Port, Program, User Defined Primitive Cop)<;ght C 1995-2006 by Ooulos Ltd. 175
  • 175. Interface Encapsulates the communication between blocks, allowing a smooth migration from abstract system-level design through successive refinement down to RT­ Ievel. The interface construct facilitates design re-use. At its simplest, an interface is a bundle of nets (or variables). An interface can also include tasks and functions to model bus functionality and it may be parameterized . ..,. This feature was added in SystemVerilog (one of! interface [ Li£cUmc 1 InLcrfaccName [ R ( [ PaL"ameteL·PorLLi s L 1 ! 1 [ [ PortNameList) 1 ; [ 'l'imcUni L I [ PortDecl arati ons . . - 1 In terfaceitems . . . endinlcrface [ : InlcriaceName) interface [ Lifetime I Inter faceName ( ii ( [ Parame LcrPorLLisL I ) 1 [ ( Ports, . . . ) 1 ; ( ANSI-style ] [ TimeUn i t J In terface Items _ . . endinterface [ : InterfaceName J interface InlcrfaccName ( . * ) ; [ 1'imeUn i t J In tcrfacci Lcms . . . endinterface [ : I nterfaceName ) extern inlerface [ Lit'e time J I nterfaceName [ H ( [ Parame terPorti.is t ] ) ) [ ( PortNameUst ) ] ; extern interface [ Lifetime] InterfaceName [ 8 ( [ ParameterPortList] l ] [ ( Ports , - . - l ) ; ParameterPorL Li s L - See Parameter Por LNamei.i s t = In cerfaceitem = See Module ( one of) Declaration Assign Ins Lance 1 interface 1 Tn i ti a l Always Final 176 CopynghiC 1995-2000 Oy Douloo Lid
  • 176. Interface Genera te GeneraLeCase Genera te If Genera LeLoop Assert As sume Cover Bind Alias ModporL Extern $un i t module-<IIERE>-endmod u l e i nterface-<HERE>-endinterface If an extern declaration exists for an interface, it is possible to use : as the ports of the interface. This is the same as placing the ports (and possibly parameters) of the extern declaration on the interface. (See Module for an example.) • Interfaces may be passed as ports or instantiated directly as static data objects within a module (port-less access). The methods used to access internal state information about the Interface may be called from different points in the design. Modports may be used to restrict access to the objects listed in the modport. An interface is connected with a modport by specifying the modport name in either the module header or port connection. All objects declared in an interface can be accessed by port reference, if no modport is used. If the interface is connected with a modport in either the module header or port connection, the interface objects can be accessed by port reference only if lhey are listed in the modport. inte r face An_lnterf; bit B; 1 1 Reference to 8 not allowed through modport A_MP l ogic I n ; modport A_MP ( input I n ) ; end interface module Ml ; An_ l nterf I nl f l ; M2 m ( Int f l . A MP) ; Cop)<lght C t99S.2006 by Doutos Ltd. 177
  • 177. Interface endmodule module M2 ( interface . A_M P I ) ; logic v, ft ; l a s s i gn V assign W - I . In; II Ml . m . I n In accessed by port reference & & Ml . m . B; In and B accessed by hierarchical reference I I Illegal, because B is not in modport A_MP II a s s i gn I .B 0; cndmodulc Interfaces can include task and function definitions, orjust task and function prototypes with the definition in one module (server/slave) and the call in another (clienVmaster). If tasks or functions are defined in a module using a hierarchical name, they must also be declared as extern in the interface or export in a mod port. • Tasks can be defined in more than one module and executed concurrently, or defined in a module that is instantiated multiple times, using an extern forkjoin declaration in the interface. Only a named port can be used to reference a generic interface. The member variables, tasks and functions are referenced relative to the instance name of the Interface as Ins tance . Member. The methods can be abstract, i.e. defined in one module and called in another, using the export and import constructs. • Multiple export of functions is not allowed because they must always write to the result. • If a port declaration has a generic interface type, then it can be connected to an interface of any type. If a port declaration has a named interface type, then it must be connected to a generic interface or an interface of the same type. Use an interface to model any non-trivial bus connections between modules. • Use mod ports to specify bus the directions of the signals in an interface and to control access to the interface's tasks and functions. You can replace an interface with a different one containing the same members, but implemented at a different level of abstraction. The modules connected via the interface can remain unchanged. Use initial or always blocks and continuous assignments in an interface for system-level modelling and testbenches. 178 Copyrlght C 1995-2006 by Doulos Ltd
  • 178. Interface Declare the task and function names in the interface, and use local hierarchical names from the interface instance for both definition and call. This allows design re-use, whereas if you use hierarchical path names, the names would be design-specific. Exam les p Using named bundle: interface FPGAtoOSPint; logic Slarl, N_Reset; logic N_CS, N_OS , R_NW ; l ogic [ 7 : 0 ] AddrBus, DataBus; II Interface definition endinterface : FPGAtoDSPinL module FPGA !FPGAtoOSPint Interf, inpuL logic C lk) ; endmodule modul e OSP ( FPGAtoOSPinL I n l e r f , input l o g i c C l k ) ; endmodule module OUT ; logic C l k ; FPGAtoDS Pinl Inlcrf ( ) ; FPGA FPGAMod ( I n L c r [ , Clk) ; OSP OSPMod ( . Inter f ( l ntel"f) , I• II Positional connection . Cl k) ) ; I I Named and .name or FPGA FPGAMod ( . * ) ; OSP OSPMod ( . ' ) ; 11 Implicit port connections *I endmodulc Using generic interface: modul e FPGAl (inlcrface Inte r f , inpul logic C l k ) ; endmodulc module OS P l ( inter face Inlcrf, input logic Cl k) ; endmodule module DUT ; 1 ogic C l k ; FPGALoOSPint Intf ( ) ; FPGAl FPGAMod ( . InLcr ( ( ln lf ) , DSPl OS PMod ( endmodulc . • , Ccpyrighl c 199�2006 by Oouloo lid I I Instantiate the interface .Clk(Clk) ) ; . I n Lc rf ( I n U ) ) ; I I Partial implicit port connection 179
  • 179. Interface Interface ports, tasks in interfaces: i nterface FPGAtoDSPint ( i npuc logic Cl k ) ; logic Start, T n L 5 i g ; t a s k AddrGen; endtas k : AddrGen endincerface : PPGALoDSPTnL module FPGA ( FPGAtoDSPint I nterf) ; al ways @ ( I nLerf . SLarL ) I n te r f . lclcl rGen ; always @ (posedge Inlerf . cl k ) I n te r f . Acldr [ O ] < - I n L_Si g ; enclmodule module OUT; logic: C l k ; FPGAtoDSPinc I n t f (C l k ) ; Instantiate the interface Has access to AddrGen II FPGA FPGAMod ( . Inler! ( I n L[ ) ) ; II endmodule Multiple tasks exports using forkjoin: interface FPGAtoDSPTnc ( input logic e l k ) ; 1 1 Tasks executed concurrently as a fork-join block extern forkjoin task do_Reg ( ) ; exlern forkjoin task 1ddrGen (input l og i c[ 7 : 0 ] Add r ) ; modport S lave ( . . . , export task AddrGen ( ) ) ; I I Export from module II , using modport modporl Masler ( . . . imporc t a s k AddrGen ( input logic[7:0] Addr) ) ; I1 Import requires the full task prototype initial do Req; endinlerface : FPGALoDSPinL ; module FPGA ( i nterface G I ) ; t a s k GI . do_Reg ; end task t a s k GI . AddrGen ; end task 180 Copynghl 0 1995-2006 by Doulos Lid )
  • 180. Interface endmodule module DSP ( inter(ace GI ) ; loqic [ 7 : 0 ] Addr; a l way� @ (posedge GI . C l k) GI . AddrGen (Addr ) ; II Call slave method via the interface endmodule module DUT; logic C l k ; FPGALoDSPint I n l f ( C l k ) ; FPGA FPGAModl ( I n t f . S l ave ) ; FPGA FPGAMod2 ( I n l f . Slave ) ; DSP DSPMod ( I ntf . Masler ) ; endmodulc Exports do_Reg and AddrGen task Exports do_Reg and AddrGen task I I Imports AddrGen task II I1 Using parameters in interfaces: i n t e r face FPGAloDSP i n t # (AddrWidth - 8 , Dl-lidth � 8 ) ( i nput logic C l k ) ; l ogic [AddrWidlh-1 : 0 1 addr; logic [ DW i dth- 1 : O J daLa; modporl Slave ( . . . , import Lask AddrGcn ( ) ) ; modport Masle r ( . . . , imporl task DinGe n ( i nput logic ( DWidLh-1 : 0 ] D i n ) ) ; task Di nGen ( input logic [Dvlidth-1 : 0 ] D l n ) ) ; cndlask Lask AddrGcn ; endtask endin Lcr!ace : FPGALoDSPint module FPGA ( i nterfacc GI ) ; i f (Gl . Start GT . AddrGen ; == 0) endmodule module DSP ( interface GI ) ; logic [ 7 : 0 ] D i n ; alway� @ (posedge GI . Clk) GI . DT nGcn ( D i n ) ; endmodul e Ccpy�;ght 0 1995-2006 by Doolos Ltd 181
  • 181. Interface module DU'l'; logjc C l k ; I I Instantiate default interface FPGAtoDSPTnt Intf (Clk) ; FPGALoOSPint # ( . 0Widlh ( 1 6) ) DTnt f ( clk) ; I I Changed data bus width FPGA FPGAMod ( In L f . Slave ) ; DSP DSPMod ( Int f . Maste r ) ; DSP OSPModl (Dlntf . Mas Ler ) ; endrnodule I I Access only to AddrGen task I I Access only to DlnGen task I I 1 6-bit wide data bus See Also Function, Instantiation, Modport, Parameter, Task 182 Copyright C 1995-2006 by Ooulos ltd
  • 182. Jump Statements Used to control the flow in a process or randsequence. II> These were added in SystemVeritog return Expression; return; ( Exit from a function } 1 Exit from a task, void function, or randsequence production} break; conLl nuc ; See Statement. • Jump statements do not require the use of block names. • The continue statement can only be used in a loop. The break statement can be used in a loop or a randsequence. The continue statement jumps to the end of the loop and executes the loop control if present. The break statement jumps out of the loop. The return statement can be used in a task, a function or a randsequence production. break and return may be used to terminate prematurely a randsequence (s ee Randsequence). production Use the jump statements in preference to self-disable. See Also Disable, Do-While, For. Forever, Function, Randsequence, Repeat, Task, While Copyright 0 1995-2006 by Doulos ltd. 183
  • 183. Keywords This is a complete list of keywords in SystemVerilog. These reserved Identifiers must not be used as user defined identifiers, unless they are escaped. alias always always_comb always_ff always_latch and assert assign assume automatic before begin bind bins binsof bit endinterface end module endpackage endprimilive endprogram endproperty endspecify endsequence endtable endtask enum shortreal showcancelled signed small solve specify specparam static string strongO strong1 struct super supplyO supply1 table tagged task this throughout time timeprecision timeunit Iran tranifO tranif1 tri triO lri1 longint macromodule matches medium modport module nand negedge new nmos nor noshowcancelled cmos event expect export extends extern final first_match for force foreach forever fork forkjoin function generate genvar highzO highz1 config const constraint contex1 continue if iff ifnone ignore_bins illegal_bins pull1 pulldown pullup pulsestyle_onevent pulsestyle_ondetect cover covergroup coverpoint cross deassign defaull defparam design disable dist do edge else end endcase endclass endclocking endconfig endfunction endgenerate import incdir include initial inout input inside instance int integer interface intersect join join_any join_none large liblist library local pure rand randc randcase randsequence rcmos real realtime ref reg release repeat return rnmos rpmos rtran rtranifO rtranif1 scalared sequence shortint break buf bufifO bufif1 byte case casex casez cell chandle class clocking endgroup 184 localparam logic not nolifO notif1 null or output package packed parameter pmos posedge primitive priority program property protected puiiO triand trior trireg type typedef union unique unsigned use var vectored virtual void wait wait_order wand weakO weak1 while wildcard wire with within wor xnor xor Cop>nghl c 1995 2006 by Ooulos Ltd
  • 184. Keywords p Version S ecifiers The 'begin_keywords and 'end_keywords directives may be used to modify the list of keywords within a section of SystemVerilog source code. See 'begin_keywords in the Compiler Directives section for more information. Verilog-1995 Keywords always and assign begin buf for force forever fork function bufifO highzO bufif1 highz1 if ifnone initi al case casex casez cmos deassign default defparam disable odgo else end endcase endfunction endmodule endprimilive endspecify endtable endtask eve nt inoul input integer join large macromodule medium modulo nand o utput parameter pmos posedge prim itive puiiO pull1 pulldown pullup rcmos real realtime reg release repeal rnmos negedge rpmos rtran rtranifO rtranif1 nmos scalared nor small specify specparam not nolifO notif1 or supplyO supply1 table task time Iran lranifO tran if1 lri triO lri1 lriand trior trireg vectored wait wand weakO weak1 while wire wor xnor xor strongO slrong 1 Verilog-2001 Keywords As Verilog-1995, but with these additional keywords: automatic cell config design endconfig endgenerate generate genvar incdir include instance liblist signed library unsigned localparam use noshowcancelled pulseslyle_onevenl pulse style_o nd etect showcancelled Verilog-2001-noconfig Keywords As Verilog-2001 , but excluding these keywords: cell config design e ndco nfig incdir include Ccp)Tioht C> 1995·2006 by Doulos ltd instance liblist library use 185
  • 185. Keywords Verilog-2005 Keywords As Verilog-2001, but with one new keyword uwire See Also 'begin_keywords (Compiler Directives) 186 Cop)Tight C> 1995·2006 by Ooulos Ltd
  • 186. Library A library is a logical grouping of design elements (e.g. modules, macromodules, primitives, interfaces and conflgs). These design elements may be referred to as cells. A Library Mapping File provides rules for mapping cells to libraries. The existence of libraries makes it possible for there to be more than one version of source code for a given Veri log module, provided these different source code descriptions are grouped in different libraries. LibraryDescriptions . . . LibraryDescriptions = { one o f ) library LibraryName [ FilePa th] [ - incdir FilePal..hs, . . .J ; include Fi l e Pa t h ; Con£igDecl aration The Library Mapping File may be a separate file, whose name and location is tool-dependent. There may be one or more library mapping files. If multiple mapping files are specified, then they are read in the order in which they are specified. The simulator is required to read these files before it processes any piece of SystemVerilog source text, but the standard does not define the name or location of these files - that is tool-dependent. In practice it is probably selected by a tool command-line option, or by default rules. The name lib. map is likely to be used. A library mapping file may contain: • Library clauses, which state the names of the libraries and specify which Verilog source files are to be collected into each library Include directives, allowing library mapping text to be taken from other specified files • The default library is called work. This library is used if no rule applies to a particular module. It is an error if a source file belongs to more than one library. Copynghl C 1995·2000 by Doulos ltd. 187
  • 187. Library The usual wildcard schemes ( ? , " , . . , . ) may be used to write library clauses. An additional abbreviation 1 . . . 1 is provided to mean "any path between here and there.., allowing convenient shorthands. Exam les p All " . v in the directory . . /primitives belong to library MyGates library MyGates . . /primitives /* . v ; References any .v source in a project hierarchy, regardless of the directory names or structure within it library ProjccLLib /usr/dcsign/project/ . . . / • . v All * . v in this directory and in . . /archives belong to library MyDesign l i brary MyDcsign . / * . v, . . /archive s / " . v ; See Also Config, Command Line Options 188 Copyright o 1995-2006 by Ooutos Lttt
  • 188. Local A member of a class declared as local is available only to methods inside the class and it is not visible in subclasses or outside the class. ..,.. This f eature was added in SystemVerilog Jocal ClassMeLhod; local ClassProperty; c l a s s -<HERE>-endc J a s s A class member cannot b e declared a s both local and protected. Gotchasl A local member of a class can be referenced within that class, even if it is in a different instance. Exam les p class 1Class; loca l int i ; function i n t AFunc AFunc � (1Class A) ; th i s . i + A . i ; I I A.i is a local property referenced outside I I its instance, but within the same class e ndfu nc ti on endcla ss See Also Class, Protected, This Copyright c 1995-2006 by Doulos Ltd 189
  • 189. Localparam Feature used just like parameter, except that it cannot be modified directly with the defparam statement or by the ordered or named parameter value assignment. ( one of} localparam [ Da t a Type) Name [ UnpackedDimensions . . . ] - Constan tExpression, Name [ Unpa ckedDimensions . . . J - Cons t a n u :xpression , . . . ; localparam [ Signing J [ PackcdDimensions . . . J Name [ Unpa ckedDimensions . . . J Consr:an tExpression, Name [ UnpackedDimen sions . . . J � ConsLanLExpression, localparam type Name Name Signing - Da t a Type , - DataT ype, (one of) signed unsigned PackedDimension � UnpackedDimension [ ConstanLExpression : Con s L a n L Expressi on ] � ( one of} (ConsLan tExpression] (ConstantExpressi on : Constan tExpression] Sunit module-<IIERE>-enclmodule begin : Labcl-<IIERE>-end fork : Label-<HERE>- j o i n tas k-<IIERE>-cndLa:;k inLer face-<HERE>-endinterface program-<HERE>-endprogram generate-<HERE>-endgenerate package-<IIERE>-endpackagc function-<HERE>-endfunction • 190 localparam defines a module constant that cannot be overridden in instantiated modules. It is calculated at elaboration time. Copyr lghl C> 1995-200£ by OouloS Lid
  • 190. Localparam localparam may depend upon parameters or other localparams at the top level or in the same module or interface. localparams default to type logic of arbitrary size. If any parameter assignments appear in a module's parameter port list, then any parameters in the module become local parameters and cannot be overridden. Gotchasl Local parameters may be assigned to a constant expression containing a parameter, which can be modified with the defparam statement or by the ordered or named parameter value assignment. Exam les p module Decoder ( A , Y) ; parameter Numins = 3 ; localparam NumOuts = 2 * * Numin s ; input [Numins - l O J A; ouLpuL [NumOu L s - 1 O J Y; See Also Cons!, Module, Parameter, "define Cop)TIIIht C 1995-2006 by Doutos ltd 191
  • 191. Mailbox A mailbox enables processes to exchange data. mailbox is a built-in class that resides in the std package. ..., This feature was added in SystemVerilog { Declaration) mailbox [ B ( DaLaType) ] Name (; new ) , . . . ; ( Methods ) function function Lask put function new ( i n t bound = 0 ) ; i n l num ( ) ; ( S i ngu l a r message ) ; int try_put (ref Singul a r message ) ; task geL (ref Singular Mcssa gcLVa l ue ) ; funct i on int try_get (ref Singular MessageLVa l ue ) ; task pee k (ref Singular MessageLValue) ; funct ion inL try_peek (ref Singular MessageLValuc ) ; � Any singular type, i.e. any data type except unpacked structure, unpacked union, or unpacked array data type MessageLva l u e = A valid left-hand side expression Singular See Declaration and Statements. • A type may be specified when a mailbox is declared. If so, this defines the type of the messages that may be stored. If no type is given, messages of any singular type may be used. Methods Mailboxes are created with the new() method. The bound indicates the size of the mailbox queue, with a bound of 0 indicating an unbounded queue, i.e. one for which a put() will never block. num() - returns the number of messages in the mailbox. put() - puts a message in the mailbox, provided it is not full. If it is full, put() blocks until there is enough room. 192 Copyughl 0 1995 2006 by DouloJ lid
  • 192. Mailbox • try_put() - attempts to place a message in a mailbox. If it succeeds, the function returns 1 , otherwise it returns 0. Unlike put(), try_put() does not block. get() - retrieves a message. If the mailbox is empty, get() blocks until a message has been placed in it. If there is a message, but it has the wrong type, an error is generated. try_get() - retrieves a message. If the mailbox is empty, try_get() returns 0 unlike get() it does not block. If there is a message, but it has the wrong type, try_get() returns - 1 . - • peek() - copies a message from the mailbox without removing it. If the mailbox is empty, peek() blocks until a message has been placed in it. If there is a message, but it has the wrong type, an error is generated. try_peek() - copies a message from the mailbox without removing it. If the mailbox is empty, try_peek() returns 0 - unlike peek() it does not block. If there is a message, but it has the wrong type, try_peek() returns - 1 . Gotchas! num() should be used with care, as other processes may subsequently put() to or get() from the mailbox. Mailboxes can be used in testbenches, for example to store the input stimulus for checking against the output of the device under test. Exam les p mailbox mbox - new; sl ri n g message; mbox . pu t ( " Thi s is rnbox . get (message) ; a message " ) ; I I Message now contains "This is a message" See Also Class, Semaphore Copynght C 1995-2006 by Doulos Ltd. 193
  • 193. Matches Matches is used to compare an expression against a pattern in an if or case statement, or when using the conditional operator (?:). Pattern-matching is especially useful with tagged unions . ..,.. This feature was added in SystemVerilog � (one of} VariableName Pa t r: ern * . Constantl -:xpression Lagged UnionMember.Name [ Pa t tern] ' { Pa t terns, . . . } ' {MemberName : Pat tern, MemberName : Pat tern , . . . } ( Pattern-matching Conditional Operator} CondPredicate ? Expression : Expression Con dPrcdi caLc ExprOrCondPa ttern [ &&& ExprOrCondPa ttern && ExprOrCondPa t tern � ...] { one of} Expression Expression maLchcs Pat tern See also If and Case See Case, If, Operators An expression is matched with a pattern using the following rules: • A VariableName always matches, and the VariableName is assigned to the expression. • The wildcard pattern • A constant expression pattern succeeds if its value equals the expression. • . *" always succeeds. A tagged union pattern succeeds if the value has the same tag and, the nested pattern matches the member value of the tagged union. (The nested pattern is omitted for void members). 194 COpyn<;ht C 1995·2006 by Doulos Llu
  • 194. Matches • A structure pattern succeeds if each of the nested member patterns matches the corresponding member values in the Expression. Each pattern introduces a new scope. Each pattern name must be unique and is implicitly declared as a new variable within the pattern's scope. The result of a pattern match is 0 for fail, and 1 for succeed. The expression being tested in the pattern-matching case statement must have the same type as the type of the pattern in each case item. Exam les p typdef union Lagged Invalid void; Va l i d inL i VInt; Vlnt v; int j Pattern-matching case statement: case ( v ) matches tagged Invalid tagged Val i d n en dca se $display ( " v ' s value is invalid" ) ; $ display ( " v i s val id : value i s %d" , n ) ; Pattern-matching if statement: (v ma Lches Lagged Invalid) $displa y ( " v ' s value is i n va l id " ) ; else if ( v matches tagged Valid n & & & n < 0 ) $display ( "v i s val i d , and negaLivc" ) ; if Pattern-matching conditional operator: j = v ma t ches Val i d n ? n : ' x; See Also Case, If, Operators C«>)f�Qht C 1995.2006 by Doolos Ltd 195
  • 195. Mod port Modports may be included in interface declarations. They give direction information for ports and control the use of tasks and functions within particular modules. eature was added in SystemVerilog II- This f modport ModporLNamc (Modport Ports , ModportName (Modpo r t Ports, Modpo rtPorL - . . . . . ) , .) ' ( one of) Direction 8imp 1 ePorts, . . . InterfaceName [ [ ConstantExpression ] ) . ModPortName clocking Cl ockingNamc ImportExport Modpor tTaskOrFunctions, . . . Direction - {one of) i npul output inout ref SimplePort = I one of) PortName . PorLNamc ( ( Expression ) ) ImportExport - (one of) import export {one of) ModportTaskOrF"unction = TaskProLo type FunctionPrototype TaskOrFunclionName FunctionProto type � TaskProto type = See Function See Task interfacc-<HERE>-endinterface All of the names used in a modport declaration must be declared in the interface where the modport itself is. Also the names used must not be declared by another enclosing interface. A mod port declaration cannot implicitly declare new ports. • 196 A mod port expression allows elements of arrays and structures, concatenations of elements, aggregate expressions of elements declared in an interface to be included in a mod port list. This modport expression is explicitly named with a port name, visible only through the modport connection. The type of the port expression becomes the type for the port. Copynght e 1995·2006 by ooulos Ltd
  • 196. Modport Hierarchical references are not permitted within a modport. If a port connection specifies a modport list name in both the module instance and module header declaration, then the two modport list names will be identical. The modport list name may be specified in the module header. The modport name acts as a direction and the interface name as a type. module m • ( in Lcrfuce i . ma s t e r ) ; The mod port list name may also be specified in the port connection with the module instance. The modport name is hierarchical from the interface instance. modu l e m ( i nlcrface i ) ; mod u l e Lop i i i nst; rn m inst ( . i (i i n s L . masler ) ) • If no modport is specified in the module header or in the port connection, then all the nets and variables in the interface have inout or ref direction, respectively. Variables cannot be connected to either side of an inout port; they can be shared across ports if declared with the ref port type. • The mod port may be used to specify the direction of clocking blocks declared within an interface. The clocking block from an interface declared as virtual can be referenced using the · . "-notation only if the interface has no mod ports. • If the interface contains modports, the clocking must be included in the corresponding modport. In order to model at a more abstract level, tasks and functions may be defined in an interface, or in one or more of the modules connected. In a modport these tasks are declared as import tasks. If tasks or functions are defined in a module using a hierarchical name, they must also be declared as export in a modport. A full prototype of the task or function must be used when a modport is used to import a task or function that has been exported from another module or when the task or function has default argument values or arguments are being connected by name. Multiple export of functions in SystemVerilog interfaces is not allowed. In other words, an exported function is only allowed in an modport that is connected once. (See Forkjoin). In hierarchical interfaces the directions in a modport can themselves be mod ports. Copynghl 0 1995-2006 by Douloo lid 197
  • 197. Modport Gotchasl • The directions of ports and the sense of import and export are those seen from the module, not the interface. • Even when a modport is used, all interface members can be accessed using a hierarchical name. • Use modports to specify the directions of signals in an Interface, and to control access to the interface's member tasks and functions. • Use the multiple task export mechanism to count the instances of a particular mod port that are connected to each interface instance. • Modports can be used to create synchronous ports (using clocking blocks), as well as asynchronous ports. Exam les p interface FPGALoDSPi n t ; l o g i c Start, N_Reset; loqic N_CS, N_DS, R_NI·J; logic [ 7 : 0 ] AddrBus, DataBus; modporL Mastcr ( ouLpuL AddrBus, ref DataBu s ) ; modport Slave ( i nput AddrOus, ref DataBu s ) ; endinterface: FPGAtoDSPin t module FPGA (FPGALoDS P i n L . MasLcr I n L e r f , input logic C l k ) ; I I Modport specified in module header endmodule module DSP ( F'PGAtoDSPint Tnterf, input logic C l k ) ; endmodul e module OUT; logic C l k ; FPGAtoDSPlnL I n l f ; FPGA FPGAMod ( . Interf ( I n t f) , Clk) ; DSP DSPMod ( . I n L crf ( I n t f . Slave) , . Clk ( C l k) ) ; I I Mod port specified in port connection endmodule 198 Copyright C 1995·2006 by OouloS ltd
  • 198. Mod port Hierarchical interface: i n t e r face T n t e r f ; i n terface FPGALoDSPint; modport Mas ler ( . . . ) ; (. . .) ; modport Slave e ndj nterface : FPGAtoDSPint rPGAtoDS P i n l I n l f l , modport Master2 Intf2 ; ( I n t f l . Ma s t e r , I n t f 2 . Master ) ; end interface Generic Interface: module FPGA ( i nterface Interf) ; endmod u l e module DUT; FPGAtoDSPinl I n l f ; rPGA FPGAMod ( I nt f . Slave 1 ; I I Connect modport to module instance endmodu l e Tasks in modports: i n t e r face rPGAtoD S P i n t logic [7:0] AddrBus, modport Slave ( ( i nput logic C l k ) ; DataBu s ; . . .) ; modporL Master ( . . . , i mport t a s k DJnGen ( i nput logic [ 7 : 0 ] L a s k DinGe n ( i n p u l 1 og i c [ 7 : 0 ] Di n ) ) ; DTn) ) ; endLask endinterface: FPGAt oDSP in t module FPGA ( i nterface G i l ; 11 Generic Interface endmodule mod u l e DSP ( i nterface G I ) ; logic ]7: 0] Din; a l ways @ ( posedge GI . Cl k ) GI . Di nGen ( D i n ) ; endmodule Cop)'fjghl e 1995-2006 by Doulos Ud 199
  • 199. Mod port module OUT; logic C l k ; FPGAtoDSPinL I nt f (Cl k ) ; II FPGA FPGAMod ( I nt f ) ; I I Access to all Master and Slave tasks 11 Access only to DlnGen task DSP DSPMod ( I n t f . Maste r) ; endmodule Instantiate default interface Exporting tasks: interface FPGAtoDSPint ( i nput logic el k ) ; modport Slave ( . . . , export task DinGen ( ) ) ; II Export from module that uses the modport modport Master ( . . . , import task DinGen ( i nput logi c [ 7 : 0 ] D i n ) ) ; endintcr[acc : FPGALoDSPint module FPGA (interface Interf ) ; task a . DinGcn; II DlnGen method II Call slave method via the interface endlask endmodule module DSP ( interface G f ) ; logic [ 7 : 0 ] D i n ; always @ (posedge GI . Cl k ) G I . DinGcn ( D i n ) ; endmodule module OUT; l ogic C l k ; FPGALo D S P i n L I n L f ( C l k ) ; FPGA FPGAMod ( I ntf . S l ave ) ; I I Exports DinGen task DSP DSPMod ( In t f . Master) ; endmodule II Imports DlnGen task Clocking blocks and modports interface An_I nter f ( input b i t e l k ) ; wire a, b ; clocking CB @ (posedge e l k ) ; inpul a ; output b ; endclocking 200 Cop)rlghl C 1995-2006 by Douloa Lid
  • 200. Mod port modport CTB ( c l oc k i ng CB) ; I I Synchronous testbench modport modport TB ( input a , outpu t b) ; endinterface II Asynchronous tb modport program T (An_Inte r f . CTB Tl ) ; I I Testbench with synchronous port i n i ti a l begin T l . CB . b <- 1 ; end endprogram Modport Expressions interface I ; log i c [ 7 : 0 ] r ; const i n t x;l; bit R; modport A (output . P ( r [ 3 : 0 ] ) , input . O ( x ) , R) ; modporl B (oulpul . P ( r [ 7 : 4 ] ) , inpul . Q ( 2 ) , R) ; endinterface module M ( inlerface i ) ; , initial i . P = i . Q; cndmodulc module top; I i1; M u l ( i l . A) ; M u2 ( i l . B ) ; endmodu l e See Also Instantiation, Interface, Task, Virtual Interface Copyright 0 1995-2000 by Ooulos lld 201
  • 201. Module The module is the basic unit of hierarchy in SystemVerilog. Modules contain declarations and functional descriptions and represent hardware components. Modules declarations may be nested . ..,. SystemVerilog adds nested module declarations and extern modules. (one of) module [ L i fetime] ModuleName [ B ( [ ParameterPorLLi s t ] ) J [ ( PorLNameL i s t ) ) ; [ 'l'imcUni t ) ( PortDeclaraLions . . . I Modul e Items . . . endmodule [ : ModuleName] module ( Lifetime] ModuleName ( i ( [ Pa rameterPorLLis L ] ) I [ ( Po r t s , . . . l I ; { ANSI-style ] [ TimeUni t ] Module Items . . . endmodu le [ : ModuleName I module [Lifetime) ModuleName ( . x ) ; [ TimeUn i t ] ModuleiLems . . . endmodule [ : ModuleName] exlern module [ Li fetime] ModuleName ( # ( ParameterPo r L L i s L ) ] [ ( PorLLisL) ] ; extern module [ Li fetime] ModuleName [ # ( Parame terPortL i s t ) ] [ ( PortDeclara Lions, . . .) I; (The keyword macromodule may be used in place of modu l e ) ParameterPortLi s L Por tNameList = See Parameter ( one of) PortNamcs, . . . PortNamc - { one of) 1 Ordered list) PorLExpression . Name ( [ PortExpression ] ) PortExpression = 1 Named list) [ one of) PortReference { PortReference, . . . ) 202 Cop)Toghl 0 1995·2006 by Doulos Ltd.
  • 202. Module PortReference = ( one of} Name Name [ Constan tExpression] Narne [ Cons tan tExpression : Con s t a n tJ::xp ress ion] Name [ ConsLan tExpress i on + : Con s ta n LExpression] Name [ Cons tan tExpres si on- : Con s t an tExpressi on ] Modul e rtem = (one of} Decla ra tion Defparam Assi gn Instance { Module, gate, UDP,program or interface} Speci fy Initial Al ways Final Generate Genera teCase Generatei£ Genera t eLoop Assert llss ume Cover Bind Alias $unit module-<HERE> -endmodule Several modules may be described in one file. (In fact, a single module can be split across two or more files, but this is not recommended.) • Modules may be defined using the keyword macromodule. The syntax is otherwise exactly the same as for modules. A Verilog compiler may compile macromodules differently from modules, for example by not creating a level of hierarchy for a macromodule instance. This might make simulation more efficient in terms of speed or memory. In order to achieve this, macromodules may be subject to certain implementation specific restrictions. If these are not met, macromodules are treated as if they were ordinary modules. Copyrlghl C> 1995-2006 by Doulos Ltd. 203
  • 203. Module If an extern declaration exists for a module, it is possible to use : as the ports of the module. This is the same as placing the ports (and possibly parameters) of the extern declaration on the module. Module declarations may be nested. Nesting modules can be used to do logical partitioning of a module without using ports. • Nested modules with no ports that are not explicitly instantiated are implicitly instantiated once with an instance name identical to the module name. If they have ports and are not explicitly instantiated, they are ignored. In the port list, the syntax : means that the ports are the same as in a corresponding extern module declaration. In the port list, a name with no port expression (e.g . .A()) defines a port which does not connect to anything in the module. For port connection rules see Instantiation. • Elements of arrays and structures, concatenations of elements, or aggregate expressions of elements declared in a module, Interface or program may be specified in the port list. The type of the port expression is identical to the type for the port. If the port expression is an aggregate expression, then a cast must be used since self-determined aggregate expressions are not allowed. module M (output . bottom ( r [ 3 : 0 ] ) , output . top ( r [ 7 : 4 ] ) ; logic [ 7 : 0 ] r; endmodulc Gotchasl The same keyword, endmodule, is used at the end of both modules and macromodules. • Have only one module per file. This eases source code maintenance for a large design. Use nested module declarations to create a library of modules that is local to part of a design. This way you can use the same module name in different parts of the design to represent different modules. An alternative igurations. way of doing this is to use conf Exam les p macromodule nand2 ( f , a , b ) ; output f ; 204 Cop)Tight 0 1995·2000 by Ooulos Ltd
  • 204. Module inpul a , b ; nand ( f , a , b) ; endmod u l e module PYTHAGORAS ( X , Y, Z ) ; inpul [63 : 0 ] X, Y; output [ 6 3 : 0 ] Z ; parameler Epsilon = l . OE-6 ; real RX, RY, X2Y2, A, B; always @ (X or Y) begln RX - Sbilstoreal (X ) ; RY = $bitstorea l ( Y ) ; X?Y2 (RX • RX) + (RY ' RY ) ; B = X2Y2 ; l - 0 . 0 ; while ( (A - B) > Epsilon I I (A - B ) < -E ps i 1 on) begi n A B; B = (l + X2Y2 I A ) I 2 . 0 ; end end assign Z Srealtob i Ls (l) ; endmodule � module MinMax # ( parameter P ) inpu L MinMaxl , input [ 3 : 0 ) X, Y , ouLpuL logic [ 3 : 0 ) Z ) ; 1 1 ANSI-style port declaration endmodule Nested modules module Mod2 ( . . . ) ; module and2 ( i nput I l , r /. , oulpul 0 ) ; endmodule and2 Ul ( . . . ) , U2 ( . . . ) , U3 ( . . . ) ; endmodule Copyt;ghl C 1995-2006 by Oouos Lid. 205
  • 205. Module Extern module Given extern module Counter # (N = 8) ( i nput C l ock , output Reset , logic [ N- 1 : 0 ] Count ) ; module Counter ( . � ) ; is equivalent to modu l e Counter # (N Bl ( input Cloc k , Reset, output log i c [N-1 : 0 ) Count ) ; endmodule See Also Instantiation, Name, Parameter, Port, User Defined Primitive 206 Copyright C 1995-2006 by O.Wios Ltd.
  • 206. Name Any SystemVerilog "thing" is identified by its name. IJJ>- SystemVerilog adds $root and class scope resolution, $unit and package scope resolution. { one of} { See Rules } Ident i fier P.scapcd TdenLiflcr [ $ root. I [ InstanceNames . . . ( Terminates with white space } { Hierarchical name 1 ] Identifier Packa gcName : ; Name $ u n i t : : Name C l a s sName : : Name { Package scope } { Compilation unit scope 1 { Class scope 1 InstanceName = Identifier [ [ ConstantExpressi on] ] . An identifier consists of letters, digits, underscores and dollars. The first character must be a letter or an underscore, and not a digit or a dollar. Names in SystemVerilog are case sensitive. A type name may not be the same as an instance name. Type names include modules, programs, interfaces and data types. Instance names include tasks, functions, procedures, variables, constants, labels, module, interface and program instances. • An escaped identifier is introduced by a backslash, ends with white space (a space, tab, form feed or new line), and consists of any printable characters, except white space. The backslash and white space do not form part of the identifier; so, for example, the identifier Fred is identical to the escaped identifier Fred. One name cannot have more than one meaning at any particular point in the SystemVerilog text. Inner declarations of names (e.g. names in begin­ end blocks) hide outer declarations (e.g. names in the module of which the named begin-end block is part). Packa e and Class Sco e Resolution g p Names in packages may be referenced by prefixing the package name followed by the scope resolution operator, ::. Alternatively, names may be imported into a local scope using import. • Names in the current compilation unit may be explicitly selected by prefixing $unit::. CopyrightC 1995.2000 by Ooulos Ltd. 207
  • 207. Name • Certain class members, including tasks, functions and constraints, may be referenced outside the class using class scope resolution. This allows these to be defined outside the class itself. Nested Identifiers) Hierarchical Names ( • Objects in SystemVerilog can be referenced using hierarchical names. This means that all nets. variables, events, parameters, tasks and functions can be accessed from outside the block in which they are declared, by using an appropriate hierarchical name. A new level of the name hierarchy is defined by every module, program or Interface instance, named block, task or function definition. • A hierarchical name is a list of instance names, separated by periods (.). An instance name is the name of a module, program or Interface instance, a task or function, or a named block. Instance names may be array elements. $root is the top of the instance hierarchy. The unique hierarchical name of a SystemVerilog object is formed from $root, followed by the name of a top-level module and the names of the module instances, named blocks, tasks or functions that contain the object, separated by periods (.). g U wards Name Referencin p • A name in the form of a hierarchical name consisting of two identifiers separated by a period may reference one of the following: An item in a module instanced in the current module. (This is a downward reference.) • An item in a top level module. (This is a hierarchical name.) • An item in a module instanced in a parent module of the current module. (This is an upwards name reference.) • The first identifier in an upwards name reference may be either a module name or the name of a module instance. • Generally, choose names which are meaningful to the reader. However, this is more important for global names than for local names. For example, G0123 is a bad name for a global reset, but I is an acceptable name for a loop variable. Do not use escaped names. These are intended to be used by EDA tools, such as netlisters or synthesis tools, which may have different name rules to SystemVerilog. 208 COpyright0 t995-2006 by Ooutos Ltd
  • 208. Name • Only use hierarchical names in a testbench, or in high-level system models where there is no suitable alternative. Avoid upwards name references, as they can make the code very hard to understand, and hence to debug and maintain. Exam las l! The following are examples of legal names l z 99 Reset 54Milz Clock$ Module II II Not the same as 'module' Escaped identifier The following names are illegal, for the reasons given. Starts with a number 123a II $data II Starts with a dollar modu l e II A keyword The following example illustrates the use of hierarchical names, and an upwards name reference. module Separate; II Separate.P or $root.Separate.P II Top.R or $root.Top.R logic R; II Top.U1 .R or $root.Top.U1.R Lask T; II Top.U1 .T or $root.Top.U1 .T Top.U1.T.R or $root.Top.U1.T.R parameter P = 5 ; endmodul e module Top; l og i c R; Bottom Ul ( ) ; endmodu l e module Boltom; logic R; II endtask i n i l i al begin : I n i L ialBlock logic R ; II $root.Top.U1 .1nitia1Biock.R Sdisplay (Bottom. R ) ; I I Upwards name reference to Top . U 1 .R $ di s pl a y (Ul . R) ; Copyrigh1 C> 1995·2006 by Ooulos Ud. II Upwards name reference to Top.U1 .R 209
  • 209. Name end cndmodule See Also Import 210 Copynght C 1995-2006 by Doolos ltd
  • 210. Net Nets are used to model connections (wires and busses) in structural descriptions. The value of a net is determined by the values of the net's drivers. The drivers may be outputs of gate, UDP or module instances, or continuous assignments. ..,. SystemVerilog allows nets to have a data type Net 2'ype [ Strength) [ Expansi on ) [ Da t a Type ] [ Delay) NetNameOrArray [ -Expressi on ) , NetNameOrArray [ =Expr essi on ) , NetNameOrArray = [one of} Ne tName NetArrayname Ranges . . . PackedDimension = NecType = [ConsLan LExprcssion: Constan tExpression] {oneof} wor Lrior { Equivalent 1 1 Equivalent} wand t r i and ( Equivalent 1 w i r e tri LriO tril supplyO supplyl u w i re Expansion ( one of} vectored scala red $un i t module-<HERE>-endmodule intcr face -<HERE>-endinlerface package-<HERE>-endpackage program-<HERE>-cndprogram gcnerale-<HERE>-endgenerate Nels have both a net type (such as wire) and a data type, which must be a 4-valued integral type or an unpacked strucl or array of a 4-valued type. The default data type for a net is logic. Ccpynght C 1995-2006 by Dootos Ltd. 21 1
  • 211. Net A Verilog net type may not be followed by the keyword reg in a net or port declaration. Use logic instead, or the keyword var. supplyO and supply1 nets have the values 0 and 1 respectively, and Supply strength. When they are not being driven, triO and tri1 nets have the values 0 and 1 respectively, and Pull strength. uwlre is an unresolved or unidirectional wire. uwire nets are only allowed one driver. If the keyword vectored is used, bit and part selects and strength specifications may not be permitted, and the PLI may consider the net 'unexpanded'. If the keyword scalared is used, bit and part selects and strength specifications are permitted, and the PLI should consider the net 'expanded'. These keywords are advisory. • Nets must be declared before being used, except for ports and scalar wires in structural descriptions and the target of continous assignments. When two nets connected by a port are of different net type, the resulting single net may be assigned one of the following: the dominating net type if one of the two nets is dominating, or the net type external to the module. • (Multi-dimensioned) arrays of nets are allowed. Truth Tables These tables show how conflicts are resolved, when a net has two or more drivers, assuming the strength values are the same for each driver. If not, the driving value with the highest strength drives the net. wire tri 0 1 X z 0 0 X X 0 1 X 1 X 1 X X X X X z 0 1 X z wand triand 0 1 X z war trior 0 1 X z 0 0 0 0 0 0 0 1 X 0 1 1 X 1 1 1 1 1 1 0 X X X X X 1 X X z 212 0 X 0 1 X z z 0 1 X z Copyroght C 1995-2006 by Doulos Ltd.
  • 212. Net 0 1 0 0 1 X X X z 0 TriO X z tri1 0 1 X X 0 1 X 1 0 0 1 X X X 1 X X X 0 z X z X X 0 1 X 1 X X X X 0 1 X 1 GotchasI • The strength of a continuous assignment to a triO or tri1 net does not affect the value and strength of the net when it is not being driven. This is always strength Pull, and logic value 0 (triO) or 1 (tri1 ). The position of the optional expansion key word scalared or vectored is different between the IEEE standard and the Cadence de facto standard. In the latter the keyword comes immediately in front of the range. • Declare all nets explicitly at the top of each module, even when an implicit This improves the readability a nd maintainability of the SystemVerilog code, by making the intent clear. Using the compiler directive 'default_nettype with argument value none outlaws implicit declarations. declaration could be made. Use supplyO and supply1 to declare ground and power nets only. If a net is declared as signed, arithmetic operations and comparison respect the sign, and any required sign extension is automatic. Exam les p wire Clock; w i re [ 7 : 0 ] Address; wire enum t rod, green, blue ) l ig h L ; t r i l [ 3 1 : 0 ] Data, B u s ; L r i rcg ( l arge) C l , C 2 ; wire f a & & b, g � a I I b; I I Continuous assignments See Also Assign, Data Type, Port, Variable Copynght C 1995-2006 by Ooulo8 Lid 213
  • 213. New Creates an instance of a class or covergroup; sets or changes the size of a dynamic array. Ill- T/1is feature was added in SystemVeri/og { Variable Declarations l ) I ClassNamc Name = new ( (argumcnLs, ClassNamc Name = ( Class instance J new HandleExpression . . . ( Shallow copy} CovcrgroupName [Name] = new [ (arguments, DaLaType Name ( ] . . . ) ] ( Covergroup J ( Dynamic array J - new [Expression) [ (Expression ) ] ( Statements l { Class instance ] VariablcName new [ (Arguments , VariableName new Handl eExpression; Var.iableName new (Expression] [ (Express i o n ) ] lla ndl cExpression � . . . J1; ( Shallow copy} ( Dynamic array ) Expression that evaluates to an object handle See Variable for declarations See Statement for statements • When declaring a new covergroup instance, the instance name may only be omitted within a class, and only then if there are no other instances of the covergroup. The size of a dynamic array may be specified or changed using new. Exam les p Class C; int s.ize ; covcrgroup cov size @ {posedge Clock) ; coverpoint s i zel endgroup funcLion new { inpul 214 0) ; II Class constructor C011yrlgh1 C 1995-2006 by Doulos Lid.
  • 214. New si ze j; cov_size = new; cnctfunction endcl.ass C I I Covergroup instance cl, c2, c3; I I Declare and initialize C c � = new; i ni t l a J begin cl I I Size = 0 I I Size = 1 0 new; c2 new ( 1 0 ) ; I I Size = 1 0 c3 - new c 2 ; end Dynamic arrays l n t Names [ ] Names = = n ew [ 20 ] ; new [ 4 0 ] (Name s ) ; I I 2 0 elements I 1 Expand to 40 elements See Also Array, Class, Coverpoint, Variable Copyrtghl C 1995-2000 by Oou$os Ltd. 215
  • 215. Number An integer or real mathematical number. Integers in SystemVerilog are represented by bits, some of which may be unknown (X) or high impedance (Z). .,... SystemVeri/og adds unsized numbers, e.g. '1, 'x and 'z {one of} BinaryNumber OctalNumber DecimalNumber 1/exNumber Real Number Bina1·yNumbcr {Size] BinaryBase BinaryDigi t . . .. � OcLalNumber - [ S ize] Octa l Hase Octa ! D i g i t . . . DecimalNumber {one of} = [ Sign] Digi t . [ S i ze ] Decima lOase HcxNumber . . { Signed number J Digit . . . [Size] HexBase HexDigit . . . = tone of} Rea l Numbe r = [ Si gnl Digi L . . . { Fixed-point number} . Digi L . . . [ Sign) Digit . . . [ . Di gi t . . . ) e [ Sign) Digic . . [ Sign) Digi L . . . [ . Digi t . . . ) E [ Si gn ) Di g i t . . . . {one of) ' [s / S ) b ' [ s/S ) B [one of} ' [ s /S ) o ' [ s/S } O BinaryBase = Occa1B a se = tone of} ' [ s / S ) d ' [s /S ) D {one of) ' (s / S ) h ' [ s/ S ) H DecimalBasc HexBase � Size - Di gi L . . . Sign = t one of} + - Digit = tone of} _ 0 1 BinaryD i g i t - [one of} 2 3 4 5 6 7 8 9 x x z z ? o 1 OctalDigi t = { one of} _ x X z z ? 0 1 2 3 4 5 6 7 HcxDi g i t = b B c C { one of} x d D e E f F X Z Z ? 0 1 ?. 3 4 5 6 7 8 9 a A UnsigncdNumbcr - Digi L . . . See Expression. Base letters, hex digits, X and Z are not case sensitive in numbers. The characters Z and ? are equivalent in numbers. 216 Co!>yrlght C 1995-2006 by Ooulos Ltd
  • 216. Number Numbers may not contain embedded spaces. However spaces are allowed either side of the base. • Negative numbers are represented in two's complement. • An underscore is not allowed as the first character of a number. (This would be a valid identifier.) Otherwise, underscores may be included for readability, and are ignored. The size indicates the exact number of bits. The size of an unsized number may default to 32 or more bits, depending on the implementation. If the size is greater than the number of bits specified, the number is padded on the left with Os, unless the leftmost bit is X or Z, in which case the X or Z is used to pad to the left. • Unsized unsigned constants where the higher order bit is unknown (X) or three-state (Z) are extended to the size of the expression containing the constant. This breaks the backward compatibility with Verilog-1995 (see Example). If the size is less than the number of bits specified, the number is truncated from the left. The sized literal numeric values, which are unsigned by default, must be explicitly marked as signed when required, using the s qualifier. The default type for fixed-point format and exponent format is real (e.g. 0 . 5, 9 . 0el0). • Unsized literal single bit values may be specified with a preceding apostrophe ( ' ). but without the base specifier. All bits of the unsized value are set to the value of the specified bit. '0, '1, ' X, 'x, 'Z, 'z I 1 Sets all bits to this value Gotchasl A sized negative number is not sign extended when assigned to a variable, unless signed variables are used. l oq i c [ 7 : 0 ] ByLc; l og i c ( 3 : 0 ] nibble; i n i Lial begin nibble = ByLc -1; n ibbl e ; I I i.e. 4'b1 1 1 1 I I Byte becomes B'bOOOO_1 1 1 1 end Cop)Tight C> 1995-2006 by Doulos ltd. 217
  • 217. Number An expression that has any unsigned operands will always result in an unsigned value. There is no space between time number and the time unit (e.g. 10ns). • Use ? in preference to Z in case statements and with the ==? and !=? operators. Do not use ? in other contexts, because it might be confusing. Use underscores to make long numbers more readable. • p Exam les -253 I I A signed decimal number ' Ha£ 1 1 An unsized hex number 6 ' o67 I I A 6 bit octal number 8 ' bx II An 8 bit unknown number (8'bxxxx_xxxx) 4 'bzl I I All but the lsb are Z (4'bzzz1 ) reg signed ( 3 : 0 ] 5 4 ; S4 -4; I I 4'b 1 1 00 54 »> 1 ; 54 I I 4'b1 1 1 0 = -2 54 54 + 2 ' sb l l ; I I 4'b 1 1 01 = -3 Broken backward compatibility reg [ 6 3 : 0 ] v/64 ; W64 64 ' b z ; W64 - ' bz ; I I Verilog-1995: 64 ' hO O O O O O O O z z z z z z z z I I Verilog-2001: 64 ' h z z z z z z z z z z z z z z z z The following numbers are illegal for the reasons given: 23 II Begins with _ 8 ' HF F II Contains two illegal spaces Oae I I Decimal number with hex digits X I I A name, not a number (use 1'bx) . 17 II Should be 0.17 See Also Casting, Expression, String, $signed, $unsigned 218 Copl'lgh1 C 1!l9S.2006 by Ooulos Lid
  • 218. Operators Operators are used in expressions to produce values from operands such as numbers, parameters and olher sub-expressions. The operators in SystemVerilog are similar to those in the C programming language. II>- A number of new operators were introduced in SystemVerilog Unary operators + - sign & -& I - I � logical negation bitwise negation reduction (-" and "- are equivalent) ++ i j � -- i increment decrement I i -- Binary operators + .. I - ** arithmetic % modulus > >- < <- comparison logical && I I == ! ; logical equality case equality wild equality bitwise ("- and -" are equivalent) , __ & I << >> <<< >>> shift Assignment operators simple assignment ,_ -- • - I= %= &= 1 - , _ <<= >>= < < < = >>> = operator assignment Other operators : C B, C A ? B A, N(A) conditional concatenation replication class or package scope resolution operator >> << event or Streaming i ns i de Set-membership or Copyrighl CI 199S-2006 by Oooios Ltd 219
  • 219. Operators See Expression. The logical operators treat their operands as Boolean quantities, as follows. A non-zero operand is considered True (1 'b1 ), and zero is considered False (1 'b0). An ambiguous value (i.e. one that could be True or False, such as 4'bXXOO) is unknown (1'bX). The bitwise operators (- & I "' "'- -"'). bitwise assignments (&= 1= "'=) and case and wild equality operators (=== I== ==? I=?) treat the individual bits of their operands separately. A logic comparison with == or I= is unknown (1 'bX) if any of the bits in either operand is X or z. (But see Gotchas!) • For the "wild equality" operators (==? and !=?), X and Z in the right operand are treated as "don't care" (Similar to casex). X and Z in the left hand operand are not wildcards. The streaming operators (<< and >>) can only process certain types that can be packed into a stream of bits, called "bit-stream" types. The streaming operators perform packing of bit-stream types into a sequence of bits in a user-specified order. When used in the left-hand-side, the streaming operators perform the reverse operation, unpack a stream of bits into one or more variables (see Casting). The stream-operator determines the order in which data is streamed: >> causes data to be streamed in left-to-right order, while << causes data to be streamed in right-to-left order, after being optionally broken up into slices with the specified number of bits. The default slice-size is 1 . No padding is added if the last slice is less than the slice width (see Expression). int j = ( 11 X " , " y n , " z " ) ; » 1 {j l l « byte I I Generates stream "x" "y" "z" { j l l I I Generates stream "z" "y" "x" Streaming operators treat a multi-dimensional packed array as a single integral type, whereas an unpacked array of packed items causes each packed item to be streamed individually. • When applied to a class handle, the streaming operator streams the contents of the object, not the handle. • A comparison with (< > <= >=) is unknown (1 'bX) if the comparison is ambiguous. For example, 2 ' b l O > 1 ' bOX 2 ' bll > l ' blX 220 II is TRUE (1'b1) II is Unknown (1'bX) Cop)11ght 0 1995-2000 by Ooutos Ltd
  • 220. Operators (But see Gotchas!) The reduction operators (& -& I - 1 " -" "-) reduce a vector to a scalar value. Arithmetic operations on sized expressions 'roll-round', so that, for example, 4'b 1 1 1 1 + 4'b0001 gives 4'b0000. Integer division truncates any fractional part towards zero. • Modulus (%) gives the remainder when the first operand is divided by the second, the result taking the sign of the first operand. • Only certain operators are allowed in real number expressions: unary + and -, the arithmetic, relational , logical, equality and conditional operators, the event or. The result of using logical or relational operators on real numbers is a single bit value. The conditional operator (?:) takes three operands. If the first expression is true, the operator returns second expression; if false, it returns third Expression. If the first expression evaluates to X or Z, then the second and third expressions are evaluated and their results is combined, bit by bit. The conditional operator can also perform pattern-matching (See Matches). Exponentiation operator •• is the same as the C library's pow() function, and works both for integer and real values. The inside operator is scanning the members in the list that is the right­ hand-side operand, until a match with the left-hand-side operand is found (see Inside). The arithmetic left shift operator <« shifts the left operand to the left by the number of bits given by the right operand. The vacated bit positions are filled with zeroes. It is identical to • «. The arithmetic right shift operator »> shifts the left operand to the right by the number of bits given by the right operand. It fills the vacated bit positions with zeroes if the result type is MSBit (the • unsigned, or with the value of the sign) of the left operand if the result type is signed. The keyword or or a comma character (,) may be used as an event logical or operator. A combination of these can be used in the same event expression. Assignment operators (= += -= etc.) may only be used with blocking assignments, or in continuous assignments. An expression can include a blocking assignment, if it does not have a timing control. The assignment must be enclosed in parentheses. if ( (A = B) ) B = (A += 1 ) ; The operators ++, - - , +=, -=, *= and /= can have operands of type real and shortreal (the increment or decrement is by Copynght C> 1995-2006 byDoulos Ltd 1 .0). 221
  • 221. Operators Identifiers on the left side of the scope-resolution operator (::) can be only class names or package names. The :: operator uniquely identifies a member of a class. It also allows access to static members, type declaration and enumeration named constants from outside the class hierarchy, as well as access to public or protected elements of a superclass from within a derived class. It applies to all static elements of a class (e.g. static properties, static methods, typedef, enum, struct, union, nested class declarations). O erator Precedence p { highest precedence l [1 I) + - - & - & I -1 � -� �- ++ -- t Una�) * . * I % ( Bina�} << >> <<< >>> < <- > >- inside dist + { Bina�) & � A- -� { Bina�) { Bina�) && I I ?: -> · - ; - %- &- A� { 1 { 1 1 1 { Concatenation ) � +� I � <<� >>� <<<� >>>� := : / <= { lowest precedence ) Gotchasl • The rules about unknown and ambiguous comparisons using ::;::; f::; < > >= are not followed closely by all simulators. Take care! <::; • Note the distinction between the una� reduction operators and the bitwise logic operators, which look the same. The meaning depends on the context, and brackets may be needed to force a particular interpretation. • When manipulating string values in vector regs, the regs should be at least a•n bits (n is the number of ASCII characters) in order to preserve the 8-bit ASCII code. It is better to use the string data type. 222 Copyrighi C 1995·2006 by DOIJios Lid.
  • 222. Operators • Use brackets rather than operator precedence to form expressions. This will prevent mistakes, and make it easier for those with less knowledge of the SystemVerilog language to understand your expressions! • The common string operations are supported by SystemVerilog operators as follows: copy by simple assignment, concatenation by the concatenation operator, comparison by the equality operators. Exam les p II - 1 6 ' dl 0 a + b X An expression, not a signed number! 'is y ! Enable II Same as Reset & & (!Enable) a & & b I I c && d II -4 ' b l l O l II Same as (a && b) II (c && d) Gives 4'b0010 & B ' hff II Gives 1 'b1 (all bits are 1 ) Reset && reg signed [ 3 : 0 ] Shftln, ShftOut; Shftrn = 4 ' b 1 0 1 0 ; ShftOut - (Shfttn >>> 2 ) ; II Shft0ut becomes 4b1 1 1 0 Assignment to RegA when a n event occurs o n A o r B @ (A, B ) RegA = RegS; Or and , in sensitivity list always @ (A or B , C, D or E) Replication operator (or multiple concatenation) 1 4 1 1'bl} 1 II Equivalent to 4'b1 1 1 1 Class scope resolution operator class BaseClass ; int x ; static task ATask (int i , i n t j ) ; endtask endclass BaseClass B int x = 1 ; = new; B . ATa s k (BaseClass : : x , x) ; I I BaseCiass::x and x are different Copyr;ght 0 199S.2006 by Doolos Lid. 223
  • 223. Operators Pack/unpack streaming operations i n t x , y, z ; logic [ 3 : 0 ) v [ 2 : 0 ] ; logic [ 4 : 1 ] •11 , w 2 , w3; bit [ 96 : 1 ] a = { » { x, y, z } } ; b i t [ 1 00 : 0 ] c = [ » ( x, y, II ( > > { x , y, z } } = 9 6 ' b l l l ; II ( >> ( •1 1 , •12 , w3 } } II inL b = v; = (>>{x, y, z } } ; Pack x, y, z, each 32 bits z } } ; I I c is paddedwith 5 bits Unpack x = 0, y :: 0, z= 7 w1 v[2), w2 = v[1), w3 = v[O) I I Error: b is 32 bits < 96 bits = See Also Casting, Class, Expression, Inside, Property, Protected, Sequence, Static 224 Copyright 0 1995-2006 by Ooulos Ltd.
  • 224. Package A package is an explicitly named scope that provides a means to share parameters, data, type, task, function, sequence, and property declarations among st multiple modules, interfaces, programs or compilation units. ..,.. This feature was added in SystemVerilog package PackageName; [ Timcuni t ] Packagci L cms . endpac kaqe Packageitem [: . . PackageNamc ] - {one of ) Dec l a ra t i on Specpa ram Anonymous Program 'l'imeuni t AnonymousProgram = program; AnonymousProqraml tems . . . endprogram AnonymousProgramitem = {one of) Task Function C l ass ClassConstructor Covcrgroup $unit Items within packages cannot have hierarchical references. Declarations made in a package may be referenced using the scope resolution operator : : or via the import statement. Use the package construct to declare global parameters, variables and nets. Copynght C 1995-2006 by Doolos ltd 225
  • 225. Package Exam les p package PO; lnt a; cans t b l l c endpackage : PO package P l ; int b; = 0; const b i t c - 0 ; endpackage : Pl module Mod; imparL PO : : * ; wire w l - P l : : b ; I I no need for import clause wire w2 - c; import PO : : c ; endmodule II 11 The import of PO : : c is forced Error: conflict between PO::c and P1::c See Also Import, Sid:: 226 Copjflght 0 1995·2006 by Doutos ltd
  • 226. Parameter Parameters are a means of giving names to constant values. The values of parameters can be overridden when a design is compiled (but not during simulation), thus enabling parameterization of bus widths etc. II- SystemVerilog adds parameter type and allows the keyword parameter to be omitted in parame ter port lists. ( Declaration - one of) pa rameter [ Da ta 1 ype ] ParamAssignments, . . ; parameter [ Signing ] [ PackedDimen sions . . . ] ' . Pa ramAs s i gnmen t s , . . . ; parameter type TypeAssi gnm en t s , 1 Parameter Port List - one of) PaL·amllssi gnmen ts, . . . [ ParameterPortDeclarations, . . . ] ParameterPortDeclara tions, . . . ParamAss ignmen t = ParamclcrName UnpackcdDimcnsions ParametcrPorLDcclara Lion - (parameter( [parameter] ( Da ta 1'ypel [Signing] = Con s L a n L Exprcssion ( one of) ParamAssignmen t s , . . . [ Pa ck edDimens i ons . . . ] ParamAssignments, . . . ; [paramcler] Lypc Typcllssignmc n t s , . . . ; TypeAssignments - Name = Signing = Da t a Type (one of) s igned unsigned [ Const a n t Express i on : Constan tExpression] Pa ck edDi men s i on = 1 Parameter port list J module Name # (<liERE>) -cndmodul e interface Name # (<HERE> ) -endinterface program Name # (<HERE>) -endprogram [ Parameter declarations J $unit module-<HERE>-endmodul e begin : LabeJ -<liERE>-end fork : Label-<HERE>- j oin Lask-<HERE>-endlask interface-<HERE>-endinterface Copyrlghl c 1995-2006 b y Doulos Ltd 227
  • 227. Parameter generaLe -<HERE>-endgcncraLe package-<!IERE>-endpackage proq ram-<HERE>-endprog ram c l a s s - <I IERE> -endcl a ss func t ion-<HERE> -endfun ction Parameters are constants: it is illegal to modify their values during simulation. But parameter values can be changed at compile time using defparam, or when a module containing parameters is instanced. A const can be set during simulation. Parameters cannot be assigned a constant expression that includes any specparams. In a list of parameters, a parameter can depend on earlier parameters. Parameters may be overridden using named association (similar format to that of named association of nets to module ports). Individual parameters may also be left at their default values. Parameters may have size and/or type. A parameter may be defined with an expression containing another parameter or localparam. • If a data type is not specified, the parameter's type is determined when the value is determined. • A type parameter is a parameter whose value is a data type. This allows a module, for example, to be parameterised with a data type. • S can be assigned to parameters of integer types. A parameter to which s is assigned can o nly be used when $ can be specified as a literal constant, in an unbounded range, for example. • System function S i s unbounded can be used to check that a constant is a $, i.e. S i sunbounde d ( Cons tExpression) ; • parameter can be used as a synonym for the localparam in generate blocks, packages or compilation unit scope. Such parameters cannot be overwritten. • If any parameter assignments appear in a module's parameter port list, then any parameters in the module become local parameters and cannot be overridden. Gotchasl A parameter declaration must include a value, even if the parameter is going to be overridden. 228 COI))foght C 1995-2006 by Ooulos Ltd
  • 228. Parameter • Parameter declarations in a parameter port list ( module #( ... ) ) are separated by commas, not semicolons. • Implicit : named association of parameters is not allowed. Use parameters extensively to give meaningful names to literal values. Use localparams if a parameter is not supposed to be overridden. Exam les p This is an example of an N bit parameterizable shift register. Different instances of Shifter can have different widths. module Shifter # ( NBits (input input = II 8) Keyword parameter is omitted C l oc k , I n , Load, [ NB its - 1 : 0 ] Data, output Out) ; always @ ( poscdgc C l o c k ) if (Load) Shi ( tRcg <- Data; else S h i f tReg <- { Sh i ( t Reg [ N B i t s - 2 : 0 ] , Tn} S h i f LRcg [ N B l l s - 1 ] ; as s ign Oul e ndmo du le module TestSh i fter; defparam U2 . NBi t s Shifter # ( 1 6 ) Sh i f ler U2 U1 = 10; II 16-bit shift register II (. . . ) ; ( . . . ) 1 O-bit shift register en clmodule Sized parameters parameter [2 : 0 ) I dl e 3 ' bl00, Go1 3 ' b010, Go2 3 ' b0 0 1 ; Typed parameters parameter integer S i z e Copyright C 1995-2006 by Doulos Ud. 1; 229
  • 229. Parameter Named association of parameters module UseShifter ( . . . ) ; Shi fter # ( . Nbits ( l O ) ) MyOHc�deShi fLer ( . . . ) ; I I Limit is unaffected Parameter dependence parameler WordSize = 16, McmSizc - WordSi ze' l O /. � ; Type Parameter module Ml l ! int BitNo = 7 , P = BitNo • 4 , I I P depends on BitNo parameter type ParType = shortreal ) ( i nput bit [BitNo : O ] I n , output b i t [ Di LNo : O ] Oul ) ; Pa rType P o ; I I Type of P is set by ParType parameter (shortreal = II unless redefined) endmodule module M2 ; bil ( 1 5 : 0 ] I n , Ou t ; Ml # ( . DiLNo ( l 5 ) , . ParType ( real ) ) Ul ( I n , OuL ) ; 11 ParType redefined as real endmodule See Also 'define, Defparam, Instantiation, Interface, Localparam, Specparam 230 Copyright C 1995-2006 by Doulos Lid.
  • 230. PATHPULSE$ A specparam used in a specify block to control pulse propagation. A pulse is two scheduled transitions on the output of a module that occur in a shorter period than the delay through the module to the output. By default, pulses are rejected by the simulator; this means that only transitions which are longer than the delay through the module are propagated. This effect is called "inertial delay". The PATHPULSE$ specparam allows this default behaviour to be modified. t one of } PlTIIPULSE$ - ( LimiL [ , Limi L ] ) ; PATH PULS E $ Tnput$0utput = { (Reject,Error) J (Limi t [ , Limi t ] ) ; L.imj t - Const.anLMin TypMaxExpression specify-<HERE>-endspecify The two invocation options, error limit and reject limit, can specify percentages applying globally to all module path transition delays. The percentage values may be integers between 0 and 100. The default values are 100%. If the error limit is not given, it is the same as the reject limit. A pulse that is shorter than the reject limit will not propagate to the output. A pulse that is longer than the reject limit, but shorter than the error limit will propagate as 1 'bX. A pulse that is longer than the error limit will propagate normally. A PATHPULSE$input$output specparam overrides the general PATHPULSE$ specparam in the same module, for delays from 'input' to 'output'. Co!>l"!lhl C> 1995-2006 by Doulos Lid. 231
  • 231. PATHPULSE$ Exam les p specify ( e l k => q) = 1 . 2 ; ( r s t -> q) - 0 . 8 ; specparam PATHPULSE$clk$q - ( 0 . 5 , 1 ) , PATHPULSE$ - ( 0 . 5 ) ; endspecify See Also Specify, Specparam 232 Copynght 0 1995-2006 by Doutos Ltd
  • 232. Port The ports of modules model the pins or edge connectors of hardware components. The ports of interfaces, programs, tasks, functions, properties, sequences, covergroups and randsequence productions are used to pass data between them. Task, function, property, sequence, covergroup and randsequence ports are also called arguments. Jlo> SystemVerilog adds a number of enhancements to ports, including interface ports, ref ports and open arrays, and the rules for what may be connected to ports { Module, interface. program ports l {one of) NetPort1'ype ] Name I Unpa ckedDimensions . . . [ [ Direction] Name [ Unpa ckedDimensions . . . 1, ], ... Da t a 1'ype ] [ [ D i rection] Name VariableDimension [ - Constan tl·:xp ression] , Name Variabl eDimens i on [ = Constan tExpression ] , [ 1 Direction] var D a L a 1'ypeOrimp l i c i t ] Name Va r i ableDimen s i on [ = Constan tExpression ] , Name VariablcDimcnsion [ - ConsLan LExpression] , I n t e r faceName [ . ModporLName] Name [ Unpa ckedDimensions . . . ], Name [ UnpackedDimensions . . . ] , i n l c r facc [ .ModportName] Name [ UnpackedDimensions . . . ] , Name [ UnpackedDimensions . . . ] , { generic interface l [ [ Direction] NcLPortType] . Name ( [ Expressi on ] ) , . . . [ [ Di rect .i on ] Data Type] [ [ Direction I var Da L a TypcOrimp l i c i t ] . Name ( l ExpL·ession J l , . . . .Name ( [ Expression ] ) , . . . { Task, function, property, sequence, covergroup and randsequence production ports/arguments) {one of) [ T£Dircc L i o n ] [var] DataTypeOrimp l i c i t [Name VariableDimension Name VariableDimension Direction = T£DirecLion {one of) [ = Express i on ] , [ = Express ion ] , . . . ] inout i nput output ref - { one of) Direction const ref Copy.-;ght C 1995·2000 by Doolos Ud 233
  • 233. Port Da ta 'l'ypeOrImplici t Data Type [ Signing] Ne tPorLType [ PackcdDimension ] = [ N e t 'l'ype] VariableDimension = Da taTypeOrimpl i c i t ( one of) UnpackcdDimension [DacaType] ( Open array) ( Associative array ) [• ] (Associative array with wildcard index ) [] [ $ [ : Cons t a n tExpressi on ] ] UnpackedDimension = (Queue) ( one of) [ Corls L an tExpress i on] [ Constan LExpression : Cons t an tExpression ] Pa ckedDimens.i on = [ Cons tan tExprcssion: Cons tan tExpressi on] See Module, Interface, Program, Function, Task, Sequence. Property, Covergroup, Randsequence Module, interface and program ports may be declared "ansi-style" in the port list at the start of the module, interface or program. Port and type declarations may be combined. Ports declared like this must not be declared in the module, interface or program. • For a "non-ansi" style port list, each port must be declared as an input, output, inout, ref or interface in the module, interface or program. The direction may not be omitted for these declarations. A port may be declared as an interface, an event, or a net or variable of any type, including an array, a structure or a union. The default port direction for the first port in a task or function port list is input. The subsequent ports inherit from the previous one, if they have no direction or type specified. Module, interface and program ports have a default direction of inout and a default type of wire. The default can be changed with the compiler directive default_nettype, • output ports declared without a data type are by default wires. With a data type they are by default variables of the specified type. • 234 A default value may be specified for each singular argument. Only input, inout and ref ports can specify defaults (not output ports). Copyright 0 199S.2006 by Ooulos Ltd
  • 234. Port • Generic interface ports can only be declared "ansi-style", using a list of port declarations. • In a task or function prototype, the port name may be omitted, unless the task or function has default arguments values, or arguments are to be connected by name, or additional unpacked dimensions are declared. Gotchasl The default port type can be changed using the 'default_nettype compiler directive. 'default_nettype none requires port types to be declared explicitly. If a port is declared ANSI-style, it must not be declared in the module itself - this would be a re-declaration. module I l legal reg V; (ouLput V ) ; I I output reg V is correct • Do not put ports in test fixture modules. • Use ref ports to pass large data values, such as arrays to a task or function. Exam les p module ( A , B, C , D) ; i nput II ; inout [ 7 : 0 1 B; output [ 3 : 0 ] C, D ; module FF8 ( input C l k , Reset, input reg [ 7 : 0 ) D, output reg [ 7 : 0 ] Q 8 ' b O ) ; 11 Declare and initialize reg typedef struct { bil A; union ( int i , real j I B; Structl; module Ml ( inpul int Jn, outpuL var Structl Out ) ; endmodule Copyright c 1995-2006 by Oou)os ltd 235
  • 235. Port Interface ports interface I n t e r f ( input C l k ) ; endinterface module ( T n Le rf I n t l , . . .) endmodule modu le ( i n terface T n t 2 , . . .) I I Generic interface endmodule See Also Instantiation, User Defined Primitive 236 Copynght 0 1995-2006 by Ooulos Lid
  • 236. Priority Used before if to indicate that a series of if-else-if conditions will be evaluated in the listed order, and before case to indicate that a case will act on the first match only. IJl> This f eature was added in SystemVerilog See If and Case If priority is used before an if, an explicit else must appear, otherwise a run-time warning is issued when a condition is not matched. A priority case acts on the first match only. If priority is used before a case, the simulator will issue a warning message if no case item matches. When using priority, there is no need to code a default case to trap unexpected case values. With nested if-else statements, priority affects all the lower-level If else statements and there is no need to repeat it in each branch. - Exam les p biL [ 1 : 0 ] S; priority i f ( S [ l : O ] =� 2 ' b0 1 ) S l a t e = Statel ; else if ( S [ l : O ] == 2 ' b l 0 ) S ta le = S l a t e 2 ; else State = Idle; II II Covers all other possible values, so no warning is issued priority case z ( S ) 2 ' b0 1 : Slalc = s tale!; 2 'bl0: State = S t a l e 2 ; defa u l t : S t a t e = Idle; endcase See Also Attributes, Case, If, Unique CopynghlC 1995-2006 by Doulos Lid 237
  • 237. Procedural Assignment Changes the value of variables, or schedules a change for the future. ( Blocking assignment } ( one of} VariablcLValue = 'l'imingCon Lrol Expression VariableLValue Assi gnOpcrator Expression DynamlcArrayVariableName - new [ Expression] VariablcName ArraySelecc = ClassNe•• ( ( Expression ) ] ( Nonblocking assignment } VariableLValue <= [ TimingConcrol] Expression; Assi gnOperacor = {one of} = +s -= * = / = %= & = ClassNew - I = A = <<= >>= <<<= >>>= {one of} ncw [ ( Argumen cs, . . . ) ] new [ ( . Name (Expression) , . . .)] 1 shallow copy 1 new Expression VariableLVa l ue = { one of} variableName VariableArray { VariableLValue, . . . } ' { VariablcLValue, . . . } Va riabl eArray = See Array See Statement Bit and part selects are not allowed for variables of type real and realtime. The expression on the right hand side is evaluated when the assignment statement is executed, but the left hand side is not updated until the timing control event or delay (called the "intra-assignment delay") has occurred. A blocking assignment does not complete until the left hand side has been updated (i.e. after the intra-assignment delay has elapsed). The next statement in a begin-end block is not executed until this happens. A fork­ join block does not complete until all the included blocking assignments have completed. 238 Copyrig/l! C 1995·2006 by Ooulos Lid
  • 238. Procedural Assignment • Events scheduled by nonblocking assignments do not take effect until after all blocking assignment events at the same simulation time have been processed. A <= #5 0 ; l = # 5 1 ; {A will be 0 at the end of time 5 J Variables may be assigned using a continuous assignment or driven from a single output port. Such variables may not be initialized nor assigned using a procedural assignment. Gotchasl A variable may be assigned in more than one initial or always. The value of the variable at any time is determined by the most recent event, irrespective of the source of the event. This is different from what happens with nets. A net may be driven from two or more different sources, the resulting value depending on the type of the net (wire, wand etc.) Use nonblocking assignments to infer flip-flops, and blocking assignments otherwise. This prevents races between clocked always's. It also makes the intention clear, and should help to avoid unwanted flip-flops. Use a simple intra-assignment delay to avoid RTL clock skew problems, in the case where a clock tree is modelled. Exam les p always @ ( Inputs) begin : CountOnes int ege r I ; f = 0; for ( I -0 ; I<S; T =T + l ) i f ( Inputs [ I ] l [ - [ + 1; end always @Swap fork II Swap the values of a and b II Completes after a delay of 5 a = H 5 b; b = #5 a; j oin always @ (posedge Clock) begin Copyr•;hl 0 1995-2006 by Doulos Lid. 239
  • 239. Procedural Assignment c <� b; b <� a ; I I Uses the 'old' value of 'b' end Delay a nonblocking assignment to overcome clock skew. always @ ( posedge Clock) Count <= #1 Count 1 1; Assert Reset for one clock period on the fifth negative edge of Clock. initial begin Resel repeat ( 5 ) @ ( ncgcdgc Clock) Reset - @ ( negedge Clock) 1; 0; end See Also Assign, Operators, Timing Control 240 Copynght C 1995-2006 by Ooulos ltd
  • 240. Process process is a built-in class (in the std package) that allows one process to access and control another process once it has started. (See Fork) II> This feature was added in SystemVeri/og { process class prototype ) class process; typede[ enum { FINISHED, RUNNING, 1'/AITING, SUSPENDED, KILLED) s t a t e ; s t a t i c [unct i on process sell ( ) ; [unction state status ( ) ; function void k i l l ( ) ; task await { ) ; function void suspend ( ) ; task resume ( ) ; e ndc l a s s Users cannot create objects of type process using new: these are created automatically when processes are spawned. Users can declare variables of type process and pass them through tasks or incorporate them into other objects. The process class cannot be extended. Methods • self() - returns a handle to the current process (i.e. the process making the call). • status() - returns the process status, as defined by the state enumeration: FINISHED: process terminated normally RUNNING: process is currently running (not in a blocking statement) WAITING: process is waiting in a blocking statement • SUSPENDED: process is stopped awaiting a resume KILLED: process was forcibly killed (via kill or disable) kill() - terminates the given process and all its sub-processes. • await() - allows one process to wait for the completion of another process. Copyrightc 1995·2006 by DouJo. ltd 241
  • 241. Process suspend() - allows a process to suspend either its own execution or that of another process. resume() - restarts a previously suspended process. • Exam les p initial beg in I I Declare a process variable process p ; Spawn a process fork begin II I I Obtain process's handle p - process : : sel f ( ) ; end j oin none II Nonblocking 11 If the process hasn't completed after 1 OOns, forcibly terminate it n 100ns i f (p ! end = process : : FINISHED) p . kill ( ) ; See Also Fork, Std:: 242 Copjnghl 0 t99S.2006 by Doulos Ltd
  • 242. Program The program block is a construct that can be instanced in the same way as a module. Programs are usually used for modelling a test environment. Program blocks facilitate correct initialisation and race-free synchronisation in testbenches and are compatible with clocked assertions and formal tools. They are often used together with clocking blocks. ..,. This feature was added in SystemVerilog ( one of} program [ Li [ e L i me] ProgramNamc [ # ( [ Parame terPortLis L ] J ] [ ( PortNameLi s L ) ] ; [ TimeUni L ] [ PorLDeclarations . . . ] Programi L cms . . . endprogram [ : ProgramNamc] program [ LifeLimc ] ProgramName [ # ( [ Paramc LcrPortLi s t ] ) ] !ANSI-style} [ ( Po r t s , . . . ) ] ; [ TimeUni t ] l'rograml Lams . . . cndprogram [ : ProgramName] program ProgramName ( . * } ; [ TimcUn i t ) ProgramiLcms . . . endprogram [ : ProgramNamc ] {extern program declarations } extern program [ L i fe t i me] ProgramName [ # ( [ Pa rameterPor LLi s t ) J ] [ ( PortNameJ.i s t ) ] ; exLern program [ L i fetime) ProgramName [ # ( [ Parame terPo z· t L i s t ) ] ] ( Po r t s , . . . ) ] ; ParameterPor tLisL = PortNamcLi s L = Programitem = See Parameter See Module {one of} Declara t i on 11ssign Initial Final Genera te GenerateCase Copynghl C 1995·2006 byDoulos lid 243
  • 243. Program Generateif GeneraLeLoop AsserL Assume Cover $unit inler face-<HERE>-endinterface package-< HERE>-endpackage module -< I!ERE>-endmodule program is a leaf in the hierarchy - it may not contain instances of other programs, nor of modules or interfaces. A • If an extern declaration exists for a program, it is possible to use : as the ports of the program. This is the same as placing the ports (and possibly parameters) of the extern declaration on the program. (See Module for an example.) Nested programs with no ports, or top-level programs that are not explicitly instantiated are implicitly instanced once. In this case, the instance name is the same as the program's name. • Local program variables can only be assigned using blocking assignments. Non-local variables can only be assigned using nonblocking assignments. Program statements sensitive to signals driven by the design are scheduled to execute in the reactive region, i.e. after the design has settled to its steady state. initial blocks from program blocks are also scheduled in the reactive region, as opposed to initial blocks in the design block, which are scheduled in the active region. Design signals driven from within a program must be assigned using non­ blocking assignments and are updated in the NBA region. This, together with the previous rule, ensures race-free behaviour between design and testbench. • tasks and functions declared in a program may not be called from a module. Programs are allowed to call tasks and functions declared in other programs and in modules. A program will finish when all its initial blocks have completed execution. Alternatively, $exit can be used to finish executing a program immediately ­ all the program's spawned processes will be terminated. However, any f inal blocks in the program will still be executed. When all programs exit, simulation finishes. 244 Copjrlgh!C 1995-2006 by Doolos Lid
  • 244. Program • Program variables may not be referenced from outside the program block. • Anonymous programs may be declared in a package or a compilation unit. They may only contain declarations of tasks, functions, classes, covergroups and constructors. The declarations in an anonymous program do not form a new scope and may only be used by program blocks. Use one or more programs in a testbench to generate the stimulus for the design and to check the response. Exam les p module design ( i nput clock, i nput [ 7 : 0 ] data, addr, output [ 7 : 0 ] Q ) ; II c . . . n dmodu l e module testbcnch; l og i c clock - 0 ; logic [ 7 : 0 ] data, addr, Q ; design DUT ( . *) ; LcsL LcsL _ i II ( . *) ; Simulation stops when the program finishes forever U l O clock - ! c lo ck; initial program t e s t ( i nput c l o c k , output logic [ 7 : 0 ] d a L a , addr, input [ 7 : OJ Q l ; c locki ng cb @ (posedge clock) default input #2ns output # 5 n s ; outpuL d a L a , addr ; i np u t Q ; endclocking initial begin c b . addr cb . data 8 ' h0 0 ; - 8 ' haa; II end Cop)Tighl Q 1995-2006 by Doutos Ltd. 245
  • 245. Program endprogram endmodule See Also Clocking, Instantiation, Port 246 COpyrighlc 1995-2006 by Ooulos Lid.
  • 246. Programming Language Interface The SystemVerilog Programming Language Interface (PLI) provides a means for users to call functions written in the C programming language from a SystemVerilog module. Such functions may dynamically access and modify data in an instantiated SystemVerilog data structure, and the PLI provides a library of C language functions to facilitate this. The PLI is invoked via user defined system tasks and functions, which the user writes to augment the built in system tasks and functions. Like the built in ones, user defined system tasks and functions have names that start with a $ character. A user defined system task or function hides a built in system task or function having the same name. The following are possible applications for the PLI: • Delay calculators Test vector readers Graphical waveform displays Source code debuggers • Interfacing models written in C or another language, such as VHDL, or a hardware modeller. ..,. SystemVerilog includes the following new features: Extensions to the Verilog Procedural Interface (VPI). A new Direct Programming Interface (DPI). which allows C functions to be called from SystemVerilog without using the PLI. The Assertion API. which enables C code to interact with SystemVerilog assertions. This can be used to create assertion debug and coverage tools. The Coverage API, which is used to provide coverage infonmation for third­ party tools. Statement, toggle, finite state machine and assertion coverage information is supported. Some information about the DPI is included in the articles on Export "DPI-C" and Import "DPI-C" and in the Direct Programming Interface (DPI) Tutorial, which can be found at http://www.doulos.com/knowhow/sysverilog/tutorial. A full discussion of the PLI, the DPI and the APis is outside the scope of this reference guide. Cop)'ightC I99S.2006 by Doulos ltd 247
  • 247. Property Defines an aspect of a design's behaviour. Properties often make use of sequences When used for verification, a property must be used with a concurrent assertion statement (assert, assume, or cover) or an expect statement to be evaluated and produce a result. � This feature was added in SystemVeritog property PropertyName [ ( [ Ports, . . . ] ) ] ; ( Va riableDeclara t i on s ] PropertySpec; endproperty [ : PropcrlyName ) PropertySpec ( Even LCon tro.l ] (disable i f f (Expression (dist 1 Distitems, . . . } ] ] [ n o L l PropertyExpr PropertyExpr - [ one of) ( PropertyE:xpr) not PropertyExpr PropertyExpr or PropertyExpr Proper LyExpr and PropertyExpr SequenceExpr SequenccExpr 1 - > ProperLyExpr 1 Overlapped implication ) SequenceExpr 1 => PropertyExpr ( Non-overlapped implicatio n ) i f ( Expressi on [ d i s t ( DisL items, . . . } ] ) PropertyExpr l else PropertyExpr ] PropertyName [ (Name ( - Actua lArgExpr] , . . .) 1 Even tCon trol PropertyExpr D i s t items - see Constraint EventExpression, Even tConcrol see Timing Control $u n i t moduJ e-<fiE:RE>-cndmod u l e generate-<HERE> -endgcncra te inte rface-<HERE>-endinterface program-<IIERE>-endprogram pac kage-<HERE>-endpackage clockj ng-<IIERE>-endclocking 248 Ccp)fighl0 199�2006 by Ooulos Ltd
  • 248. Property • A property may be declared with formal arguments that may later be replaced by a name, an expression, an event expression or upper range as $. • A property's arguments may be typed or untyped. Arguments are passed by reference. Exporting of local variables through typed formal arguments is not allowed. The disable iff clause allows pre-emptive resets to be specified. disable iff clauses cannot be nested. • The values of the variables in a disable iff are those in the current cycle, not the sampled ones. You can refer to a seuqence's .triggered method, but not to .matched and .ended. • The not clause negates the PropertyExpr. • The implication construct allows a user to monitor sequences based on satisfying some criteria. There are two forms of implication: overlapped, using operator 1 -> : if there is a match for the left-hand ("Antecedent") SequenceExpr, then the first element of the right-hand ("Consequent") PropertyExpr is evaluated on the same clock tick. non-overlapped, using operator 1 => : the first element of the "Consequent" PropertyExpr is evaluated on the next clock tick. • A degenerate sequence is one that can't be matched or that can only be matched by an empty sequence. Any sequence that is used as a property must be non-degenerate and must not admit any empty match (see Sequence). Any sequence that is used as the "Antecedent" of an overlapping implication (1->) must be non-degenerate. Any sequence that is used as the "Antecedent" of a non-overlapping implication (I=>) must admit at least one match. Such a sequence can admit only empty matches. The "Antecedent" SequenceExpr may be on one clock and the '"Consequent" PropertyExpr on another clock. The concatenation operator # # 1 synchronizes between the two clocks. Using sequence operators other than ##1 (e.g. ##2, ##0) is illegal. @ (posedge clk l ) S i g l # # 1 @ (posedge c l k 2 ) S i g 2 I I VVhen I1 Sig1 matches at clock clk1 , ##1 moves the time 1 1 to the nearest clock tick of clk2 after the match • Multi-clocked properties are not allowed to be defined within a clocking block. Copynght C> 1995·2006 by Doulos Ltd. 249
  • 249. Property Since 1 -> overlaps the end of its "Antecedent" with the beginning of its "Consequent", the clock for the end of the "Antecedent" must be the same as the clock for the beginning of the Consequent. E.g. for sO, s 1 , s2 sequences with no clocking events: @ (posedge clk2 J s2 @ (poscdge c l k 2 ) s2 • clkO) sO 1 -> @ (poscdge c l k l ) sl # i l @ (poscdge 11 Illegal c l kO) sO 1 - > @ (posedge clkO) sl ff # l @ ( po�cdge II Legal In multiply-clocked properties, when using If or if-else, the if and else clause properties must begin on the same clock as the test of the boolean condition. This is because the if/if-else operators overlap the test of the boolean condition with the beginning of the If clause property and the else clause property, if present. E.g. @ (posedgc c l k O ) i f (Cond) @ (posedge clkO) s l else @ (p6sedge c l k l ) s2 • is illegal because if and else clauses begin on different clocks A named property is recursive if its declaration involves an instantiation of itself. Recursive properties are allowed, with the following restrictions: The not operator cannot be applied to any property expression that instantiates a recursive property. • disable Iff cannot be used in the declaration of a recursive property. • If p is a recursive property, then, in the declaration of p, every instance of p must occur after a positive advance in time. For mutually recursive properties, all recursive instances must occur after positive advances in time. Property recursion provides a flexible framework for coding properties to serve as ongoing assumptions, checkers, or coverage monitors. Exam les p The following property states that when the sequence (a ##1 b) is matched, then the sequence (d ##1 e) must also match. The two sequences are evaluated starting at the same time. property P; (a H 1 1 b ) 1 -> ( d U l e ) ; endproperty Clock resolution: 250 Copyright C> 19!JS.2006 by Doolos ltd
  • 250. Property I I Clock inferred from procedural block a l ways @ (posedge e l k ) assert properly ( (a 1 12 b ) ) ; II Clock from clocking block c l ocking cbl @ ( posedge e l k ) ; property P l ; ( a ##2 b ) ; endproperly endclocking asserL property (cbl . Pl ) ; Multi-clock property examples: sequence s l ; @ (posedge c l k l ) a U l b ; II Single clock sequence endsequence sequence s 2 ; @ (posedgc cl k2) c H H 1 d; I I Single clock sequence cndsequence I I Multiple clock sequence sequence MulLSeq ; @ ( posedge c l k l ) e I l l @ (posedge c l k 2 ) sl I l l @ (posedge c l k 3 ) s 2 ; cndsequence properly p l ; Mul tSeq; endpropcrly I I Property with a named multiple-clock seq. property p2; I I Property with multiple-clock implication @ (poscdge c l k l ) a I H J @ (posedge clk2 ) s l I => @ (posedge c l k 3 ) s 2 ; endpropcrly properLy mul t_p6; I I Property with implication with named MulLSeq I -> Mu l tSeq ; endproperty I I Multi-clocked sequences I I a, b , cond, e are clocked o n posedge clk1 property p 3 ; @ (posedge c l k l ) a i H l b 1 - > i f (cond) ( 1 I = > @ (posedge c l k 2 ) d ) else e U l @ (posedge c l k 3 ) f ; endprope r t y Recursive properties properly RecPl ( p ) ; p and ( l ' bl I => RecPl ( p ) ) ; endproperly properLy RecP2; CopYflght 0 t99S.2006 by Ooulos Ltd. 251
  • 251. Property sl 1 -> (prop2 and ( l ' bl I => RecP3 ) ) ; endpropcrt y prope rty RccP3; 1 -> (prop3 and endproperL y s2 RecP2 and RecP3 are mutually recursive I => RecP2 ) ) ; I1 (1 'bl See Also Assert, Bind, Clocking, Cover, Sequence 252 Copyrighl co 199$-2006 by Doolos Lid
  • 252. Protected A protected member of a class is available only to methods inside the class (similar to local), but (unlike local ) it can be inherited and it is visible to subclasses. "" This feature was added in SystemVerilog c o n s l protec ted DataType C ons tName [ = Constan tExpression ] ; protected Declaration protected '/'as k protected Function extern protected 1'askProtoype extern protected FunctionProtoype See Class. It is an error to define a member of a class as both local and protected. Class properties can be further defined as const, and class methods can be defined as virtual. These qualifiers can appear only once per member. Examp les c l a s s BaseCla s s ; virtual protected fu nc ti o n inl AFunc (bit X) ; I I Prototype i n t B Fu n c ( i n t Y ) ; ex tern pro t e c t e d virtual function endclass class ExtendedC l a s s extends B a s e C l a s s ; protected function i n l AFunc ( b i l X) ; . . . I I Function body endfunction endclass See Also Class, Local Copyright c 1995-2006 by Doulos Ltd. 253
  • 253. Queue A queue is an ordered collection of elements of variable-size, analogous to a one-dimensional unpacked array that grows and shrinks automatically. A queue supports constant time access to all its elements, as well as constant time insertion and removal at the beginning or the end of the queue. II> This feature was added in SystemVerilog Da caTypc PackedDimens.ions QueueName ($ [ : Constan tExpression] ] PackediJi mcnsion = [Cons tan tExpressi on : Cons tan LExprcssion] ! Methods ) funclion int s i ze ( ) ; function void insert ( input inc Index, input Elemen c Type I cern) ; funclion function funclion funcLion function void delete ( i nput inl Index) ; Elcmen t Type pop_front: ( ) ; Elemen t 'l'ype pop_back ( ) ; void push_front ( input Element'l'ype ILem) ; void push_back ( inpul El emen t Type Item) ; • Queues are declared using the same syntax as unpacked arrays, but specifying $ as the array size. The maximum size of a queue can be limited by specifying its optional right bound. the Cons/an/Expression must evaluate to a positive integer value. • A queue declared with a right bound [ $ : N ] is limited to the indexes 0 through N (its maximum size will be N+1 ). An index that lies outside these limits is invalid. • Unlike arrays, the empty queue of some queue operations. ' { ) is a valid queue and may be the result Q [ a : b 1 yields a queue with b-a+ 1 elements. If a>b , then Q [ a : b 1 yields the empty queue Q [ n : n 1 === • ' ' I ). (Q [ n 1 ) If n<O or n>$ then Q [ n : n 1 yields the empty queue ' I}. If either a or b are 4-state expressions containing X or Z values, it yields the empty queue ' ( ) . Q [ a : b 1 where a< 0 is equivalent to Q [ o : b 1 . 254 Copyrighl C 1!!95·2006 by Doulos Lid.
  • 254. Queue • Q [a : b l where b> $ is equivalent to Q [ a : $ ] . • An invalid index value (i.e., a 4-stale expression with X's or Z's, or a value that lies outside 0. .. $) causes a read operation (e Q [ n ] ) to return the default initial value for the type of queue item (i.e. x for 4-stale type, 0 for 2state type, "" for string, null for class and event, first element for enum). = An invalid index causes a write operation to be ignored and a run-time warning to be issued. • Writing to Q [ $ + 1 ] is legal. Methods size() - returns the number of items in the queue. If the queue is empty, it returns 0. insert() - inserts the given item at the specified index position. • delete() - deletes the item at the specified index position. pop_front() - removes and returns the first element of the queue. pop_back() - removes and returns the last element of the queue. push_front() - inserts the given element at the front of the queue. push_back() - inserts the given element at the end of the queue. Gotchasl The SystemVerilog LRM contains examples where assignment patterns are not used for queues. Implementations may or may not decide to implement assignment patterns for queues. Exam les p int Q1 [ $ ] ; I I An empty queue of ints inl Q2 [ $ ] - ' 1 1 , 2 ) ; I I An initialised queue of ints bit Q3 [ $ : 7 ] ; I I A queue with max size = 8 bits int I l , T 2 ; 11 e Q2 � = = Q2 [ 0 ) ; Q2 [ $ ] ; 02 [ 0 : $-1 ) ; Q2 - Q2 [ 1 : $-l ) ; Q . delete ( i ) Ql = 02; Copyright C 1995·2006 by Doulos Ud II Read the first (left-most) item I 1 Read the last (right-most) item I I Delete the last (right-most) item I I Delete the first and last items II Equiv. to: Q = '{Q[O:i-1], Q[i+1 ,$]} II Copy Q2 in Q1 255
  • 255. Queue Q2 - ' { Q2 , 3 ) ; Q2 ' { Q2 [ 0 : i - 1 ] , j , Q2 [ i , $ J Q2 - ' { Q2 [ o : l J , j , Q2 [ i + 1 , S J e = Q . pop_front ( ) e - Q . pop back ( ) Q . pus h front { e ) II Insert 3 at the end } ; II Insert j at position i ); II Insert j after position i I I Equiv. to: e = Q[O]; Q = Q[1,$] I I Equiv. to: e = Q[$]; Q = Q[0,$-1] I I Equiv. to: Q = '{e, Q } See Also Array, Dynamic Array, Sid:: 256 COpy!lght 0 199:'>-2006 by Ooutos ltd
  • 256. Rand Enables a class member variable to be given a random value using the built-in randomize() method . (For rand join see Randsequence) ..,. This feature was added in SystemVerilog 1 one of) rand DataDeclaration randc Dataneclara tion { Methods) task rand mode (bit on_o f f ) funcllon int rand mode ( ) function voi d srandom (lnt seed) ; funcllon string get rands Lalc ( ) ; funct ion void seL_randstate ( string slale ) ; 1 Class methods J vi rlual function int randomi ze ( ) function voi d posl randomize ( ) function void prc_randomize ( ) { Scope randomize function 1 [ s t d : : I randomize ( [Va r i abl cNames , [ w l l h Con s t rain tBlock] . . . I ) [with Const rai n tBlock I ConstraintfJiock - See Constraint class-<HERE>-endc l ass The values of rand variables are uniformly distributed over their range. The values of ran de variables are random-cyclic - their values iterate in a pseudo-random sequence with the value repeated during the iteration. In a rand or randc array, all array elements are random. • The size of a dynamic array can be declared rand or randc. The array size constrained is declared using the size() method. An object handle can be declared rand (but not randc). All the object's var iables and constraints are solved concurrently. An unpacked structure may be declared rand, but not randc. Copyt;ghtCI 199S.2006 by Ooulos ltd 257
  • 257. Rand Members of unpacked structures containing a union and members of packed structures may not be declared rand. randc variables cannot be specified in solve-before constraints (See Constraint). [std::]randomize() allows the users to randomize variables in the current scope, without defining a class or instantiating a class object. In-line constraints may be applied using the options with. Methods Random values are assigned using the randomize() method. The with construct adds an anonymous constraint (See Constraint). When randomize() is called with no arguments, it assigns new values to all random variables in an object. When randomize() is called with arguments, those arguments become random variables within that object; all other variables in the object (including those defined using rand and randc) being considered state variables. randomize() cannot change a non­ random variable into a randc, and cannot change a ran de into rand. class A_C l a s s ; rand b i L ra , r b ; bit a, b; endc l ass A Class C - new; c . randomize ( ) ; c. random i ze ( r a , a ) ; 11 Random vars: ra, rb state vars: a, b Random vars: ra, a state vars: rb, b c. randomize ( a , b) ; II Random vars: a, b state vars: ra, rb II Random var: b state vars: a, ra, rb c . randornL�e ( b ) ; II randomize(nu/1) may be used to indicate that there are no random variables and all class members behave as state variables. In this case randomize may be used as a checker instead of a generator, i.e. to check all constraints and return 1 if all constraints are satisfied, and 0 otherwise. success = C . random i z e ( nu l l ) ; The functions pre_randomize() and post_randomize() are called implicitly just before and just after randomization respectively. The method rand _mode() called as a task returns the random generation of a variable on ( 1 ) or off(O). rand_mode() called as a function returns the variable's randomization mode. • 258 The srandom(seed) method initializes an object's random number generator using the value of the given seed. Copyright C> 1995-2006 by Doolen Lid
  • 258. Rand • The get_randstate() method returns a copy of the internal state of the random number generator associated with the given object. The returned value is a string of unspecified length and format. • The set_randstate() method sets the state of an object's random number generator, using a string returned by get_randstate(). Exam les p Random variables in classes class C ; rand b ) t a , b ; endclass C c = new; c . randomi�c ( ) ; Seeding class B; rand b i L a ; function new ( i n L seed) ; this . srandom (seed) ; end funcL ion en dclass B b = new ( 8 ) ; I I Create b with seed = 8 b . srandom ( 1 0 ) ; I I Re-seed b with seed 1 0 The scope randomize function ([std::]randomize) b) t a , b; bit OK; OK OK - I I Variables with module scope r a n domize (a, b) ; I I Make a,b random variables randomize ( a , b) with { a ! - b l ; Sea Also Sid::, Constraint, Randsequence. System Randomisation Functions Copy<;ght C 1ggs.2006 by Doolos Ltd 259
  • 259. Rand case randcase is a case statement that randomly selects one of its branches . ..,. This f eature was added in SyslemVerilog randcase F.'xprcssion Sta tement Expression Sta temen t endcase See Statement • The Expression is the branch weight. An item's weight divided by the sum of all weights gives the probability of taking that branch. The weight can be any expression, not just a constant and will be taken as an unsigned value. A branch with the weight 0, means that the branch is never taken. • Each call to rand case retrieves one random number in the range [0: SumOfWeights]. The weights are then selected in declaration order: smaller random numbers correspond to the first weight statements. Exam les p bit a, b; 1I randcase = a+b : X 5: X = ' h9 : X = 4 The weights are added using 4-bit precision 8; I I 1-bit precision 3; I I 3-bit precision 10; I I 4-bit precision I I The weight selection uses unsigned 4-bit comparison endcase See Also Rand, Randsequence 260 CopYfighl 0 1995-2006 by Oouloo Ltd.
  • 260. Randsequence randsequence is a random sequence generator. � This feature was added in SystemVerilog ra n dsequ en cc ( [ ProductionNamc ] ) [ DataType) Producti onNamc l ( Ports , . . . ) 1 [Data'l'ype ) ProduclionName l ( Ports, . . . ) ) Hulcs Rules e n ds equen ce Rule = Produ c L i onLi s t [ : = l·:xp rcssi on l CodeBlock ) ) ProductionLi st - { one ofl Prods . . . rand j o i n [ (Expression ) ) ProductionName [ (Argumen t s , . . . ) ] ProducLionName l ( Argumen t s , . . . ) ) CodeBlock Prod = { [ Da taDeclara tions . . . ) [ S t a temen t ) } [one of} ProducLionName [ (Argumen t s , . . . ) I = RsCode13lock Rs iLElse RsHepeat RsCase Rsfft:lse - i f ( Expression) P roduc l i on Name [ (Argumen t s , . . . ) I [ e l s e ProducLionName I (Argume n t s , . . . ) I J RsRepeat • repeal ( Expres s i on) ProducLionName I ( Arg11ments, . . .I ) RsCase case (Expression) Expressions, Expressions, ... ProductionName [ ( Arg umen t s , . . . ) 1 ProducLlonName I (Arg11men t s , . . . ) J defau l t I : J ProducLionName l ( Arguments, endcase Arg umen t • . . .)) { one of} [ Expression) . Por tName ( [ Expression l l See Statement Copyright 0 1995-2006 by Doutos Ltd 261
  • 261. Randsequence randsequence is composed of one or more productions. The optional RandName gives the name of the top-level production. If unspecified, the first production becomes the top-level production. A production contains a name, a colon and one ::>r more production lists, separated by 1 Production lists separated by a 1 imply a set of choices, . which the generator will make at random. • A production list is a list of production items, which are streamed in sequence. Production items are classified into terminals and nonterminals. A terminal is an indivisible item that needs no further definition than its associated code block. Eventually, a production list will be decomposed into terminals. • The : - operator assigns the weight specified by the Expression to its production list. The probability that a particular production list is generated is proportional to its weight. Unspecified weights default to • 1. A weight is meaningful only when assigned to a production list. Weight expressions are evaluated when their enclosing production is selected, thus allowing weights to change dynamically. • A production can be made conditionally using an if-else production statement (similar to the procedural if-else statement). A production can be selected from a set of alternatives using a case production statement (similar to the procedural case statement). The repeat production statement may be used to generate a production for a given number of times. The repeat expression must be integral and not be negative. • A break statement terminates the sequence generation - it forces a jump out of the randsequence block. • A return statement aborts the generation of the current production. Sequence generation continues with the production following the aborted production . • • A repeat production statement cannot be terminated prematurely (except by terminating the randsequence block using break). Data can be passed down to a production about to be generated. The syntax for passing data to a production is the same as a task call. • Generated productions can return data (void by default) to the nonterminals that triggered their generation. The name of the production can then be used as a value in the production list's code block. If the same production appears more than once, then a one-dimensional array that starts at 1 is implicitly declared. The rand join production control is used to randomly interleave two or more production sequences while maintaining the relative order of each sequence. The optional expression following the rand join must be a real 262 Copyri!Jhl C 1995-2006 by Doulos Ltd
  • 262. Randsequence number in the range 0.0 to 1 .0, representing the degree to which the length of the sequences to be interleaved affects the probability of selecting a sequence. A sequence's length is the number of productions not yet interleaved at a given time. If the expression is 0.0, the shortest sequences are given higher priority. If the expression is 1 .0, the longest sequences are given priority. The default value is 0.5, which does not prioritize any sequence length. Gotchasl There is not a semicolon where you might expect one in the if-else and case constructs; there is an (unexpected) semicolon after endcase! Exam les p The following example generates either ABC or ABD. The latter is twice as likely. randscqucnce A B 52; c I D 2; { $display ( "A" ) { Sd i spl a y ( " B " I c ( Sdisplay ( "C " ) ( $display ( " D" ) D endsequence Sl 52 A B I I Sequence starts here ; ; ; ; ) I ) ) randsequcncc (Top) Top : One Two Three Four; One : 5 1 1 I 5 1 2 ; 1 1 Sequence aborted after 521 i f i < 2 Two : 5 2 1 { i f ( i < 2 ) break; I 5 2 2 ; Three : case ( j ) : 531 1 1 I f j=O, 531 is generated 0 1' 2 : 532 1 1 I f j=1 or 2, 532 is generated 1 1 Otherwise, 533 is generated default : 533 cndcase ; II Repeat 54 a random no. of times in the range [1 :3), depending on the I I value returned by $urandom_range() Four : repeat ( $ urandom_range ( 1 , 3 ) ) S � ; Sll ( Sdisplay ( "S l l " ) ; } ; ( Sdisplay ( "S l 2 " ) ; } ; 512 521 ( i - - ; $dj spJay ( " S2 1 " ) ; } 522 ( i H ; $display ( "S22" ) ; } end sequence Cop)Tl!lhl 0 1995-2006 byOouto. Lid 263
  • 263. Randsequence Sequence interleaving randsequcnce ( Top ) Top Sl S2 rand j o i n Sl S 2 ; A B C D endsequence Generates, for example: A B C D, See Also Case, 264 If, Rand, Randcase, Repeat Cop)flght C 1995-2006 by Doulos Lt�
  • 264. Repeat Repeats one or more statements a specified number of times. The repeat production statement in a randsequence block is used to iterate over a production a specified number of times (see Randsequence). � Repeat in a randsequence was added in SyslemVerilog repeat ( Expression) SLa LcmcnL See Statement. The number of loop iterations is determined by the numerical value of the expression. If this is 0. X or Z, no loop iterations are made. Examp les i n i t ial begin Clock 0; repeat (MaxClockCycle5 ) = begin # 1 0 Clock 1; H l O Clock 0; end end repeal ( - 3 ) @ (EventExpress i o n ) I I Will not execute EventExpression See Also For, Forever, Timing Control, While Copyright C> 199�2006 by Ooutos Ltd 265
  • 265. Semaphore A semaphore is used to provide synchronisation, mutual exclusion and access to shared resources. semaphore is a built-in class that resides in the built-in std package. ..,.. This f eature was added in SystemVerilog { Declaration ) semaphore Name s , . . . ; { Methods ) function t a s k put task get function new ( i n l keyCounl - 0 ) ; ( int keyCount - 1 ) ; (int keyCount 1) ; i n l Lry_gcl ( in l kcyCounL - l ) ; = See Declaration and Statements • A semaphore is a bucket that is created with a fixed number of keys. Processes using the semaphore must first obtain one or more keys from the bucket, which is returned when the processes has finished. If there are insufficient keys, the process must wait until sufficient keys are returned to the bucket. Methods new() - creates a semaphore, which the specified number of keys. Note that additional keys can be created with put(). put() - returns the specified number of keys to the semaphore. put() may create keys, if more are returned than were originally obtained. put() causes processes that are waiting for keys to unblock. get() - obtains the specified number of keys. If the are insufficient keys in the bucket, the process blocks until sufficient keys are returned. try_get() - obtains keys if sufficient are available and returns 1 . Otherwise it returns 0; try_get() does not block. 266 CopjTlght 0 1995-2006 by Doulos Ltd.
  • 266. Semaphore Exam les p semaphore sm new ( 2 ) ; sm . get ( ) ; sm . pu t (2 ) ; II Create semaphore with 2 keys Get a key, or block if none available I I Return two keys II See Also Class. Mailbox, Std:: Copytight C 1995-2000 by Doulos Ltd. 267
  • 267. Sequence A sequence is a list of SystemVerilog boolean expressions in a linear order of increasing time, specified by clock ticks. The boolean expressions must be true at those specific clock ticks for the sequence to be true over time. Sequences are used in properties and in assert, assume, cover and expect statements . ..,.. This feature was added in SystemVerilog sequence SequenceName [ ( ( Ports, . . . l l I ; Variab 1eDeclarations . . . ScquenceExpr; endsequcncc [ : ScqucnccNamcl SequcnceExpr = ( one of) CyclcDclay SequcnccExpr [ CycleVel ay Sequencel·:xpr . . . ] SequenceExpr CycleDelay SequenceExpr [ CycleDelay . . . ] Express ion [ d i s L { Disti tems, . . . (Expression [dist { Dist items, . . . } ] { Repe t i tion] )I I , SequenceMa tchitems, . } ) I Repeti tionl SequenceName [ ( [ Argumen ts ] ) ] [ [ • ConstOrRangeExpressi on ] ] . . ( SequenceExpr [ , Sequen ceNa tclJitems, . . . I ) I ( * ConstOrRangeExpression] I SequenceExpr and Sequen ceExpr SequenceExpr intersect SequenceExpr SequenccExpr or ScqucnccExpr first_malch (ScquenceExpr [ , SequenceMa t chitems, . . ] ) [ d i st { Dist items, . . . } ] throughout . Expression SequenccExpr Sequcn ccExpr wilhin Scqven ceExpr Even LCon trol SequenceExpr CycleDelay = { one of) # JI In t egralNumbcr ##Name # # ( Constan tExprcssion) II [ConstRangc) SequenceMa t chiLcm - {one of} Opera torAssi gnmen t ++VariablelNalve --VariablcLVa l v c VariableLValue++ VariablcL Va l ue- ­ SubroutineCall Repeti ti on 268 - I one of) CopyrightC 1995-2006 by Doulos LtO.
  • 268. Sequence [ • con.s tOrRange] { Consecutive repetition ) [ ; cons tOrRange] { Non-consecu tive repetition} [-> Cons LOrRange] { Goto repetition} Argumen t s - { one of} Expressions, . . . . Name (Expression) , . . . ) Cons LOrRange = { one of) Constan LExprcssion Con s tRa nge ConstRange - {one of) Con s l a n L Expre s s i o n : Constan tExpression Cons tan tExpressi on : $ EventExpressi on , EventControl ; see Timing Control Distitems ; see Constraint OperatorAssi gnment - See Expression Va d ablel.Va 1 ue = see Procedural Assignment Subro u t ineCall ; see Task Enable { Sequence methods ) SequenceName . ended SequenceNa me . L r i gg c rcd Seque nceName . matched Sunil modu l e - < HERE>-e ndmodu l e generale-<HERE>-endgenerate i n te r face - < I IERE> - c ndi n Lcrface prog ram- <HERE> -e ndprogram package-<HERE>-endpackage c l oc ki ng - <I IERE> -cn dc lockin<J A sequence may be declared with formal arguments that may later be replaced by a name, an expression, an event expression or upper range as $. A sequence's arguments may be typed or untyped. Arguments are passed by reference. Exporting of local variables through typed formal arguments is not allowed. • Concatenation of two sequences, where each sequence can have a different clock, is allowed. CopyHght0 1995-2006 by Ooolos Ltd 269
  • 269. Sequence @ (posedge c l k l l 51 ii @ (posedge c l k 2 ) 52 1 1 Foreve� I I match of S1 at clk1 , ## moves the time to the first clock I I tick of clk2. From that first tick of clk2, S2 is matched. Syntactic cyclic dependency of the sequence names is not allowed. sequence sl ; @ (posedge clock) a #Jil s 2 ; I I s1 depends on s2 endsequence sequence s 2 ; @ (posedge c l ock) b U l s l ; II s2 depends on s1 ; illegal endsequencc A # # followed by a number specifies the delay as a number of cycles from the current cycle. The [ * N l notation indicates consecutive repetition of a sequence, i.e. the sequence is repeated exactly N times. [•N:M] means the sequence is repeated between N and M times. The $ token indicates the end of simulation. For example a # # 1 b [ * 1 : $ 1 # # 1 c means a clock tick where a is true, followed by one or more {unbounded) clock ticks where b is true, followed by a clock tick where c is true. • The goto repetition {indicated by [ ->N l ) and non-consecutive repetition {indicated by r =N 1 ) mean the non-consecutive exact repetition of an expression (not a sequence). i.e. the expression is true N times, not necessarily consecutively. The difference between goto and non­ consecutive repetition is best illustrated by an example: a [ -> 2 ] # # 1 b means any number of clock ticks, on exactly one of which a is true, followed by a being true in the next clock tick and b in the one following that. a [=21 # Ul b means any number of clock ticks, on exactly two of which a is true, followed by b being true in the next clock tick. In other words, there may be one or more clock ticks after the second occurrence of a, in which neither a nor b is true. The occurrence of the end point can be tested in any sequence expression when the clocks of the source and destination sequences are the same, by using the method ended. Its result is true or false. The method has no bearing on the starting point of the sequence expression. • 270 When the clocks of the source and destination sequences are different, the occurrence of the end point can be tested in sequence expressions by using the method matched. Its result is true or false. matched uses synchronisation between the two clocks, by storing the result of the source sequence match until the arrival of the first destination clock tick after the Copyright C I995-2006 by Ooulos ltd.
  • 270. Sequence match. matched tests whether the source sequence has reached the end point at that particular point in time. The result of matched does not depend on the starting point of the source sequence. • Like ended, matched can be used on sequences that have formal arguments. sequence S 1 ( a , b ) ; @ { posedge c l k 1 ) a # # 1 b; endsequence sequence S 2 ; @ ( posedge c l k 2 ) c # U S 1 ( x , y ) . matched [ -> 1 ] ##1 d; I I S 1 (x, y) is tested to occur sometime after c endsequence The triggered sequence method evaluates to true if the given sequence has reached its end point at that particular point in time (in the current time­ step), and false otherwise. • The dynamic creation of a variable and its assignment is achieved by using the local variable declaration in a sequence declaration and making an assignment in the sequence. The local variables declared in one sequence are not visible in the sequence where it gets instantiated. The following rules apply to a sequence specified in a clocking block: Event control of the clocking block is the clock of the sequence. No explicit event control is allowed in the sequence declaration. If a named sequence that is defined outside the clocking block is used, its clock must be identical to the clocking block's clock. To access a local variable of a sub-sequence, a local variable must be declared as a formal argument of the sub-sequence. • The binary operator and is used when both operand sequences are expected to succeed, but the end times of the operand sequences can be different. The end time of the and operation is the end time of the sequence that terminates last. The binary operator intersect is used when both operand sequences are expected to succeed, and the end times of the operand sequences must be the same. The throughout construct is an abbreviation for writing: { Expression) [ " 0 : $ ] intersect SequenceExpr The within construct is an abbreviation for writing: {1 [*0 : $] ##1 Sequen ceExprl ##1 1 [ '0:$] ) i n tersect Scquen ccExpr2 Copyright C 1995-2006 by Dootos ltd. 271
  • 271. Sequence • The operator or is used when at least one of the two operand sequences is expected to match. The sequence matches whenever at least one of the operands is evaluated to true. The first_match operator matches only the first match of possibly multiple matches for an evaluation attempt of its operand sequence. This allows all subsequent matches to be discarded from consideration. • Tasks, task methods, void functions, void function methods, and system tasks can be called at the end of successful match of a sequence. The subroutine calls are said to be attached to the sequence. All attached subroutine calls are executed at every successful match of the sequence, in the order they appear in the list. • Each argument of a subroutine call attached to a sequence must either be passed by value as an input or be passed by reference (either ref or const ref). • Local variables may also be passed into attached subroutine calls. If so, it must be passed by value. Clock Flow • Clock flow provides that in a multiply-clocked sequence or property the scope of a clocking event flows left-to-right across linear operators (e.g., repetition, concatenation, negation, implication) and distributes to the operands of branching operators (e.g., conjunction, disjunction, intersection, if-else) until it is replaced by a new clocking event. Therefore, it reduces the number of places at which the same clocking event must be specified. @ (c) X I => @ ( c ) y H#1 @ (d) z is equiv. to: @ (c) x I => y H # l @ ( d ) z II clock event c flows across => Clock flow makes the adjointness relationships between concatenation and implication clean for multiply-clocked properties. @ (c ) x U l y I => @ ( d ) z is equiv. to: @ (c ) x I => y I => @ (d ) z The scope of a clocking event flows into parenthesized sub-expressions and, if the sub-expression is a sequence, also flows left-to-right across the parenthesized sub-expression. However, the scope of a clocking event does not flow out of its enclosing parentheses. @ ( c) v 1 -> (14 # B t @ ( d ) x) a nd (y I H l z ) II v, w, y, z are I I clocked at c and 272 x is clocked at d Copynght C t99S.2006 by OO<Jios Ltd.
  • 272. Sequence Se uence o eratorp q p recedence , ( fo r assignment) - highest precedence [ . [ = [-> ## throughoul within j nlcrsecl and - lowest precedence or The execution of procedural code can be delayed until a sequence termination status is true by using the level-sensitive wait statement in conjunction with the triggered method. sequence S 1 ; endsequence program Test; i n .i tia l begin wait ( S 1 . tri ggered) ; II Waits for the end point (success) of 81 end endprogram Exam les p a II#N b; I I a must be true on the current clock tick, and b on the Nth I I clock tick after a is true a # # [ 2 : 5 1 b I I a must be true on the current clock tick, and b must be true II on some clock tick between 2 and 5 after a is true sequence s 1 ; a ##1 b; endsequence sequence s 2 ; @ ( p o scdgc clk2 ) I I Reference s1 in s2. s1 starts one clock cycle after the occurrence I I of d in sequence s2 c # # 1 d # # 1 s1 # # 1 f ; I I Equivalent to c ##1 d ##1 a ##1 b ##1 f; I I Use ended method in s2. Now s1 must end successfully one clock tick I I after d c # # 1 d # # 1 s l . ended # # 1 f ; Copyright C 1995-2006 by Doutos Ltd 273
  • 273. Sequence endsequence Repetition in sequences: I I Consecutive repetition a # # 1 b I l l b i i l b fi # l c ; I I Equivalent to: a il ll l b [ ' 3 ) a Ul c; I I Equiv. to a ##1 a ##1 a [ •3 I ; (a [ • 0 : 2 ] ##l b H i l c) ; I I Equivalent to: (b # il l c) or (a # # 1 b # # 1 c) or (a # # 1 a # # 1 b # # 1 c ) ; Goto repetition II a # # 1 b [ ->1 : 9 J fi #1 c I I a followed by at most 9 occurrences of b, followed by c II I I Non-consecutive repetition a ##l b [ =1 : 9 ) ##1 c Equivalent to: II a #ill ( ( ! b [ ' 0 : $) Ul b ) ) [*1: 9)) ##1 !b[•O:$) HJ c Using sequence binary operators: I I Using first_match sequcnc.:e :> 1 ; (a # # [ 1 : 2) b) or (c 8# [ 2 : 4 ] d) ; endscquencc sequence s 2 ; fi rs t_maL ch ( s 1 ) ; 1 1 s2 results in the earlier match from one of the following: I I a ##1 b I I a ##2 b I I c # # 2 d I I Ending a t the same time with previous. If both match, II first_match results i n two sequences I I c lili 3 d I I c Bi4 d end sequence Dynamic creation of a variable and its assignment: sequence SubSeq ( lv ) ; a H1 ! a, I I Declare lv as formal argument ! c • I 0 : $ I H 1 c & & (d 1vl ; 1 v - b II # 1 == endsequence sequence Seq ; int Var; c NH 1 SubSeq ( Va r ) ## 1 (a Var) ; II Var is bound to lv cndsequence 274 Copyright C t99S.2006 by DoulcS Ltd.
  • 274. Sequence Clock flow property P ; @ (poscdge e l k ) x ##1 y I => if (Z) j 1 => @ (posedge c l k l ) else k; I I k is clocked at posedge clk1 y, z, j, m are clocked at posedge elk n is clocked at posedge clk2 I I x, m 1 => @ ( posedge c 1 k?. ) n; I I endpropc r t y Multi-clock sequences: sequence s 1 ; II Single clock sequence II a ##1 b; @ ( poscdgc clk1 ) Multiple clock sequence endsequence sequence s 2 ; @ ( posedge c l k 2 ) c # # 1 d # # @ (posedge c l k 1 ) s1; endsequence II Source sequence s 1 evaluated on clk1; Destination II sequence s 3 ; sequence s3 is evaluated at clk3 @ ( posedge c l k 3 ) g # # 1 h # # 1 s 1 . matched [ -> 1 ] ##1 k; endsequence See Also Assert, Bind, Clocking, Cover, Property Copy<ight C 1995-2000 by Ooutos Ltd. 275
  • 275. Specify A specify block is used to describe path delays from a module's Inputs to its outputs, and timing constraints such as setup and hold times. A specify block allows the timing of a design to be described separately from the behaviour or structure of a design. speci fy Specif ir:: em s . . . y cndspec i fy Speci fyiLcm = ) one of) Specparam Pa thDcclara tion Sys tem'/'i m i ngC!Jecks PulseS r::yleDeclaration Shot1CancelledDeclara tion see Timing Checks - {one of} System'l'i mi ngchecks Pa tlJDeclara tion � S i mplcPath = PatlJDelay; EdgeSensi ti vePa th = Pa thDelay; Sta tcDependentPath = PathDelay; SimplePa t h = ( Inpu t , . . . ( Input {one of} [ Polarity] [ Polarity] EdgeSensi ti vePa th ' > Our::put , . . . J {Full) ( Parallel ) => Output) { one of} = * > Output, . . . ( { Edge) Inp u t , . . . ( [ Edge] Inpu t => Output [ Polarity) : Expression) [ Polarity] : Expression) ( one of) i f ( Expression) Simpl ePa t h " Pa thDelay ; S t a teDcpcndentPath if (Expression) = EdgeSensi ti vePa tll = Pa thDelay; i fnone SimplePa th - Pa thDelay; Pul seStyleDecla r a t i on = ( one of) pulsestyle_onevent Output, . . . pulscstyle_ondclc cl Output, . . . ; • (one of) showcancelled Output , . . . ; noshowcancelled Output, . . . ; S!Jo•�Cancel l edDecl a ra t i on Inp u t = ( one of} I npu tName I nputName [Cons ta ntExpression] InputName [Con s t a n t Expression : Cons t a n t Expressi on ] InOuLNamc 276 C<>pyrlght 0 1995·2006 by Doulos Ltd
  • 276. Specify I nOutNamc [ Cons L an tExpression ] InOutName [ Cons ta ntExprcss i on : Con s Lan L Exprcssion ] Output = (one of} OuLpu tName OulputName [Constan tExpression] OutputName [Constan tExpres s i o n : Constan tExpres s i o n ] I nOutNamc InOutName [Constan tExpress i o n ] I nOu tName [ Cons t a n t Express i on : ConstantExpressi on ] (one of} posedge (one of} + PaLhDclay - {one ofJ Edge = negedge Pol a ri ty = Li s t OfPa thDel ays ( L i s tOfPathDelays) L i s t OfPa thDelays = (one of} L { Rise,Fa U } { Rise,FaU,Turn-Off} t, t t' t ' t t, t , t , t , t, t t I 01,1 O,OZ,Z1 ,1 Z,ZO l t, t , t, t , t, t, t , t, t, t, t, t { 01 ,1 0,0Z,Z1 , 1 Z,ZO, OX,X1 ,1X,XO,XZ.ZX l = Min TypMaxExpression module-<HERE>-endmodulc Paths must have only one driver inside the module. • The module path source may be an input or an in out port, while the module path destination may be an output or an inout port. • The timing checks are relative to the module inputs. The specify block refers to the module ports as terminal descriptors. A ref port cannot be used as a terminal in a specify block. When one of the port instances is an interface, each signal in the interface becomes an available terminal, with the default direction as defined for an interface, or as restricted by a modport. in lcrface I n l f ; bit 1 7 : 0] In, Cowioht c 1995·2006 by Dooto. Ltd Out; 277
  • 277. Specify modport MP ( i nput [ 7 : 0 ] I n , output ( 7 : 0 ] OuL ) ; endinLerface module M ( I nt f . MP An Tnlcrf) ; specify ( I n + => Out) endspeci fy cndmodulc 3, �' 5; • Full (•>) or parallel (=>) connections may be described in a path declaration. A full connection indicates all possible paths from the inputs to the outputs. A parallel connection indicates paths from the bits of one named input to the corresponding bits of one named output. • The optional polarity in module paths indicates whether a path is inverting (positive polarity) or not inverting (negative polarity); it does not affect simulation, but may be used by other tools such as timing verifiers. • The data expression in edge sensitive paths likewise does not affect simulation. If a vector port is specified as the Input, the edge transition will be detected on the LSBit. If the edge transition is not specified, the path is considered active on any transition at the Input. • State dependent path delay (SDPD) expressions may reference only ports, constants and locally defined variables or nets. A limited set of operators is valid in SDPD expressions: bitwise ( - & I A A_ -A ), logical and equality ( == I= && II ! ), reduction ( & I A -& -1 A_ -A ) concatenation, replication and conditional ( {} {{}} ?: ). The path delays only affect the paths if the conditional expression is true. ( 1 , X and Z are all considered true in SDPD expressions.) , • ifnone defines the default SDPD if no if conditions are true. It is illegal to have both an lfnone SDPD and a simple path delay for the same path. • Unconditional paths take precedence over SDPD paths. Edge sensitive SDPD path declarations for the same path must be unique, with either a different condition, or a different edge (or both). The output must be referenced in the same way (entire port, bit select or part select) in each declaration. • If a module contains both specify delays and distributed delays (on gate and UDP instances and nets), the largest is used for each path. Showcancelled behaviour may be enabled in two different ways: globally, through use of the showcancelled and noshowcancelled invocation options, or locally, through use of specify block showcancelled declarations. The showcancelled invocation options take precedence over the showcancelled specify block declarations. 278 Copyright0 199S.2006 by Doulos Ltd
  • 278. Specify • I t is an error if a module path output appears in a pulse style declaration, or in a showcancelled declaration, after it has already appeared in a module path declaration. The pulse style invocation options take precedence over pulse style specify block declarations. Gotchasl The list of 1 2 delays for a path is not supported by all implementations. • The rules for path destinations are more flexible than many implementations currently support. • Use specify blocks to describe delays of cells in a library. Bear in mind how delays will be calculated when modelling libraries. A PLI based delay calculator will need to access the information in the specify blocks of all the cells of a design. Use specify blocks to describe the timing of 'black box' components in conjunction with a timing verification or synthesis tool which supports specify blocks. Exam les p module M ( F , G , Q, Qb, W, A , B, 0, V, C l k , RsL , X, Z ) ; input A, B , D, C l k , Rsl, X ; input [ 7 : 0 1 V ; oulpul F , G , Q , Qb, 7. ; ouLpuL [ 7 : O J �I; reg C; II Functional Descr iption . speci f y spccpdram TLII$Clk$Q . . 3, THL$Clk$Q �. - 4, TLH$Clk$Qb TIIL$Cl k$Qb S, Tsetup$Clk$0 - 2 . 0 , Thold$C l k$D 1.0; II Simple path, full connection II Simple path, parallel connection, positive polarity ( V + -> W) - 3 , 4 , 5 ; (A, B ' > F) � Copyright c 199$-2006 by Doolos Ltd. (1 . 2 : 2 . 3 : 3 . 1 , 1 .� :2 .0:3.2) ; 279
  • 279. Specify II Edge-sensitive paths, with polarity (posedge Clk •> Q + : D) = (TLH$Clk$Q, THL$Clk$Q) ; (posedge C l k *> Qb - : D) - (TLH$Cl k$Qb, 1'Hl.$Cl kSQb) ; II State dependent paths i f (C) (X * > Z ) = 5 ; i f ( ! C & & V �- 8 h f f ) ' (X • > 7. ) - 4 ; I I Default SDPD, X to Z Timing checks Sseluphold (poscdge C l k , D, Tsetup$Clk$D, Thold$ClkSD, Err) ; endspecity i!none ( X * > Z ) - 6 ; II cndmodule Pulse-Style and showcancelled speci fy showcancclled Ou t l , Ou l 2 ; pul sescyle ondetecc Ou tl , Oul2; ( A -> Oul l ) = ( 2 , 3 ) ; (D => Outl ) - ( 3 , 4 ) ; ( B -> Out2 ) = ( 3 , 4 ) ; ( B => Out2) � ( 5 , 6 ) ; endspecify See Also PATHPULSE$, Specparam, $setup 280 Copyrlgl1 0 1995-2006 by Dooloo LIO.
  • 280. Specparam Special type of parameter intended only for providing timing and delay values. It may appear in any expression that is not assigned to a parameter and is not part of the range specification of a declaration. Permitted in both specify blocks and in the main module body, but not in interfaces or programs. spccparam [ Pa cked/Ji mens ion J Name ; Con s tantMinTypMaxExpression, Name - Cons LantMinTypMaxExp1·ession, I PulseControJSpecparam] , Pul seCon trolSpecparam 1 one of} PATHPULSE$ - (Limi L [ , Limi t ] ) ; PATIIPULSE$Input$0utput 1 In specify blocks} = 1 (Reject, Error) J ( Limi L [ , Li m i t ] ) ; Limi t � ConstanLMinTypMaxExpression PackedDimension - [Constan tExpress i on : ConsLan LExpression] Sun i l specify-<HERE>-cndspccify interfacc-<HERE>-end i nte r face program-<IIERE>-cndprogram package-<HERE>-endpackage modu le-<IIERE>-cndmodule • Constant expressions in specify blocks may use numbers and specparams, but not parameters. Specparams may not be overridden using defparam, or using # in module instantiations. They can be modified using the Programming Language Interface (PLI) or through SDF annotation. A specparam declared outside a specify block must be declared before it is referenced. By default, specparams are as wide as necessary to contain the value of the constant, except when a Range specification is present. • A • specparams default to type logic of arbitrary size. specparam is calculated at elaboration time, but it may be modified by the PLI, and so it cannot be used to set parameters or localparams. Copyrlghl C> 1995-2006 by Douto. Lid 281
  • 281. Specparam Use specparams rather than literal numbers in specify blocks. Adopt a naming convention for specparams, so that they can be modified, if necessary, by a delay calculator which uses the PLI. Exam les p specify 1 . 0, specparam L R i s e S a S f tfal l $ a $ f - 1.0, LRiscSoSL � 1 . 0 , t�all$b$f - 1 . 0 ; ( LRisc$a$ f , ( a * > [} (b •> f) • LFall$a$ f ) ; ( t R i seSbSf, tF'a l l $ b $ f ) ; endspecify module (input 11, 12, output 0 1 ) ; specparam Spec - 1 . 0 ; parameter P a r ; endmodule Sea Also Module, PATHPULSE$, Specify 282 Cop)11<Jhl C 1995·2006 by Douioo Ltd.
  • 282. Statement The behaviour of a block of hardware can be described using statements. Statements execute at times defined by timing controls (delays , event controls and waits). Whenever two or more statements are required together they must be enclosed in begin-end or fork-join blocks. In a begin-end block, statements are executed in sequence; in a fork-join block they are executed in parallel. Statements in one initial or always are executed concurrently with those in any other initial or always. II!- Several new statement types were added in SystemVerilog {one of ) { Null statement 1 [ BlockName : } 1'imingCon trol S t a t ement [ B l ockName : ] Begin I B l ockName : ] 1 Statement may be null} Fork [ Bloc kName : ] Procedura lAssignmen t [ BlockName : J As s i gn I B l ockName : ] Force { Procedural continuous assignment 1 [l3loc kNarne : l If IBlockNamc : ] Case !Ill ockNi.lrnc : I IncOrVecExprc��ion I BlockName : ] 1'askEnable [ Bloc kName : ] FuncLi onCall { including methods and system tasks 1 {void function or cast to void 1 [ B l oc kNamc : J JumpSta temenL I Bloc kNamc : ] Assert 1 Procedural or concurrent 1 [BlockName : ] Assume [ B l.ockName : I Cover I BlockNamc : ] Expect [BlockName : ] Do-Wh i l e [AlockName : ] For I Bloc kName : ] Forcac!J [ B l o c kName : ] Forever I Bl ockNamc : ] Repeat [BlockName : ] Whi l e I B l ockNarne : ] Disable [ n l o c kName : ] -» [BlockName : ] 1 Event trigger} -> EvenLName; l BlockName : ] Wai t [ TimingControl I I B lo ckName : ] RandCase (Bloc kName : ] { Nonblocking trigger) ClockingDrive [Bl ockNamc : ] EventName; Randscqucnce Copyooght C 199�2006 by Doulos Ltd 283
  • 283. Statement IncOrDecExpression " (one of} ++VariableLValue; -- Va ri abl eDVal ue; Va riableLVa l ue++ ; Vari ab l e T.Va l ue- - ; Va ri ableLVal ue = see Procedural Assignment i n ) t i.al -<HERE> always-<HERE> bcgin-<HERE>-end fork- < IIERE>-j o i n generate-<HERE>-endgcncrale Lask-<HERE>-endlask ( Null allowed ) funct ion-<IIERE>-endfunction i f ( ) - <IIERE>- e l s e-<HERE> case-labe l : -<HERE>-endcasc (Null allowed 1 (Null allowed ) for ( < IIERE>) - < I IERE> forever-<HERE> repca l ( ) -<IIERE> do-<HERE>-wh i l e ( ) whil e ( ) -<IIERE> • A block name may be specified before ANY statement, followed by a colon, to help identify a single statement. A statement label does not create a hierarchy scope. • A statement with a label can be disabled using a disable statement. Disabling a statement has the same behaviour as disabling a named block. • Any statement may be prefixed by one or more Attributes. Exam les p Labe J A : Statement Labe l D : begin end 284 Cop)11ght C> 1995-2006 by Ooulos Ltd.
  • 284. Statement Sea Also Attributes, Timing Control Copjfighl c 199>2006 by Ooulos Lid 285
  • 285. Static The keyword static is used in two ways in SystemVerilog. Outside classes, it specifies the lifetime for variables. Inside a class, it specifies how class properties and methods may be accessed. .,.. This feature was added in SystemVerilog s t a t i c DataType VarNames, . . . , s la l i c constraint ConstrainLName; [ static ] task [ Li fetime) Tas kName [ . . . ) ; [ s tatic) function [ LifeLimc) FunctionName [ . . module [ Lifclime ) Modul eName [ . . I ; program [Lifetime] ProgramName [ . . . ] ; interface [LifcLimeJ rnterfaceName [ . . . ) ; c l a s s [ L i fetime) ClassName [ ]; . 1; . . Lifetime = . . {oneof} stat i c automatic • When applied to a variable, static means that the storage is allocated on instantiation of that variable and never de-allocated, as opposed to automatic. So, for example, an automatic var iable in a task or function is created when the task or function is entered and destroyed when it is left, whereas a static variable retains its value from one task or function call to the next. • A static task or function (i.e. a task or function with a static lifetime, specified after the word task or function) is one in which the local variables are, by default, static. static tasks and functions may not have ref arguments. A static class, module, interface or program is one in which the tasks and functions are, by default, static. static constants are calculated after elaboration. Global constants in a class are usually declared as static, because they are the same for all instances of the class. The default lifetime of a task or function declared outside a class is static. By default, class methods have automatic lifetime for their arguments and variables. Class properties that are declared static are class-wide: every object of the class sees the same property. 286 COp)'light c 1995-2006 by Ooulos ltd
  • 286. Static • The class scope resolution operator : : applies to all static elements of a class (e.g. static properties, static methods, typedef, enum, struct, union, nested class declarations). A static method of a class has no access to non-static members, but it can directly access static class properties or call static methods of the same class. static methods cannot be virtual. Gotchasl A static method is different from a method with static lifetime in that the former refers to the lifetime of the method within the class, while the latter refers to the lifetime of the arguments and variables within the method. c l a s s AClass; sta t i c STask ( ) ; end t a s k II task static Task ( ) ; I1 Static class method with automatic variable lifetime Non-static class method with static variable lifetime end t a s k I I 1I cndclass By default, class methods have automatic lifetime for their arguments and variables. This differs from tasks and functions that are not class methods. See Also Class, Cons!, Constraint, Function, Operators, Task, Variable Copyrighl c 1995-2006 by Dooloo Lid 287
  • 287. Std : : SystemVerilog provides a built-in package that contains system types (e.g., classes), variables, tasks and functions. The declarations in the built-in package are directly available (without using the std:: prefix) in any other scope (like system tasks and functions) unless they are redefined by user code . .,.. The built-in package std was introduced in SystemVeri/og Contents class mailbox class process funcLion int randomize ( . . . ) class semaphore • The package name std followed by the scope resolution operator :: can be used to unambiguously access names in the built-in package. Users cannot insert additional declarations into the built-in package. A scope randomization function called randomize() is defined in the built-in package, to generate random values (see Rand). See Also Mailbox, Process, Rand, Semaphore 288 Copynght c 1995.2006 by Doulos ltd
  • 288. Strength In addition to a logic value, nets also have strength values, to allow more accurate modelling. The strength of a net is derived dynamically from the strength(s) of the net's driver(s). Strengths are used extensively in switch level simulation, and when multiple drivers on a net are driving conflicting values. 1 one of) ( StrengthO, Strengthl) ( S t rcng t h l , StrengthO) ( S t rength./ ) ( Pulldown primitives only 1 1 Pull up primitives only 1 ( ChargeStrength) tTrireg nets only} ( St rengLIJO) StrengthO - { one of} supplyO strongO pul l O weakO highzO Strengthl = [one of} supply! stronql pu l l l wcakl highzl ChargeSLrength � {one of} large medium sma l l See Net, Instantiation and Continuous Assignment. The StrengthO and Strength1 keywords specify the strength of net drivers when they are driving the values 0 and 1 respectively. The strength specifications (highzO,highz1) and (highz1 ,highzO) are not allowed. highzO and highz1 are not allowed in strength specifications for pullup and pulldown gates. The default strength is (strongO, strong1 ) except for the following: , • pull up and pulldown gates. where the default is (pull1) and (pullO) respectively. • trireg nels, where the default is (medium). supplyO and supply1 nets, which always have strength supply. • The strength of a net during simulation is derived from the strength of the dominant driver on that net (i.e. the instance or continuous assignment with the strongest value). If a net is not being driven, it has a high impedance value, except as follows: triO and tri1 nets have the values 0 and 1 respectively, and pull strength. Copyr;ghl 0 199>2006 by Doulos Ltd 289
  • 289. Strength trireg nets keep their last driven value. supplyO and supply1 nets have the values 0 and 1 respectively, and supply strength. • The strength values have a "pecking order" ranging from supply (the strongest) to highz (the weakest). The relative position of two strength values is used when resolving the logic value and strength of a net, when there are conflicting drivers. supply strong pull large weak medium small highz The nmos, pmos and cmos switches shall pass the strength from the data input to the output, except that a supply strength is reduced to a strong strength. • The tran, tranifO and tranif1 switches shall not affect signal strength across the bi-directional terminals, except that a supply strength is reduced to a strong strength. Strength values may be displayed using the format specifier o/ov in $display, $monitor etc. Exam les p a + b; assign ( weakl , weakO) f trireg ( large) c l , c2 ; and (strong l , weakO) u l ( x , y , z ) ; a See Also $display 290 Copynght C 199�2006 by Ooulos Ltd.
  • 290. String String is a built-in data type. A string is an ordered collection of characters. A number of methods are provided to work with strings. tn addition, comparison and concatenation operators can be used with strings. ..,.. This feature was added in SystemVerilog See Variable ( Methods ] function int len ( ) task putc ( i nt i , stri ng s ) task putc ( i n t i , byte c ) function byte getc ( int i ) function string toupper ( ) function string tolowe r ( ) function int comparc ( string s ) function inL icompare (sLring s ) function i n t substr ( i n t i , i n t j ) function integer atoi ( ) function integer atohex ( ) function i nteger atooc t ( ) function integer atobi n ( ) function real atoreal ( ) task itoa ( i ntegcr i ) task hextoa ( i nteqer i ) task octtoa ( intcgcr i ) task bintoa ( i ntegc r i ) task realtoa ( re a l r ) The default initial value o f a string is "" (the empty string). strings may not conatin the character 0. If another string or a string literal is assigned to a string variable, the variable expands or shrinks to accommodate the value. All 0 values in the string literal are ignored. • lntergal types can be assigned to a string, but they require a cast. If the size (in bits) of the integral value is not a multiple of 8, it is zero filled on the left. The resulting value is treated as a string literal. The operators ==, 1=, <, <=, >, >=, {} , {0}, and indexing are defined for string types. If string literal arguments are used, they are converted to strings. Copyright c 199S.2006 byOoutos ltd 291
  • 291. String Indexing (i.e., Str[index)) is equivalent to Str.getc(index) - see below. Indexes are in the range 0 to N-1, where N is the number of characters in the string. Reading an element of a string yields a byte. If the given index is out of range, Str[index] is 0. Methods function int len() - returns the length of the string, i.e. the number of characters in the string, possibly 0. task putc(int i, byte c) - replaces the ith character of the string with the given integral value (c) or the first character from the string s. function byte getc(int i) - returns the ASCII code of the ilh character in the string. function string toupper() and to/ower() - return the string converted to upper- or lower-case respectively. • function int compare(string s) compares two strings, as in the ANSI C strcmp function, and embedded null bytes are included. - function int icompare(string s) - performs case-insensitive string comparison. • function string substr(int i, intj) character j of the string. • function integer atoi(), atohex(), atooct(), atobin() - return an integer corresponding to a string that contains a decimal, binary, octal or hexadecimal representation respectively. atoreal() returns a real number corresponding to a string. • function real itoa(), task hextoa(integer i), task octtoa(integer i), task bintoa(integer i) and task realtoa(real r) - perform the reverse function of the above operations. - returns the substring from character i to Gotchasl The behaviour when the string data type is used is different to that defined for strings in Verilog. Verilog strings are integers, with 8 bits for each character ­ see String Literal. Use strings in preference to storing string values in integral types. 292 Copyright C 1995·2006 by Doulos Ltd.
  • 292. String Exam les p I I s1 is initially "" string s l ; slri ng s2 � " Thi s is a s t r i ng l i teral . " ; sl = •so i s this . " s2 = ( s2 , sl } ; II $di spJ ay (s l . len ) ; II s2 is now "This is a str literal. So is this." ing Returns 1 1 See Also Array, String Literal, Variable Cop)nght 0 1995 2006 by Doolos Ltd 293
  • 293. String Literal String literals are string values; they are enclosed in double quotes. They behave like packed arrays, with a width of eight bits times the number of characters. " S t r i ng " See Expression. • A string literal may not span multiple lines of source code. • String literals may include the following escaped characters: n Newline t Tab Backslash " Double Quote %% Percent Character nnn Octal ASCII Code v Vertical Tab f Form Feed a Bell x02 Hex Number • Strings that are to be printed by system tasks such as $display and $monitor may include format specifiers (e.g. %b), which are interpreted in a special way (See $display). • When a string is stored in a non-string variable, 8 bits are required for each character, which is stored in ASCII code. Unlike in the C programming language, strings are not terminated by a null character (ASCII 0). • A string literal can be assigned to an integral type. If the size differs, it is right-justified and truncated or padded with zeroes. byte Cl 294 - "A" ; bll ( 7 : 0 ] B � " n " ; Copynght0 1995-2006 by Doulos Ltd
  • 294. String Literal • A string literal can be assigned to an unpacked array of bytes. If the size differs, it is left-justified and truncated or padded with zeroes. by te C3 [ 0 : 3 ] - " hi n " ; • String literals can be cast to a packed or unpacked array. Use strings in preference to storing string values in integral types. Gotchasl • The common string operations are supported by Verilog operators as follows: copy by simple assignment, concatenation by the concatenation operator, comparison by the equality operators. When using a string in an expression, be careful about padding. Strings are treated in the same way as numbers, and padded on the left with D's if the number of characters is less than the number that can fit in the variable. Padding may affect the results of comparison and concatenation operations. Exam les p l ogic [ 2 3 : 0 ) MonlhName [ l : l 2 ] ; iniLial begin "Ja n " ; MonlhName [ l ] MonLhName [ 2 ] - "Feb"; MonthNamc [ 3 ) "Mar"; "Apr " ; Mon thName [ 4 ] MonthName [ S ] "May"; "Ju n " ; MonthNamc [ 6 ) MonthName [ 7 ) - IIJul " ; 11Aug " ; MonthNamc [ 8 ) "Sep " ; MonthName ( 9 ] "Oct " ; MonthNamc [ lO ] MonlhName [ l l ) - "Nov " ; "Dec " ; MonthName [ l 2 ] end - - Sea Also Number, Operators, String, $display Coj>yrlght0 1995-2006 by Ooulos Ltd 295
  • 295. Struct Composite data type; a composite of one or more variables. � This feature was added in SystemVerilog s L ruct [ packed [ Si gning] ] { VariableDeclarations; . . . } ( PackedDimensions . . . ) StrucLName s , . . . PackedDi mens ion ; [ ConsLan tExpression : ConsLan tl-:xpressi on] S i gning = {one of) signed unsigned See Declaration • A structure can be assigned, or passed to or from a function or task as a whole. A function can return a struct. Structure literals (i.e. initial values to a struct) may use assignment patterns. The braces must match the structure dimensions. typedef struct ( i n t a; real b ; ) AB; AB c; c = • ' { 1 , l . 0 1 I I Struct literal assignment pattern Each element must match the type being initialized. AB TwoAB ( 1 : 0 I • = ' { { 0, 2 . 0 I , ' ' {1 , 3.0I l The ' { member : value 1 , {data type : value I and ' { d e fa u l t : value ) syntaxes may also be used: ' ' { member : value 1 sets a specific member to the specified value. ' 1 da La_type : va 1 ue 1 specifies the default value for all members of the specified type • ' { defa u l l : value 1 specifies the default value for any member. • A packed structure consists of bit fields that are packed together in memory without gaps. An unpacked structure has an implementation­ dependent packing. • If any member of a packed structure is 4-state, the whole structure is treated as 4-state. The values of any 2-state members are implicitly converted when reading from or writing to the structure. 296 Copi"!jhl 0 1995·2006 by Doulos Lid
  • 296. Struct packed structure can be used as a whole with arithmetic and logical operators. Its behaviour depends on whether is signed or unsigned; unsigned is the default. The first member specified is the most significant. A One or more bits of a packed structure can be selected as if it were a packed array, assuming an [n-1 :0] numbering: struct packed signed I int a; byte b; bit c; S; 5 [ 15 : 8 ] I I b Non-integer data types (e.g. real, shortreal) and unpacked arrays are not allowed in packed structures. The signing of unpacked structures is not allowed. Gotchasl C struct tags are not allowed in SystemVerilog. Exam les p typedcl slruct int A; union (biL i; byte j ) B; Strucll ; SLructl S [ 7 : 0 ] ; Named structure 11 Array of structures II struct packed signed int A; byLc B; byte C; PackedStruct; II Signed, 2-state See Also Casting, Typedef. Union Cop�t C 1995-2000 by Dootos Ltd 297
  • 297. Super Used to access members from the parent class, when they have been overridden by the derived class. .,.. This feature was added in SystemVeri/og super . Name (See Name) The member can be a member declared in the immediate parent class or be inher ited by the parent class. super.super is not allowed. • When using the super within new in a superclass, super.new must be the first executable statement in the constructor. That is because the superclass must be initialised before the current class. If the initialisation method of the superclass requires arguments the superclass's constructor can be called using the super keyword: function new ( ) ; super. new ( 3 ) ; I I Must be executed first in function new endfunclion Exam les p class ParentClas s ; int X = 1; function int AFunc ( ) ; AFunc - 2 • x ; end function endclass c l a s s SuperClass exLends ParentClass; int X = 2 ; I I Overridden variable function int AFunc ( ) ; AFunc = super . AFunc ( ) + 2*X* supe r . X; end function cndclass s- Aiso Class, Extends, New 298 Ccpynght C 1995-2006 by Doutos Ltd
  • 298. SystemVerilog Versions SystemVerilog went thjrough a number of revisions before becoming an IEEE standard in 2005. The underlying Verilog language also changed between 2001 and 2005. This article provides a brief summary of the main differences between the versions. For more information, the Accellera SystemVerilog standards may be downloaded from http://www.accellera.org. S stemVerilo 3.0 y g This was the first version of SystemVerilog. It was an Accellera standard. This version is an extension of Verilog-2001 and included: Extensions to Always blocks for modelling combinational, latched or clocked processes • Interfaces to encapsulate communication • Dynamic Processes for pipeline modelling (removed from later versions) • Procedural Assertions for verification New data types: int, char, logic, bit, etc. Typedef, Struct, Union. Enum • Automatic/static specification on a per variable instance basis Jump Statements (return. break and continue) A $root top level hierarchy for global definitions (modified in 3.1a) S stemVerilog 3.1 y SystemVerilog 3.1 is also an extension to Verilog-2001 . The testbench extensions were introduced in this version. In addition to the features in version 3.0, further features were added, including: Dynamic and associative arrays Classes Automatic/static specification on a per variable instance basis Extensions to fork-join, disable and wait to support dynamic processes. Interfaces to encapsulate communication • Clocking domains to support cycle-based methodologies • Program blocks for descr ibing tests • Randomization and constraints for random and directed-random verification Concurrent assertions for verification (replaced in 3.1 a) C<lp)'ighl 0 199�2006 by Doulos ltd 299
  • 299. SystemVerilog Versions Enhancements to events and new Mailbox and Semaphore built-in classes for inter-process communication. The Direct Programming Interface, which allows C functions to be called directly from SystemVerilog (and vice versa) without using the Pll. Assertions and Coverage Application Programming Interfaces (APis) S stemVerllo 3.1a y g SystemVerilog 3.1a was the final Accellera version of SystemVer ilog. It is pretty similar to the IEEE 1800-2005 standard. Again, it is an extension of Verilog2001, and includes these additional features: • Tagged union • Queues Packages and support for Compilation Units Procedural and concurrent assertions (rewritten) Functional Coverage The std:: package Pattern matching S stemVerllo IEEE 1800-2005 y g The following features are new to IEEE 1 800-2005 SystemVerilog, which is an extension of Verilog-2005 (see below): · Assignment patterns ( ( 1 ) ' The keyword var and data types for nets Set membership (inside) in case statements Typed arguments for properties and sequences As well as many minor changes and corrections. Chan es from Verllo g g-2001 to Verllo -2005 g With the introduction of SystemVerilog, no significant new features will be added to Verilog. The main changes between Verilog-2001 and Verilog-2005 are New net type: uwire Modified syntax for generate • 300 Protected envelopes (encryption) and ·pragma Copyright C 1995-2006 by Oouloo Ltd
  • 300. SystemVerilog Versions • 'begin_keywords As well as many minor changes and corrections. See Also Keywords Copl"!jhl0 1995-2006 by Doulos Lid. 301
  • 301. Task Tasks are used to partition large blocks of statements, or to execute a common sequence of statements from several places. Interfaces may include task definitions/prototypes . ..,. In SystemVerilog, tasks have been enhanced in a number of ways. I Task declaration } task [ Li fe time] [ Tn terfaceOrClass ] TaskName [ ( Ports , . . ) ] ; [ Declara tions . . . ) Sta temen t s . . . endtas k [ : TaskNamc] 1 Task prototype} task [ T a s kNamc) { [ Ports, . . . ) ) LifeTime = {one of} automalic static {one of) InterfaccNamc . ClassName [ # ( Parame terAssignments, rnterfaceOrClas:; = . . . ) I :: $unit module-<HERE>-endmodu l e interface-<HERE>-endinter face program-<!IERE>-endprogram package-<HERE>-cndpackage class-<HERE>-cndclass generale-<HERE>-endgenerale • Names used in a task that are not declared in the task refer to names in the calling module. A task may have any number of arguments (including none). If a task's arguments are declared ANSI-style, they must not be declared within the task. • 302 The default direction of a task argument is input. The default data type is logic. Copynghl Cl 1995-2006 by Doulos Ltd
  • 302. Task • A task prototype specifies the types and directions of the arguments of a task defined elsewhere. In a modport, the import requires the full task prototype, while the export construct can use the task prototype name. If a task has default argument values, so must the prototype. An array may be specified as an argument to a task . • The return statement can be used to exit the task before the endtask. The difference between disabling a task and returning from a task is that if a task disables itself, the outputs will not be defined. Returning from a task is recommended. • Tasks may be called in initial and always processes. • When a task is enabled, the values of the argument expressions corresponding to the task's inputs and inouts are copied into the corresponding argument variables. When the task completes, the values of the inout and output argument variables are copied to the corresponding expressions in the task enable statement. Ref arguments are passed by reference. automatic tasks can be invoked through use of their hierarchical name. The local variables of an automatic task cannot be accessed from outside that task using hierarchical names. In a static task specific data may be explicitly declared as automatic. If so, data has the lifetime of the call or block, and is initialized on each entry to the call or block. static tasks may not have ref arguments. In an automatic task specific data may be explicitly declared as static. If so, data has a static lifetime and a scope local to the block. • The default lifetime for a task is static. This may be overridden in the module, interface or program declaration: program automa Lic t e s t ; task T . . . II T is automatic II . . . endprogram Gotchasl • If a non-automatic task's inputs, inouts, outputs and any local variables are stored statically, even if a task is enabled (i.e. called) more than once, there is only one copy of these variables. If a task is enabled a second time before the first enable has completed, the values of the input and inout variables, and possibly the local variables too, will be overridden. Ccpynght 0 199$-2006 byDoulos Ltd 303
  • 303. Task • The values of the outputs and inouts are only copied to the corresponding variable expressions in the task enable when the task completes. If there is a timing control in the task after an assignment to an output or inout, the corresponding variables in the task enable will only be updated after the timing control delay. • Similarly, a nonblocking assignment to an output or inout may not work, because the assignment may not have taken effect when the task returns. If a task contains more than one statement, there is no need to enclose them in a begin-end. Statements are still executed sequentially. Complex RTL code is often structured by writing many always's. Consider instead using one always that enables several tasks. Use tasks in testbenches to apply repetitive sequences of stimulus. For example, to read and write data from a memory (See Examples). • Tasks to be used in more than one module can be defined in a separate module, containing only tasks, and referenced using a hierarchical name. automatic tasks may be used recursively, and may be re-entrant. Exam les p This shows a simple RTL task, which can be synthesized. task CounLer; inout [ 3 : 0 ] CounL; input Reset; if I 1 Synchronous Reset (Reset) CounL - 0 ; else CounL - Count I 1 Must use nonblocking, or value when be seen • 1; endt a s k An automatic task: task aulomatic PipelinedMu l l ( input [ 7 : 0 ] A, 0 , input integer Depth, outpuL [ 1 5 : 0 ] Y ) ; logic [15:0] begin temp 304 Lemp; I 1 ANSI-style arguments 1 1 a distinct Lcmp for each running instance of 1 1 P ipelinedMu l L due to automatic keyword A w B; Cop)Toghl 0 1995-2006 by Ooutos Lid
  • 304. Task repea t (Depth) @ (posedge e l k ) Y temp; = end e n dla sk An automatic task with static variables: task automat i c Task ( ) ; i nt varAl; stalic int VarS ; / / Automatic by default automati c int VarA2; II Automatic I I Static endta s k Argument of type array. task ATa s k ( input [ 15 : 0 ] [ 7 : 0 ] A, 13 [ 1 5 : 0 ] , output [ 1 5 : 0 ] [ 7 : 0 ] C [ I : O ] ) ; end task The following example shows the use of tasks in a testbench. module TestR/M; parameter /ddrWidth parameter DataWidth parameter MaxAddr = 5; 8; < < llddrB i t s ; reg [Da t a l� idth-1 : O J Addr ; reg [AddrWidth- 1 : 0 1 Data; wi re [ DataWidt h - 1 : 0) DutaBus - Data; reg Ce, Read, Write; Ram32 x 8 Uut ( . Ce (Ce ) , . Rd (Read) , . Wr (Write ) , . Data ( Datal3us) , .Addr (Addr ) ) ; initial begin : stimulus integer NErrors; integer i ; I I Initialize the error count NErrors - 0 ; I 1 Write the address value to each address for ( i-0; i<=MaxAddr; i-i+l ) ·lriteRam ( i , i ) ; Copl'ighl 0 1995 2000 by Doulos Lid 305
  • 305. Task I I Read and compare for ( i=O; i<-MaxAddr ; i= i +l ) begin ReadRam ( i , Data ) ; i f ( Data ! == i ) RamRrror ( i , i , Data) ; end I I Summarise the number of errors $display ( Completed with %0d errors, NErrors ) ; end task WriLeRam; input [ AddrWidth-1 : 0 1 Address ; input ( Da laWidth-1 : 0 1 RamData; Ce = 0 ; Addr = Addre s s ; nata = RamDa t a ; # 1 0 Write - 1 ; 1 1 0 Write 0; Ce 1; endtask = = task ReadRam; input [ AddrWidth-1 : 0 1 Address ; output [ Da t a-Hdth-1 : 0 1 RamData; Ce - 0 ; Address; Addr Data = RamData; Read = 1 ; 1 1 0 RamDaLa - DataBus ; Read = 0 ; Ce 1; end task = task RamError; input (AddrWidth-1 : 0 1 Address ; input [ DalaWidth-1 : O J Expected; input [ DataWidth- 1 : 0 1 Actual; if ( Expected ! �= Actual ) begin $displ ay ( "Error reading address h" , Address) ; $di sp l a y ( " Actua l % b , Expected % b " , Actual, 306 Copynght 0 1995-2006 by Doutoo Ltd.
  • 306. Task Expected) ; NErrors - NErrors + 1 ; end end ta s k endmodul e Tasks in interfaces: inter face A ( input log i c Clk) ; logic SLart; task Tas k ! ; endta s k : Taskl endin terface : A module Mod(A Interf ) ; a l ways @ ( I nter f . S L a r L ) Interf . Taskl ; endmodule modul e DUT; 1 ogic C l k ; A In t ( ( C l k ) ; I I Interface instantiation Mod Ul ( . l nLeL l ( In t: f . Tas kl ) J ; I I Only has access to the I I AddrGen task endmodule See Also Class, Export "DPI-C", Function, Import "DPI-C", Interface, Modport, Task Enable Copl'ighl c 1995-2006 by Ooolos ltd 307
  • 307. Task Enable A statement to enable (or "call') a task. When a task is enabled, values are passed into the task using the input and inout arguments. When the task completes, values are passed out from the task using the task's output and inout arguments. Ill> Named association of task arguments was added in SystemVerilog Tas kName l ( Expression, . . . ) ] ; See Statement. Tasks may be enabled from an initial or always, or from other tasks. They may be called recursively. Tasks may not be called from functions. The order of the expressions in the task enable statement corresponds to the order in which the arguments are declared in the task. The number of expressions must be the same as the number of arguments. • When a task argument is an input, the corresponding expression can be any expression. When it is an in out or output, it must be an expression that is valid on the left hand side of a procedural assignment. When a task is enabled, the input and inout expressions are copied into the corresponding argument variables. When the task ends, the values of the output and in out variables are copied into the variables listed in the corresponding task enable expressions. Tasks may be disabled internally or externally. Gotchasl By default, the implicit variables defined by the arguments to a task are static. So if a task is enabled whilst the same task is executing, the input and inout variables will be overridden. Exam les p t a s k Counter; inout [ 3 : 0 ) Count; input Reset; 308 Cop)f1ght c 1995-2006 by llootos Lid
  • 308. Task Enable endtask always @ (posedgc Clock) CounLcr(Count, Rese t ) ; See AJso Disable, Function Call, Task Cop)<ight c 199>2006 by Dootos ltd 309
  • 309. This Used to unambiguously refer to properties or methods of the current instance of a class. IJil> This feature was added in SystemVerilog {one of) th i s . ClassMcLhod this . Cl assProperty th i s . Name Class Property, ClassMethod - see Class See Class. The this keyword can only be used within non-static class methods. Exam les p class AClass; inl Va r l ; I I Var1 is a property of ACiass function new ( lnl va rl ) I I Var1 is an argument of the constructor this . varl - va r 1 ; end function I I The instance property is accessed using lhls e ndc l a s s See Also Class, Static 310 Cop)flgh1 0 1995-2006 by Doulos Lid
  • 310. Timeunit timeunlt is used to set the current time unit. timeprecislon is used to change the time step. II> This f eature was added in SystemVeri/og {one of} timeunit TimeLiteral; Limcprecision TimeLi tera l ; timeunit 'l'i mcLi teral; timeprccision 'l'imcLi teral; t imeprecision TimeJ,i tcral; Limcunit TimeLi tcra l ; TimeLi teral = (one of} Unsi gnedNumber Unit FixedPoi ntNumber Unit Uni t = {one of} s ms us ns ps fs $unit class-<!IERE>-endclass package-<!IERE>-endpackagc modulc-<HERE>-endmodule program-<!IERE>-endprogram interface-<HERE>-cndinterface A timeunits declaration appears as the first item in a compilation unit, or of a package, module, program or interface, i.e. before any other declarations. It may be repeated, provided any repeated declarations match the previous declaration. The precedence followed to determine the time unit is: The time unit set by a timeunit in the current module. Else, for nested modules, the time unit is inherited from the enclosing module. Else, if a "timescale directive has been specified, then the time unit set by the last "timescale directive. Coc>yrtght 0 1995-2006 by Oouloo Ltd 311
  • 311. Tlmeunlt • Else, the time unit set in the compilation unit ($unit). • Else, the simulator's default time units. There is no space between the time unit value and the unit. For example, 1 ns is valid, but 1 ns is not. • • A step is equivalent to the simulation time precision. It is an error to set a precision larger than the current time unit. The timeprecision sets a time which must be a power of 10 units. • If the timeprecision is not specified, then the precision is determined following the same precedence as with time units. time is a 64 bit integer of time steps data type. The time step can be changed using timeprecision or a 'timescale directive. Local time values are scaled to the timeprecision declared in the module. module m; timeprecision O . l n s ; i n i t i a l U 5 . 15ns A - 1 ; II Round lo#1 5.1ns according to lime I I precision endmodule • By default a literal time number is multiplied by the current time unit, if no time units are specified. Gotchasl • An integer or real variable is cast to a time value by using the integer or real as a delay. # 1 5 . 1 5 ; 1 1 Multiply by time unit and round according to lime precision There is no space between time and the time unit. Use in preference to 'timescale, which produces file order dependencies. Exam les p L imcunit lOOns; timeprecision lOps; s- Aiso 'timescale, Compilation Unit, Interface, Module, Variable 312 COpP.jhl 0 1995-2006 by Ooulos Ltd.
  • 312. Timing Control Used to delay or schedule execution of statements. Timing controls may either be placed in front of statements, or between the = or <= and the expression in procedural assignments. The former delays the execution of the statement it precedes, and the latter delays the effect of the assignment. ""' Timing controls were enhanced in SystemVeri/og ( Timing controls before statements ) tone of) DelayCon trol EvenLConLrol ( Intra-assignment Timing controls ) (one of) Del ayCon trol EvenLCon trol repeal ( Expression ) EvenLCon Lrol Del ayCon trol = ( one of) #Unsi gncdNumberl Uni t ] #ParameLerName IConsLanLMinTypMaxExpression # !Min TypMaxExpression) Even tCon trol = (one of] 1 of Variable, Net, Event, Sequence 1 @Name @ ( Evenu::xprcssion ) @ (*) @' @SequenccName EventExpression - (one of) Expression [ i f f Expression] Name [ i f f Expression] {of Variable, Net, Event, Sequence ) { 0 1 , OX, OZ, X1 or Z1 1 negedge Expression [ i ff Expression] { 10, 1X, 1Z, ZO or X0 ) EventExpression or EventExpression posedqe r:xprcssion [ i f f Expression] EvenLExpression, Even tl·:xprcssion Uni t = {one of) s ms us ns ps fs step clocking-<HERE>-cndclocking covergroup-<HERE>-endqroup property-<HF.RE>-endproperty Cop�l 0 1995-2006 by Doulos lld 313
  • 313. Timing Control sequence-<HERE>-endsequence See also Statement. For Intra-assignment Timing controls see Procedural Assignment. An event or delay control before a statement causes the execution of the immediately following statement to be delayed. • The expression on the right hand side of a procedural assignment is evaluated when the assignment is executed. If there is no intra-assignment delay, the variables on the left hand side are updated immediately for blocking assignments, and in the next simulation cycle for nonblocking assignments. If there is an intra-assignment delay, the variables on the left hand side are only updated after the intra-assignment delay has occurred. Intra-assignment delays must be constants, but delays before statements may be constants or variables (i.e. they may involve nets or variables). • An event control is triggered by a change of value of a net, variable or expression, the triggering of a named event or the success of a sequence. Where there is an "or" or comma-separated list, the event control is triggered if any one of the event expressions. • @• or @rl is an implicit event expression. It is triggered by a change of value of any net or variable in the statement it precedes, which may be a begin-end or fork-join group. • For posedge and negedge, only the least significant bit of the expression is tested. Otherwise any change in the expression triggers the event. Events expressions must evaluate to a singular type (i.e. not an "aggregate type", which is the type of an unpacked array or struct) Assignment expressions may be used in an event control (e.g. @ ( (a t c ) ) ). The event control is sensitive to changes in the result of the expression on the right-hand side of the assignment ONLY. b When using the iff qualifier, the event expression only triggers if the expression after the iff is true. iff has precedence over or. For sequences in event expressions, the event expression triggers when the sequence matches. Gotchasl An intra-assignment delay of zero (#0) is not the same as having no intra­ assignment delay. Nor is it the same as using a nonblocking assignment with no delay. #0 is used to schedule an event after all pending event assignments at the current time have been made, but before any non314 Copyright Cl 1995-2006 by DO<Jios Ltd.
  • 314. Timing Control blocking assignments are made. (A nonblocking assignment with no intra­ assignment delay is the same as a one with an intra-assignment delay of #0. ) • There is no space between a time literal and the time unit. Intra-assignment delays can be used in RTL descriptions to overcome problems of clock skew when assigning variables representing flip-flops. Exam les p HO # l Ons # ( Period/2) # (1 . 2 : 3 . 5 : 7 . 1 ) @ Trigger @ (a or b or c ) @ (a , b , c ) @' @ (* ) @ (posedge c l ock or neqcdgc rescL) Delay a nonblocking assignment to overcome clock skew. always @ (posedge Clock) CounL <� 1 1 Count 1 1 ; Assert Reset for one clock period on the fifth negative edge of Clock. injtial begin Reset = repeat ( 5 ) @ ( negedge Clock) 1 ; ReseL @ (neqcdge Clock) 0 ; end module Latch (input [ 7 : 0 ) D, i npul E n , outpuL logi c [ 7 : 0 ] Q ) ; always @ ( D i f f En =- 1 ) Q <� D; endmodule See Also Always, Repeat, Wait Ccpynghl 0 199!>2000 by Doo1ao Lid 315
  • 315. Typedef Defines a new type . eature was added in SystemVeri/og .,.. This f ( one of} typedcf DaLaType TypeNamc [ PackedDimcnsions) ; typedef T n ter f a ceN amc [ [ Conscan tExpression] . . . I . TypeName TypeName [ PackedDimensions ) ; Lypedc( [ c l a s s ] ClassName; typedef Clas sNamc [ n ( Pa rame L crll ssi gnmen t } ] TypeName; Parame LerAssignment = { one of) [Ordered assignment J OrderedParamAssign , . .. NamedPar·amAssign, OrderedParamAssign NamedParamAssign c = { Named assignment } {one of} Expression DataType { one of} . ParameterName ( Exprcss i on ) . Pa ramet e rNa me ( Da ca Type ) PackedDimension - [ConscantExpression : Constantcxpression] See Declaration. A type can be used before it is defined, if it is first identified as a type by an empty typedef, except for enum values, which must be defined before they are used. typcdcf NewType; New'l'ype T = 1 ; typcdef i n t Nei<Type; If a type is defined within an lnterface, it must be re-defined locally before being used. in terface Interf; Lypedef i n L intP; endinterface Interf I l ; typedef I l . int P i n t P ; 316 Copyrogho C 1995-2006 by Ooulos Lid.
  • 316. Typedef • The type may be given by the context, or specified with a cast. type de f bit ( 1 : 3 1 Th recChar; I I 3 characters packed together ThrccChar ' ( { A , B, C } ) ; b = Multiple packed/unpacked dimensions of an array can be defined in stages with typedef. typedef class is used to declare a class name before the class is defined. The word class is not required and may be omitted, although it is useful for documentation and readability. typedef may be used to resolve the case when two classes need a handle to each other, to avoid the compiler finding an undefined reference: typedef class B; I I Forward declaration for class B; class keyword is I I optional in this statement class A B c; endclass class B 11 c ; endclass Exam les p Lypedef enum {True, False} Boo!; Bool Var; Lypedef s l rucl {byte Addr; byle Data ; } Bus ; Bus Busl ( 0 : 3 1 ; int X ; shorlreal Y ; typedef union FloalingPoint N; N . Y = 0 . 0; II Array of structures 1 FloaLingPoinr.; typede f mailbox # ( i n t ) Ma i lBox; II Parameterised mailbox Ma i lBox MB = new; See Also Array, Class, Struct, Union Cop)T1Qhl 0 1995-2006 byDooJoo ltd 317
  • 317. Union Composite data type; a composite of one or more variables sharing the same storage. Tagged unions are type-checked unions. II> This feature was added in SystemVeri/og u n i on [ Lagged ) (packed VaciableDeclarations ; [ Signing) ) { {void allowed in tagged unions } } UnionNamcs, . . . ; Signing ; (one of} signed uns i qned See Declaration • The size of a union in bits is the size of its largest member. packed union contains members that are packed structures or arrays of the same size. A If any member is 4-state, the whole union is 4-state. packed union can be used as a whole with arithmetic and logical operators. Its behaviour depends on whether is signed or unsigned; unsigned is the default. A Non-integer data types (e.g. real, shortreal) and unpacked arrays are not allowed in packed unions. • A function • A tagged return can be a union. If so, a hierarchical name used inside the function and beginning with the function name is seen as a member of the return value. union is a type-checked unio n. The "tag" is the current member name. A member of a tagged union may only be updated with a tagged union expression (see example) or an expression of the correct type, and only read with a type that is consistent with the tag value. A member of a tagged union can be declared with type void, in which case all the information is in the tag (See example). In a tagged union that is packed, the minimum number of bits to store the tag are included as the most significant bits of the packed representation. Unlike a non-tagged packed union, members need not be the same size. The member expressions are right-justified. For example, a tagged packed 318 Copynghl 0 1995-2006 by Ooulos Ltd.
  • 318. Union union with five members needs three bits for the tag, in addition to the bits to represent the largest member. As well as providing type-safety and simpler code than explicit tags, tagged unions can be used with pattern matching - see the article "Matches". Exam les p typedef u n i on { inL i ; shortint j ; ) Un; Un N; N . j = 0 . 0; typedef struct packed { I I Unsigned by default b i t [ 3 : 0 ] 14 ; bil [ 7 : 0 ) B B ; bil [ 15 : 0 ] C16; Structl; Lypcdef union packed I I Unsigned b y default StrucLl ASLrucL; b l L [ 2 7 : 0 ) A2 8 ; b i t [ 1 3 : 0 ] [ 1 : 0 ] A14_2; Union1 ; Union1 U 1 ; byte 11; b i t [ 3 : 0 ] Nib; D - U 1 . A2 8 [ 2 7 : 2 6 ] ; II Same as D - U1 . Al4_2 [ 1 3 ) ; N i b - U 1 . A2 8 [ 27 : 2 4 ) ; II Same as Nib - Ul . AsLruct . A4 ; Lypedef union tagged void Invalid; i nt i ; InLOrlnvalid; T nLOrTnvalid L i ; ti - Lagged i 4 2 ; ti . i I 1 Tagged union expression I I OK - tag is "i" 10 i f ( t i . i -- 1 0 ) . . Li - L agged I nvalid ; . if (L i i . == 10 ) . Copl'ight C> 1995-2006 by Doulos ltd . . I I True I I No value needed 1 I Error - ti is "Invalid" 319
  • 319. Union See Also Matches, Struct, Typedef 320 Copyrighl 0 199S.2006 by Ooulos Lid
  • 320. Unique Used before if to guarantee that there is no overlap in a series of if-else-if, allowing the expressions to be evaluated in parallel. Used before case to guarantee that there are no overlapping values, allowing the case items to be evaluated in parallel. Ill" This feature was added in SystemVerilog See If and Case A unique if indicates that there should not be any overlap in a series of if­ else-if conditions, allowing the expressions to be evaluated in parallel. If unique is used before an if, an explicit else must appear, otherwise a run-lime warning is issued when a condition is not matched. A unique case checks for overlapping case values items, allowing the case items to be evaluated in parallel. If unique is used before a case, the simulator will issue a warning message if no case item matches. If unique is used before a case, the simulator will issue a warning message if more than one case item matches the case expression. When using unique, there is no need to code a default case to trap unexpected case values. Exam le p bi L [ l : O ] S ; unique i f ( S [ l : 0 ] Slale Statel; ?. ' b01 ) = e l se if ( S [ l : O ] == 2 ' b10) I I 2'b00 and 2'b11 cause a warning State State2; unique case?. ( S ) Stale l ; 2 ' b0 1 : State = ?. ' b l O : Slate = S L a L c 2 ; II 2'b00 and 2'b11 cause a run-timewaming endcase See Also Attributes, Case, If, Priority Copynghl 0 1995 2006 by Douto> Lid 321
  • 321. User Defined Primitive User defined primitives (UDPs) can be used as an alternative to modules for modelling small components. They are instanced in exactly the same way as the built in gates. { one oft primi t ive UDPNamc (OuLpuLNamc, InpuLName s , . . .); UDPPor tDcclara tions; UDPBody endprirnilive pr im i Li ve UDPName ( UDPOutputPortDecl aration, UDPinp u L PorLDeclara t i ons, . . .) ; UDPBody endprimilive UDPPortDeclara tion � {one of} output Outpu tName reg OutputName [ = ConstantExpression] input InputName , . . . oulput reg 1 Sequential UDP) OutputName UDPBody = {oneof) Combin a t i onalBody Sequen tia lBody Combin a L i o n a l Body - t ab l e Combina tionalEnLry . . . end t able Sequen LialBody = [ i ni t i a l OutputName Initial Value; I Lab l e Sequen LialEntry . . . end table Ini t ial Value � tone of} 0 1 l ' bO l ' b l l ' bx { Not case sensitive } Combi n a L i onalEntry - LcvclinputList Sequen t i a l En try OutpuLSymbol ; = Sequen tial inpu tList Sequen t i a l inputList Curren tOutput NextOu tput ; - { one of} LevelinpuLLisL Edgeinpu tl.i st Levcl inputLi s L Edgeinp u t L i s t = ( Level Symbol . . . 322 LevelSymbol . . . � 1 Edge Indicator [ Level Symbol . . . 1 Copjf'9hl C t995·2006 by OouiOS ll�
  • 322. User Defined Primitive = Curren tOutpu c Nex tOu tput � T ,ovelSymbol (one of) OutputSymbol - Edge Indica tor � (one of) ( Le vel Symbol J,evel Symbo I ) EdgeSymbol ou tpu t Symbol Leve I Symbo 1 EdgcSymbol - { one of) 0 1 x (one of) 0 1 x ? b ( one of) r f p n * = - ( Not case sensitive 1 ( Not case sensitive ) { Not case sensitive 1 $unit A UDP has one output and at least one input. Implementations may limit the number of inputs, but at least 9 inputs for sequential UDPs and 1 0 inputs for combinational UDPs must b e allowed. inout ports are not permitted on UDPs. All ports of a UDP must be scalar. Vector ports are not permitted. If the UDP output is declared as a reg, the UDP i s a sequential UDP. Otherwise it is a combinational UDP. • If a sequential UDP output is initialized, the initial value only starts propagating from the output of any instances of the primitive at the start of simulation. Sequential UDPs can be either level sensitive or edge sensitive. A sequential UDP is edge sensitive if there is at least one edge indicator in the table. The behaviour of a UDP is defined in a table. The rows in the table define the output values for various input conditions. For a combinational UDP, each row defines the output for one or more combinations of input values. For a sequential UDP each row also takes into account the current value of the output reg. A row may have at most one edge change entry. The row defines the value of the output for the input and current output reg values, when the specified edge occurs. Copynghl 0 1995-2006 by Doulos Lid 323
  • 323. User Defined Primitive • The special level and edge symbols used in tables have the following meanings: ? 0 1 or X b or B 0 or 1 - Output is unchanged (vw) Change from v to w r or R (01) f or F (10) p or P (01 ) (Ox) or (x1) n or N (1 0) (1 x) or (xO) . (??) • Unspecified combinations of input values and edges result in the output being unknown (1 'bX). • The Z value is not supported. Zs on inputs are treated as Xs; Zs are not allowed as output values. Note the special meaning of?, which is different from its meaning in a number (where it has the same meaning as Z). It is illegal to have the same combination of inputs. including edges. specified for different outputs. Gotchasl • For a sequential UDP. if an edge appears anywhere in the table, all possible edges on inputs must be considered, because the default is that an edge causes the output to be unknown. • In a sequential UDP, the keyword logic may not be used in place of reg. UDPs can sometimes be made to simulate very efficiently compared with behavioural models. Use UDPs when modelling library components such as ASIC cells. For components with more than one output, use a separate UDP for each output. Put a comment at the top of a table, indicating what the columns are. 324 �yrlght c 1995-2006 by Ooulos ltd
  • 324. User Defined Primitive Exam les p primi tive Mux2tol a, (f. b, sel l ; II Combinational UDP ou tpu L [ ; input a , b, scl ; tabl e II a b sel f 0 ? 0 0; 1 ? 0 1; ? 0 1 0; ? 1 1 1; 0; 0 0 ? 1; e n dtable e ndpri miL.ive primitive Latch (Q, D, Ena ) ; output Q; input D, En a ; II Level sensitive UDP II Keeps previous value II reg Q; Edge sensitive UDP table II D En a old Q 0 0 0 ? 0; 1 0 ? 1; ? 1 ? ' 0 0 0; ? 1 ? l; endLablc endprimitive primitive DFF (Q, Clk, D) ; ou tput O ; inpul Clk, D; r e g Q; initial Q - 1; Copynght C 1995-2006 by Ooulos Lid. 325
  • 325. User Defined Primitive table II Clk D r 0 0; II Clock '0' r 1 ? 1; II Clock 1 0 0 ' II Possible Clock 1 ' II 0 0 ' II 1 ' ' ' II ' II (0?} old Q (0?} (?1} (?1} (?0) ? ? ( 1?} ? ? ? Q II ' ' Ignore falling clock II Ignore changes on D endLdble endprimi t i ve primitive SRFF (output reg Q II initial Q 1 ' bl ; table l ' bl , input S , R) ; � II s R 1 0 Q+ Q ? 1 f 0 1 0 r ? 0 f 0 0 - ; ? 0 end table endpr imi t j ve See Also Gate, Instantiation, Module 326 Coc>�Tighl C 199!>-2006 by Doole$ Ltd
  • 326. Variable Variables store values assigned in initials, always's, tasks and functions. They may also be assigned with continuous assignments. They are used extensively in behavioural modelling. .,.. Many new variable types were added in SystemVerilog. Variables may be assigned by a continuous assignment. [ va r j [ T, i fetime] [ DataType ] NameOrAssignmenLs, . . . ; Lifet ime - { one of} st a ti c automalic Data Type = {one of} In tegerVector'l'ype [ Signing J [ PackedDimens ions . . . J IntegcrAL omType [ Signing] Noninteger1'ype Struct Union Enum String Event Clwndle Vi rtua 1 Interface TypdcLName ClassName CovergroupName NamcOrAssignment {one of} � V a r i ableNamc [ Va riableDimensions] [=ConsLan LExpressionl ArrayName [ ] new [ Expression] [ (ArrayName) I ClassObjec LName [ = new [ (Expressions, . . . ) I = ClassObjectName - new ClassObjectName ( shallow copy l [CovergroupinstanceName] = new [ (Expressions, . . . ) ] Signing - (one of} signed unsigned InL egerVectorType = { one of ) b i t logic reg In tege riLomType = ( one o f } byte shortint i n t longint integer = { one o f ] time shorlreal real realtime NonintegcrType PackedDimcnsion - [ Constan tExpress ion : Cons tanLExprcssion ] VariableDimensi on = (one of) Unpa ckedDimensi ons . . . [] f Open array} [DaLa'l'ype] f Associative array} (*] ( Associative array with wildcard index} UnpackedDimensi on - {one of] Copynght C> 1995-2000 by Oouioo Ltd 327
  • 327. Variable ( Cons tantExpressi on : ConstantExpress i on ] (ConstantExpress ion] $unit package-<HERE>-endpackage modul e-<IIERE>-endmodu l e begin-<HERE>-end generate-<HERE>-endgenerate i nterface-<HERE>-endi nterface prog ram-<llf-:RE>-endprogram class-<HERE>-endclass for k-<UERE>-joi n Las k-<HERE>-endtask function-<HERE>-cndfunction The keyword var is optional. If present, the data type may be omitted, and defaults to logic. var may be used in port declarations to declare a port as a variable rather than a net type. • Variables may be assigned using procedural assignments. The same variable may be assigned in more than one process (initial or always). • A variable may be assigned using one continuous assignment or driven from a single output port. Such variables may not be initialized nor assigned using a procedural assignment. They may not be driven from more than one continuous assignment, from more than one output port, or a combination of these. bit, byte, shortint, int and longint are 2-state integers. logic, reg, Integer y and time are 4-state integers. logic and reg are exactl the same (except for the name). In SystemVerilog, logic is preferred to reg, because the term describes the usage more accurately. • byte is a signed 8 bit integer, shortint is a signed 1 6 bit integer, int is a 32 bit signed integer and longint is a 64 bit signed integer. bit, reg and logic have a used-defined vector size. integer is a signed 32 bit integer and time is an unsigned 64 bit integer. A variable of type Integer or time generally behaves like a reg or logic with the same number of bits. Individual bits and part selects of integers and times can be made in the same way as they can for logics However, in an expression, the value of an integer is treated as a signed value, whereas the value of a logic, reg or time is treated as unsigned. . 328 Copyr•Jhl C I 995-2006 by Douloa Ltd.
  • 328. Variable • byte. shortint, Int. integer and longlnt default to signed. bit, reg and logic default to unsigned, as do arrays of these types. • An automatic variable has the stack storage allocated on entry to a task, function or named block and de-allocated on exit. A static variable has the storage allocated on instantiation and never de-allocated. • automatic variables cannot be used to trigger an event expression or be written with a nonblocking assignment. • If a variable is declared as signed, arithmetic operations and comparison respect the sign, and any required sign extension is automatic. • When declaring a new covergroup instance, the instance name may only be omitted within a class, and only then if there are no other instances of the covergroup. Automatic Converslons!Truncatlon Automatic type conversions from a smaller number of bits to a larger number of bits will extend the sign if signed, or add the appropriate number of zeros if unsigned, and will not cause warning messages. Automatic truncation from a larger number of bits to a smaller number does cause a warning message. • Automatic conversions between logic and bit do not cause warning messages; 1 converts to 1 , anything else to 0. Use logic or bit for describing logic, lnt for loop variables and calculations, real in system models, and time and realtime for storing simulation times in testbenches. The other types are useful for interfacing with C programs, or for translating C code into SystemVerilog code Exam les p reg a , b , c ; logic ( 7 : 0 ] mem [ l : 1 0 2 4 ( , Byte; I I Byte is not a memory array in Leger i , j , k; Lime now; real r ; short i nL Shint [ 7 ] ; II Same as shinL ( 0 : 7 J bit ( 7 : 0 ] B; I I Same as byte B ; logic s i gned [ 3 1 : 0 ] L; byte C � " A " ; I I Same as integer L ; Cop)Tlghlc 1995-2006 by Doolos ltd 329
  • 329. Variable logic [ 1 5 ; 0 ] V; logic Pa rity 0; al•<�ays @ (V) for ( int i - 0 ; i <= 1 5 ; i++ = Parity A= V(i ] ; See Also Std::, Class, Assign, Covergroup, Initial, Name, Net, String 330 Copynght c 1995-2006 by Do<Jios Ltd
  • 330. Virtual If a class is not intended to be instantiated, it can be made abstract by declaring it as vi rtual. Methods of a class can also be declared virtual .. .,. This feature was added in SystemVerilog virtual class ClassName ; v i r t u a l Cla ssMc LlJod; An abstract class cannot be instantiated, it can only be derived. • An abstract class can contain virtual methods with only the prototype and no implementation. Methods of normal classes can also be declared virtual, but the methods must have a body. • If a derived class overrides a virtual method, it must follow the prototype exactly. A variable in a superciass may hold subclass objects. If virtual methods have been defined. the appropriate subclass methods (and not the superclass ones) will be called. See the example below. This behaviour is called polymorphism. Gotchasl Virtual classes and methods are not related to virtual interfaces. Exam les p virtua l class BaseC l as s ; I I Class that cannot be instantiated virtual protected function i n t AFunc ( i n l x ) ; cndfunction II p ro t o t ype only e nd c l a s s class ExtcndClass extends BascClass ; I I Subclass protect ed funclion int AF'unc ( i nt x ) ; I I Prototype identical to 1 1 the BaseCiass one AFunc; = x - 1 ; endfunct ion cndclass Copyrighl 0 1995-2006 by Ooulos Lid 331
  • 331. Virtual Polymorphism example: BaseClass Bases ( 2 ] ; II Declare a variable of abstract BaseCiass ExtendClass ExCl - new; I I Instance of an Extended Class object BaseClass [ 0 I = ExCl; II Legal int x; 1) II Invokes the AFunc method 1I i f (BaseC lass [ O ) . A<unc ( x ) from ExtendCiass See Also Class, Protected 332 Copyright C 1995·2006 by Doul01 ltd.
  • 332. Virtual Interface A virtual interface is a variable that can represent different interface instances at different times in a simulation. This allows, for example, the same subprogram to operate on signals in different interfaces. � This feature was added in SystemVeri/og Virtual interfaces and virtual classes and class methods are not related. ( Declaration) virtual [ inlerface] InLerfaceName V i rtual Name [ - I nterfaceinstance ) , Vi rtualName [ � Interfaccinstance ) , { Data Type} v irtual [ i nterface ) InterfaceName; See Declaration. Virtual interface variables can be passed as arguments to tasks, functions or methods. A virtual interface must be initialized before it can be used. Before it is initialized, it has the value null. The only operations that are allowed on virtual interface variables are (i) assignment to, or (ii) comparison (== and !=) with an interface instance or another virtual interface of the same type, or to null Virtual interface may not be used as ports, interface items, or members of unions. • The components or the interface that has been assigned to a virtual interface are available using the dot (.) notation. They can only be used in procedural statements, not in continuous assignments or sensitivity lists. Virtual interfaces can be declared in a class and initialized in the class constructor. This enables every instance of the class to connect to a different interface instance (See the example). Cop)'lght C !99!>-?006 by0outos ltd 333
  • 333. Virtual Interface virtual interface can refer to an interface's clocking block in a modport to create an abstract synchronous model. A Exam le p interface Bus ; logic pa ssenger ; endintcrfacc class BusTransaclor; virtual interface Bus b u s ; f u n c t i o n n e w ( v i rtual B u s b ) ; bus ; b ; cndfunc l i o n t a s k do_some lhing ( i ) ; bus . passenger �; endtask endclass - module Slave (Bus bus ) ; . . . endmodule module Test; Bus busl () , bus2 ( ) ; Slave slave i n s t l ( bu s l ) ; S lave s l ave inst2 (bus 2 ) ; i n itial begin BusTransactor Ll BusTransactor t2 = = new (busl) ; new (bus2 ) ; t l . do_somethi ng ( O ) ; I I bus1 .passenger = 0 t2 . do_something ( l ) ; end endmodul c I I bus2.passenger = 1 Clocking blocks in virtual interfaces i nterface An i n t f ( i nput logic e l k ) ; wire a , b ; clocking c b @ (posedge e l k) ; input b ; output a ; endclocking 334 Cop�t C 1995-2006 by Dou!OO Ltd
  • 334. Virtual Interface modporl STB (clocking cb) ; I I Synchronous testbench modport modport OUT ( i nput b , oulput a ) ; I I Connects to DUT endinLerface module Device ( i nlerface T ) ; endmodule modu l e Test Dev i ce ; logj c e l k ; A n 1 n t f 1 1 ( el k ) ; Anintf 12 ( e l k ) ; Device Dcvicel ( I l . DUT ) ; Device Device? ( I 2 . DUT ) ; Tester test ( l l . STB, T2 . STB ) ; endmodule : Test Device program Tester (Aninlf i l , An l n l f i 2 ) ; typedef virlual i nterface Anintf V I ; L a s k Drive ( V J v) ; v . cb . a <- 1 ; endlask : Stirn function Sample (VI v) ; rcLurn v . cb . b; cndlask : Stirn in i Lial begin Drive ( i l ) ; Sarnple ( i l ) ; Drivc ( i2 J ; Sample ( i 2 ) ; end endprogram : Tester See Also Class, Clocking, Interface, Modport Copynght0 199$-2006 by Doutos ltd 335
  • 335. Wait A wait statement is a procedural statement that may cause a process to block until a specified condition occurs. The condition could be the value of an expression (wait), the termination of spawned processes (wait fork), or a specified sequence of events (wait_order). ..,. wait_order, wait fork and the sequence tiggered method were added in SystemVerilog {one of) wail (Expression) [ S t a temen t ] ; wa i t_order ( Names, . . . ) Action8lock wait fork; ActionBlock ( one of) Sta temen t [ S t a temen t ] else Sta tement • A walt only delays the following statement if the expression is false (zero or X) when the wait is reached; the following statement is executed when the expression becomes true. If the expression is true (non-zero) when the wait is reached, the following statement is not delayed, but executed immediately. A walt fork causes the calling process to block until all its child processes have finished. (See Fork) A wait_order causes the calling process to block until the specified events trigger in the order specified. When this happens, the statement (if any) before the else in the action block is executed and the process unblocks. If the events trigger out of sequence, the else (fail) branch of the action block is executed. If there is no else branch, an error is generated. Only the first event in the sequence in a wait_order can wait for the triggered property. Exam les p wail ( ! Resell Sdisplay ( "Reset has gone l ow" ) ; The following example waits until the sequence seq1 is successfully completed. wait ( scql . triggcred ) Sdisplay ( "Scquence seq! has complelcd" ) ; 336 Copynght 0 t99S.2006 by Dootos Ltd
  • 336. Wait The following statement wails until the events e 1 , e2 and e3 are tr iggered in that sequence. When this happens, success is set to one. If the events trigger out of sequence. success is set to 0. wai t_ordcr ( e l , e 2 , e 3 ) success = I ; e l s e success - 0 ; See Fork for an example using walt fork. Sea Also Assert, Fork, Sequence, Timing Control C<>pynghl C 199S.2006 by Doulos Ltd 337
  • 337. While A loop statement that repeats a statement or block of statements as long as a controlling expression remains true (i.e. non-zero). while ( Expressi on) Sta tement See Statement. Exam les p reg ( 1 5 : 0 ] Word; (�lord) while begin if (Word [ O ] ) CountOnes Word - CounLOnes 1 l; Word > > 1 ; end See Also Do-While, For, Forever, Repeat 338 Copyright C 1995.2006 by Douto. Ltd.
  • 338. System Veri log GOLDEN REFERENCE GUIDE Compiler Directives /�DOULOS
  • 339. Compiler Directives Compiler directives are instructions to the SystemVeritog compiler. Compiler directives are preceded by the backwards apostrophe C). sometimes called the grave accent character. The effect of a compiler directive starts from the place where it appears in the source code, and continues through all files processed subsequently, to the point where the directive is superseded, or the end of the last file to be processed. A summary of SystemVerilog compiler directives follows. More detailed information about some of the more important directives follows this summary. n Ill> ·defi e and 'include have been modified in SystemVerilog. Gotchasl The effect of compiler directives may depend on the order in which the files that include the source code for the design are compiled. Standard Com lier Directives p The following compiler directives are defined in the Veri log LRM. 'begin_keywords and 'end_keywords These are used to modify the list of keywords the compiler recognises within a section of SystemVerilog source code. 'celldefine and 'endcelldefine Used, respectively, before and after a module to tag it as a library cell. Cells are used by certain PLI routines for applications such as delay calculators. Example: ' ce l ldefine module Nand2 ( . . . ) ; I I Nand2 is a 'cell' endmodu le endcelldefine · · default_nettype Changes the default net type for implicit declarations. If this directive is not present, the default net type is wire. Example: · de fa u l l_ net type t r i l I I All SystemVerilog net types allowed Implicit declaration of nets may be suppressed by using argument value none. Example: 340 Copynght 0 1995-2006 by Doolos Ltd.
  • 340. Compiler Directives · de fa ult_nettype none I I Implicit declaration switched off 'define and ·undef 'define defines a text macro. ·undef cancels a macro definition. Macros are substituted during the first phase of compilation. They are also used to control conditional compilation (see 'ifdef). For more details on 'define, see the separate article. 'ifdef, 'else, 'elsif, 'end if and 'ifndef Conditionally compiles SystemVerilog code, depending on whether or not a specified macro is defined. For more details, see the separate article, 'ifdef. 'include Directs the compiler to read the contents of a file, and compile them in place of the "include directive. Examples: ' incl ude "definilions . v " I I or ' define MyFile "definitions . v" ' include ' My F i l c ' include <VcndorDe fin i Lions . vh> When the file name is in double quotes it may include a full or relative path name in the operating system. When angle brackets are used, the location is relative to a vendor-specific include directory. 'line Number "FileName" Level 'line resets the current line number and filename of the current file to the line number and filename presented. It renects the location in an original file, if the actual source file has been modified by addition or reduction of lines (e.g. error messages, source code debugging, etc. may direct the user to the actual original line). Level indicates whether an include file has been entered (value is 1 ). an include file is exited (value is 2), or neither has been done (value is 0). The results of this directive are not affected by the compiler directive · resetall. Example: " l ine 20 " f ile" 0 ·resetall Resets all active compiler directives to their default values. This can be used at the top of every SystemVerilog source file, to prevent unwanted effects resulting from compiler directives in files that were compiled before the file. Example: ' resetall Copynght 0 1995-2006 by Doolos Lid 341
  • 341. Compiler Directives 'timescale Defines the simulation time units and precision. For more details, see the separate article. 'unconnected_drive and 'nounconnected_drive 'unconnected_drive causes unconnected inputs of modules to pull up or down. 'nounconnected_drive resumes the default, which is to make unconnected inputs float with a value of Z. Example: ' unconnected drive pullO II or'pull1' Non-standard Com iler Directives p The following directives are not part of the IEEE standard, but are mentioned in the LRM for informative purposes. They may not be supported by all SystemVerilog tools: 'default_decay_tlme Specifies the default decay time for trireg nets, when no explicit decay time is given. Examples: ' default_decay_Lime 50 · defaul L_decay_time i n f i n i te · II Means it will not decay default_trireg_strength Specifies the default strength for trireg nets, as an integer. The modelling of strengths using integers is a non-standard extension to the SystemVerilog language. Example: " default_Lrircg strength 3 0 'delay_mode_distributed, 'delay_mode_path, 'delay_mode_unit and 'delay_mode_zero These directives affect the way in which delays are simulated. Distributed delays are the delays on instances of primitives, continuous assignments delays and net delays. Path delays are defined in specify blocks. Unit and zero delays replace any distributed and path delays, and may result in faster simulation, but at the expense of realistic delay information. By default a simulator will choose the longest of the distributed delays and path delays. 342 Copjright c 1995-2006 by Ooutoo ll<l
  • 342. ' begin_keywords Compiler Directives The "begin_keywords and ·end_keywords directives may be used to modify the list of keywords within a section of SystemVerilog source code. ..,.. The version "1800-2005" was introduced in SystemVerilog " begi n keywords Version _ SourceCode · end_ keywords Version = (one ofl ( Verilog-1995 keywords } ( Verilog-2001 keyword s ) " 1361-1995" " 1 3 64 -2 0 0 1 " " 1 3 6 4 - 2 0 0 1 -noconfig" " 1 3 64-2005" ( Verilog-2001 keywords, except config etc. l ( Verilog-2005 keywords 1 ( SystemVerilog keywords 1 " 1800 -2005 " See Keywords for lists of the keywords in the different versions. Outside any design elements. The version specifies which keywords the SystemVerilog compiler recognises. • Implementations may have additional, proprietary version strings. Use appropriate version strings to compile legacy Veri log code with an uptodate Verilog or SystemVerilog compiler. Exam les p " begin_keywords " 1 3 6 4 -2 0 0 1 -noconf ig I I This module uses Verilog-2001 keywords, except those pertaining to I I configurations module design ; II design is a keyword in Verilog-2001 reg logi c ; II 1 ogle is a keyword in SystemVerilog endmodule Copyrighl c 1995-2006 by Doulos Ltd 343
  • 343. 'begln_keywords Compiler Directives ' end_keywords See Also Keywords 344 Coj))flghl C 199S.2006 by Oouloo Lid
  • 344. 'define Comp iler Directives 'define defines a text macro. Macros are substituted in the first phase of compilation. Macros can be used to improve the readability and maintainability of the SystemVerilog code where parameters or functions are inappropriate, or where they are not allowed. IJI.. ·•, ' and ·· are added in SystemVerilog 1 Declaration I ' de f i n e Namc [ ( Argumen l , . . . } } 1'exL ( Usage ) ' Name [ (Expression, . . . } ] Macros may be defined inside or outside modules. • Macro definitions, like all compiler directives. are active across file boundaries, unless overridden by a subsequent 'define, 'undef or 'reselall directive. There are no scope restrictions. When a macro is defined with arguments, the arguments may be used in the macro text, and are substituted with the actual argument expressions when the macro is used. ' define add ( a , b ) f - a · add ( 1 , ?. ) ; + b I I f = 1 + 2; ·define supports strings as macro arguments. Macro definitions may span several lines, by escaping the intermediate newlines with a backslash (). The newlines are part of the macro text. Macro definitions may also include to allow macro arguments to be included in strings. If a string has to contain " , the macro text should be written · " · " , · Macro definitions may also include a double back tick · , to allow identifiers to be constructed from arguments. There must be no space between the parentheses, or it will be treated as macro text. · ' define pref ix_add ( f ) f ' · s u f f i x p r e f i x add (Prefix) • II Becomes: Prefix_suffix The macro text may not split the following language tokens: comments. numbers. strings. names, reserved names, operators. Copyright c 1995-2006 by Ooulos Lid 345
  • 345. 'define Compiler Directives Compiler directives are not allowed as macro names. • Gotchasl Macros with arguments are not supported by all implementations. • Once defined, a macro is used by prefacing the name with a backwards apostrophe ('). The macro name without the apostrophe is a separate identifier. • Be careful to distinguish the backwards apostrophe (') from the inverted comma (') which is used in numbers. Do not end a macro definition with a semicolon, unless you really do want a semicolon substituted when the macro is used. Otherwise you will probably get a syntax error when the macro is used. Parameters or enums are often preferable to macros for giving meaningful names to literals. Macros with arguments can usually be simulated more efficiently than functions having the same functionality. The 'include directive may be followed by a macro, instead of a literal string. • ' de f i n e ' i ncl ude Path "/home/afile" " Path Exam les p This example shows how to use text macros to select different implementations of modules in an hierarchical design. This is useful during synthesis, when it may be necessary to simulate a mixture of RTL and synthesized gates for a design. " de fine SUBBLOCKl subblockl_r t l " de f i n e SUBBLOCK2 subblock2 rtl ' de f i ne SUBBLOCK3 subblock3_g a Lcs module TopLevel . . . " SUBBLOCKl subl insL (. . .) ; ' SUBBLOCK2 sub2_inst ( . . . ) ; " S UBBLOCK3 sub3 i n s t ( ...); endmodulc 346 Cql)Tl!)hl 0 1995-2006 by Doulos Lid.
  • 346. Compiler Directives 'define This example shows a text macro with arguments. ' define nand(delay) nand # (delay) · nand (3 ) · nand ( 4 ) (f,a,b) ; (g, f, c ) ; See Also 'ifdef, Localparam Cop)Tfghl C> 1995-2006 by OouJos Lid 347
  • 347. ' ifdef Compiler Directives Conditionally compiles SystemVerilog code, depending on whether or not a specified macro is defined. ' i fdef MacroNamc Sys temVeri l ogCode . . . . .] . . . . . . ] . . ] [ ' cl s i f MacroNamc SystemVeril ogCode . [ ' el s e SystemVerilogCode . ] ' cnd.if ' ifndef MacroName SysLemVcri logCode . [ ' elsif MacroName SystemVeri logCode . [ ' e l se Sys temVerilogCode . ' endi f Anywhere. • If the macro name has been defined using 'define, the first block only of SystemVerilog code is compiled. • If the macro name is not defined, and an 'else directive is present, the second block only is compiled. • These directives may be nested. Any code that is not compiled must still be valid SystemVerilog code. Can be used, for example, to switch between alternative implementations of a module, or to selectively turn on the writing of diagnostic messages. 348 CopyrightCl 1 995·2006 by OO<Jioo Lid
  • 348. Compiler Directives "ifdef Exam les p " defi ne pr imitiveModel modul e Testl ; " i f de f primiLiveModel MyDes ign_primi Lives UUT ( . . . ) ; "else MyDesign_RTL U U T ( . . . ) ; ·endif endmodule Example of chained nested conditional directives module TesL2; ' i fdef Bl ockl ' i f ndef Block2 i n i t i al $display ( "Blockl is defined" ) ; 'else init i a l Sdisplay ( "Blockl and Rlock2 de fined" ) ; 'endif ' e l s i f Block3 i n i t ial $display ( "Block3 defined, Block! i s not " ) ; 'else i n i t ial $display ( "Block ! , 13lock3 not dellned . " ) ; 'endi f endmodule See Also "define Ccpl"ijht c 1995-2006 by Doolos Ltd 349
  • 349. pragma Compiler Directive s Used to alter the interpretation of the SystemVerilog source code. The only pragmas specified by the Verilog-2005 standard concern protected envelopes, which are used to encrypt SystemVerilog source code. Encryption envelopes fall outside the scope of the SystemVerilog Golden Reference Guide. pragma [ PragmaExpress i ons . . . ) Name PragmaExpression � { one of} PragmaKcyword PragmaKeytvord � Pragma Va l ue Pragma Value Pragma Value = [one of} ( PragmaExpressions, . . . ) Number S t ri n g Name Anywhere The effect of pragmas is implementation-dependent, except for than those defined in the Verillog-2005 standard relating to protected envelopes, and the reset and resetall pragmas. • Pragmas that are not recognised by a particular implementation have no effect. Exam les p ' pragma resetall ' pragma proLect en codi ng= ( e nc cype= " uuc ncode " ) 350 Copyright c 1995·2006 by Doutos Lta
  • 350. Compiler Directives 'timescale Defines the time unit and simulation precision (smallest increment). · L ime scale TimeUni L I PrecisionUni L TimeUni t , Preci s i onUni t - TimeNumbcr Uni t TimeNumber - (one of} 1 1 0 J O O Uni t = (one of} s ms us ns ps f s <HERE>-module • The precision unit must be less than or equal to the time unit. The precision for a simulation run is the smallest of all the precision units in 'timescale directives and timeprecision declarations. Gotchasl The 'timescale directive, like all compiler directives, affects all the code that follows in lhe compilation unit, until the next 'timescale or ·resetall. 'timescale doesn't affect the time unit of the compilation unit scope, only of modules etc. without timeunit and timeprecision declarations. Time is followed without a space by a time unit. • Use timeunit and time precision in preference to 'timescale. Include a 'timescale directive at the top of every module, even if there are no delays in the module, because some simulators may require this. Exam les p ' Limescale lOns I lps See Also Compilation Unit, Timeunit, $timeformat Copynglit0 t99S-2006 by Doulos Ltd. 351
  • 351. (' I r � { (' (
  • 352. SystemVeri log GOLDEN REFERENCE GUIDE System Tasks and Functions /�DOULOS
  • 353. System Tasks and Functions The SystemVerilog language includes a number of useful system tasks and functions. These can be enabled and called in the same way as user defined tasks and functions. They are guaranteed to be available in any tool that conforms to the IEEE Verilog standard. The SystemVerilog LRM also mentions a number of other, commonly found system tasks and functions, which are not actually part of the standard, but may be found in some implementations. Note that Verilog simulators from different vendors may include additional, proprietary system tasks and functions. Users can add their own user defined system tasks and functions using the Programming Language Interface (PLI). All system task and system function names, including user defined ones, begin with a dollar character, to distinguish them from ordinary tasks and functions. There follows a summary of all the system tasks and functions mentioned in the LRM. More detailed information for some of the more important of these follows this summary. ..,. A number of new system tasks and functions were added in SystemVerilog Standard S stem Tasks and Functions y The following system tasks and functions are part of the IEEE standard. $display, $monitor, $strobe, $write etc. A whole family of system tasks to write text to the standard output or one or more files. For full details see the separate articles, $display and $write. $monitor etc., and $strobe. $fopen and $fclose Sfopen ( "F ileName" ) ; S f close (Mcd) ; ( Returns an integer} $fopen is a system function to open a text file for writing. $fclose closes a file that was opened with $fopen. For full details, see the separate article. $readmemb, $readmemh, $writememb and $writememh $readmemb ( " Fi le " , Ar:rayName [ , SLartAddr [ , FinishAddr] J ) ; $readmemh ( " F i le " , ArrayName [ , StartAddr [ , Finishllddr ) ] ) ; $wri Lememb ( "Fi le " , ArrayNamc [ , Sta rtAddr [ , rinishAddr ] I ) ; $wri tememh ( " File" , A rrayName [ , StarlAddr [ , FinishAddr ) ] ) ; Tasks to initialize or dump the contents of a memory array from or to a text file. For full details, see the separate articles. $timeformat Stimeformat [ (U n i t s , Precision, S u f f i x , MinFlcldWidth) J ; 354 Copyrighl 0 1995-2006 by Doulos Lid
  • 354. System Tasks and Functions Defines the format for writing simulation time with $display etc. For full details, see the separate article. $printtimescale $ p r i n t l imesca l e [ (Moduleinstan ceName 1 ) ; Displays the lime unit and precision for a module in the following format: 'l'imc scale of (Modu leins tanccName) is unit I precision . If no argument is given, the time unit and precision for the module that called $prinltimescale are displayed. $exit $exit [ ( ) 1 ; Causes the calling program block to finish. Ail processes spawned by the program are terminated. When ail programs have finished, simulation stops. $stop $slop ( (N) ) ; { N is 0, 1 , or 2 ) Causes simulation to suspend. The optional argument determines the type of diagnostic output produced. 0 gives the least amount, 1 gives more, and 2 gives the most amount of output. $finish $finish [ (N) 1 ; ( N is 0, 1 , or 2 J Causes the simulator to exit, passing control back to the operating system. If an argument is supplied, diagnostic messages are printed as follows: 0 - prints nothing 1 - prints simulation time and location (this is the default if no argument is supplied). 2 - prints simulation time and location, and statistics about the memory and CPU time used in the simulation. $time, $stime, and $realtime $ t i me ; Sslime; $realtime; System functions to return the current simulation time. The time returned has the units of the module from which the system function was called, as defined by 'timescale or the timeunil. $time returns a 64 bit unsigned value, rounded to the nearest unit. $slime returns a 32 bit unsigned value, truncating large time values. COpydg c 1995-2006 by Daub> Ltd. ht 355
  • 355. System Tasks and Functions $realtime returns a real number. Note that unlike any other functions in SystemVerilog, these functions have no inputs. $realtobits, $bitstoreal, $shortrealtobits, $bitstoshortreal $real tob i ls (Rea l Expressi on ) ( Returns 64 bits 1 $bi tslorea1 ( B i t Va l ucExp ression) ( Returns real 1 $ s ho r t r:eal L ob i ts ( Rea1Expressi on) ( Returns 32 bits 1 ( Returns shortreal 1 $bitstoshortreal {Bi tVa1 ueExprcssion) Convert between a real number and a bit level representation, so that a real number can be passed through the port of a module. (Ports cannot be declared as real). For an example, see Module. $rtoi and $itor $ r l o i ( Rea1Expression) ( Returns an integer 1 $ i t o r ( IntegerExpression) 1 Returns a real number) Convert between a real number and an integer. $rtoi truncates the real number to form the integer. $bits $bits ( Expression) $ b i L S { TypeNamt!) Returns the number of bits required to hold a value. A 4-state value counts as one bit. Example: logic (15 : 0] V; V_NumB i ts - $b i t s { V ) ; I I V_NumBits = 1 6 $isunbounded $ i s u nboundcd ( Co n s t a n tExpres s i o n ) $isunbounded returns true if the expression is unbounded (i.e. a parameter that has the value $). Typically, $isunbounded would be used as a condition in the generate statement. $cast $cas t { Variable , Expression) Casts an expression and assigns the resulting value to a variable. Variable is the variable to which the assignment is made and Expression is the expression. $cast may be called either as a task or as a function. As a task, a runtime error occurs if an invalid cast is attempted. As a function, $cast returns 1 for a legal cast, and 0 otherwise. 356 Ccpyn<Jilt0 1995-2006 by Doolos lt�
  • 356. System Tasks and Functions Example: Lype dc f ( Red , Amber, Green} J, iCJhtColour; Ligh LCol o ur Light; $cast ( Light , 1+2) ; I I Light = 1+2 is illegal $typename S typename (Expression) $typcname (TypeName) $typename retruns a string that represents the underlying name of the type of the expression or the type name. Examples: I I "logic" I I "logic signed[7:0)" I I "bit" l ogi c a ; l og i c s i g n e d [ 7 : 0 ] a_byte; typedef biL Boolean; i n t s ig ne d Y ; package A; enum (A, B, C=4 ) X; endpackage : A I I "int" I I "enum{A=32'd0,B=32'd1 ,C='32d4}A: :e$ 1 " $type of S L ypco f (Exprcs s i o n ) S t ype o f ( TypeName ) $typeof returns the type of its argument. This can be used to defined a type parameter or lor comparing types. The actual value returned by $typeof is not available to the user. Example: logi c [ 1 5 : 0 ] 1d d rB u s ; parameLer type Addr_t SLypeof (AddrBus ) ; $signed/$unsigned $ s i gncd (Expressi on ) S u n s igned ( Expre s s i o n ) These two system functions handle type casting on expressions. They evaluate the input expression and return a value with the same size and value of the input expression and the type defined by the function. $test$plusargs and $value$plusargs S L e s L $plusargs (String) $val u c Sp l usa r gs ( UscrString, Copyright c 1995-2006 by Dooloo ltd Va ri a b l e ) 357
  • 357. System Tasks and Functions Information for use in simulation may be specified using a command to invoke the simulator. This information is in the form of an optional argument provided to the simulation, starting with the plus (+) character. $test$plusargs searches the list of plusargs for the provided string, in the order provided. If the prefix of one of the supplied plusargs matches all characters in the provided string, a non-zero integer is returned. If no plusarg from the command line matches the string provided, 0 is returned. $value$plusargs searches the list of plusargs for a user-specified plusarg string. This string may be a string or a reg. If the string is found, the remainder of the string is converted to the UserString type and the resulting value stored in the Variable provided. The function returns a non-zero integer. If no string is found matching, the function returns zero and the var iable provided is not modified. The UserString has the form:"PiusargString FormatString ". The format strings are the same as in the $display system tasks. System Tasks and Functions for File Input-Output $fgetc, $ungetc and $fgets $fget c ( fd) Reads a byte from the file specified by fd. If an error occurs reading from the file, then returns EOF (-1 ). Define the width of the reg to be wider than 8 bits so that a return value from $fgetc of EOF (-1) can be differentiated from the character code OxFF. $ungelc ( c , fd) Inserts the character specified by c into the buffer specified by file descriptor fd The character c shall be returned by the next $fgetc call on that file descriptor. The file itself is unchanged. Operations like $fseek might erase any pushed back characters. If an error occurs pushing a character onto a file descriptor, then it returns EOF. Otherwise it returns zero. $ fg c t s ( st.c, fd) Reads characters from the file specified by fd into the reg str until either str is filled, or a newline character is read and transferred to str or an EOF condition is encountered. If sir is not an integral number of bytes in length, the most significant partial byte is not used in order to determine the size. It returns zero, If an error occurs. Otherwise it returns the number of characters read (type integer). $fscanf, $sscanf $ fs c a n f ( fd, forma L , Argume n t , . . . ) $sscanf ( s tr, format , 1rgumen L , . . . ) $fscanf reads from the files specified by the file descriptor fd. $sscanf reads from the reg or string str. Arguments specify where to place the results. If there are insufficient arguments for the format, the behaviour is undefined. If in excess, the 358
  • 358. System Tasks and Functions excess arguments are ignored. Both tasks return the number of successfully matched and assigned input items (type integer). For full details on format specifiers, see $display entry below. If the format string, or the sir argument to $sscanf contains unknown bits (x or z), then the system task shall return EOF. $fread Sfread (MyReg, fd) S f rea d (t-1cmoryName , fd) $ f read (MemoryName, [d, $£read Sta rtAddr) (NcmoryNamc, fd, StartAddr, $£read (MemoryName, fd, , Count) Count) Reads a binary data from the file specified by fd into the reg MyReg or the memory MemoryName. For full details, see below. $ftell, $fseek and $rewind S f tell ( fd) $£seek (Id, Offset, Opera t i on ) Srewind ( fd) $ftell returns the offset from the beginning of the file or the current byte of the file fd which shall be read or wrillen by a subsequent operation on that file descriptor. This value may be used by subsequent $fseek calls to reposition point. If an error occurs EOF is returned. the file to this $fseek sets the position of the next input or output operation on the file specified by fd. The new position is set according to an operation value of 0,1 and 2 as follows: 0 set position equal to Offset bytes 1 set position to current location plus Offset 2 set position to EOF plus Offset $rewind is equivalent to $fseek (fd, 0, 0); Any repositioning cancels any $ungetc operations. $fseek()allows the file position indicator to be set beyond the end of the existing data in the file, in case data is later wrillen at this point. Subsequent reads of data in the gap will return zero until data is actually wrillen into the gap. $fseek by itself does not extend the size of the file. When a file is opened for append, it is impossible to overwrite information already in the file. $fseek can be used to reposition the file pointer to any position in the file, but when output is wrillen to the file, the current file pointer is disregarded. All output is wrillen at the end of the file and causes the file pointer to be repositioned at the end of the output. Col>lnghl 0 1995-2006 by Ocutos ltd. 359
  • 359. System Tasks and Functions If an error occurs repositioning the file, $fseek and $rewind return -1 .0therwise they return 0. $fflush Sf flush (Mcd) S f flush ( fd) S f flush ( ) Writes any buffered output to the file(s) specified by Mcd or fd. If $ffiush is invoked with no arguments, writes any buffered output to all open files. $ferrer $ fe r ro r ( fd, str) Returns the integral value of the error code, when a string is written into sir. Sir should describe the type of error encountered by the most recent file 1/0 operation, and it should be at least 640 bits wide. If the most recent operation did not result in an error, then the returned value will be zero, and the reg sir will be cleared. $feof Sfeof ( fd) Returns non-zero if end of file has previously been detected for the file fd. Otherwise returns 0. PLA Modelling Tasks A number of system tasks are provided to model PLAs. $async$and$array (MemoryName, { I nputs, . . . } , {Outputs, . . . } ) $asyncSnand$array (MemoryName, { Inputs , . . . } , {Outputs, . . . ) ) $async$or$arra y ( MemoryName, { I nputs, . . . ) , {Outpuls, . . . ) ) $async$nor$array (MemoryName, { I nputs , . . . ) , {OuLputs, . . . } ) Sasync$and$plane (MemoryName, { Inputs , . . . } , {Oulputs, . . . ) ) Sasync$nand$plane ( MemoryName, { Inputs , . . . ) , {Outputs, . . . } ) $async$or$plane (MemoryName, { Inpuls , . . . } , {OuLpuLs, . . . ) ) Sasync$nor$plane (MemoryName, { I nputs, . . . } , {OutpuLs, . . . }) $ s y nc$and$a rray (MemoryName , { I nputs , . . . } , {Oulputs, . . . ) ) $sync$nand$array (MemoryName, { I nputs, . . . } , { Outpuls , . . . ) ) $sync$or$array ( MemoryNamc , { Inpu ts , . . . ) , {Outputs, . . . } ) $ s ync$nor$array (MemoryName , { Inpu ls , . . . } , {Oulputs, . . . } ) $sync$and$plane (McmoryName, { Inputs, . . . } , (Outputs, . . . ) ) S s ync$ nand$plane (MemoryName , { Inputs , . . . } , { Output s , . . . ) ) $sync$or$plane (McmoryName, ( Inputs , . . . ) , (Outputs, . . . ) ) $sync$nor$plane (MemoryName, { I nputs, . . . ) , {Outputs, . . . ) ) The first argument of each of these tasks is the name of a memory array, which stores the personality of the PLA being modelled. The array should be declared 360 Cqlyrigt11 Q 1995-2006 by Doulos Lid
  • 360. System Tasks and Functions with ascending indices (e.g. reg [1 :Ninputs] Mem[1 :NOutputs]). The personality can be changed dynamically. The asynchronous tasks are analogous to procedural continuous assignments. The outputs are updated whenever one of the inputs changes, or if the personality is changed. The synchronous tasks only update the outputs when the task is called. Tasks for Stochastic Modelling Sq_i n it i a l i ze (q_id , q type , max_lengLh, sta t11s ) ; _ S q_a dd ( q_ i d, job _id, in £orm i d, _ s t a t us ) ; job_id, inform_id, Sq removc ( q i d , Sq_exam (q_id, status) ; { Returns an integer ) S q_ful l ( q i d, s t a t us) ; q s t a t_code, q stat_v a l u e , status ) ; Four system tasks and a system function to support stochastic modelling by enabling the creation and management of queues. For full details, see below. Random Number Generation Functions $random[ ( Seed) ) ; S u random [ ( Seed) I; S u r a ndom_range (MaxVal [ , S d l s l ch i_s quarc (Seed, Sdist_e r l a n g ( Seed, Mi n Va l J ) ; DegrccOfl-'reedom) ; K L age , Mea n ) ; _s S d i s L_exponenlla l ( Seed, S d l s t_normal ( Seed, SdlsL pois s on ( Sccd , S dis l_L ( Sccd, Mean, Mean ) ; StandardDevi a t i on ) ; Mean ) ; DegreeOfFreedom) ; $disL_u n i form ( Secd, Start, End) ; Each of these system functions, when called repeatedly, returns a sequence of pseudo random numbers, according to various probability distributions. The sequence will always be the same for the same starting seed. The C code underlying $random and other probabilistic system functions is given, thus ensuring that, given the same "Seed' , $random returns the same sequence of "random" numbers on different operating systems. Consult a text on statistics or probability theory for details of the distribution functions and their application. $random returns signed integer values. $urandom and $urandom_range return an unsigned integer value. The default minimum value is 0. These system functions value exhibit random stability. Math Functions $clog2 ( n ) Copyrlghl 0 1995.2006 by llou1os Lid. 361
  • 361. System Tasks and Functions Returns the ceiling (rounded up value) of the log base 2 of the argument, n. This can be used to calculate the minium address width needed to address a memory of a given size. The following functions accept real arguments and return a real result. They are equivalent to the corresponding functions in the C programming language. $1 n ( x ) S log lO ( x ) Scxp ( x ) Ssqrt (x) $pow ( x , y) $ floor ( x ) $ce i l ( x ) $ s i n (x) $cos (x) Stan ( x ) $asj n ( x ) $aco:; (x) $atan ( x ) $atan2 ( x , y) $hypot ( x , y) $ s i nh ( x ) Scosh ( x ) $tanh ( x ) $asinh ( x ) Sacosh ( x ) Salanh ( x ) Specify Block Timing Checks $hold ( RcferenceEven t , DataEvent , Limit [ , Notifier] ) ; Snochange ( ReferenceEvent , Da LaEven t, StartEdgeOffse t , EndSdgeOffse t [ , Notifier] ) ; $period (ReferenceEve n t , Limit [ , Notifier] ) ; $recovery ( RcferenceEvcn t , DataEven t , Limi t [ , Noci ficr] ) ; $:;etup ( DataEven t , ReferenccEvenr., r.imi t [ , Notifier] ) ; S s c Luphold (ReferenceEven t, DataEven c , Set upLimi t, HoldLimi t [ , Notifier] ) ; $ s kew ( ReferenceEven t , DaLaEvent , Limit: [ , Notifier] ) ; $width ( HeferenceEven t , Limit [ , Threshold [ , Notifier] J ) ; Special system tasks to perform common timing checks. These system tasks may only be called from specify blocks. For full details, see below. Value Change Dump Tasks $dumpfi l e ( " Fi leName" ) ; $dumpvars [ (Leve1s, ModuleOrVariabl e , . . . ) ] ; $dumpoff; $dumpon; $dumpa l l ; $dumplimit (FileSize) ; $dumpflush; A family of system tasks to store value changes in a Value Change Dump (VCD) file. A VCD file is a means of passing simulation stimulus or results to another program, for example a graphical waveform viewer. For full details, see below. Assert Control System Tasks ( one of) $as sertklll ; $assertk i l l (Levels [ , ModuleOrAssertions, . . . ] ) ; $as sertoff ; 362 CopiTighl 0 199>2006 by Ooulos ltd
  • 362. System Tasks and Functions Sasserto ff ( Levels [ , ModuleOrAssert ion, . . . ]); S asse rLon ; Sasscrton ( Levels [ , ModuleOrAssertion , Modul eOrAsser ti on . . . ]) ; (one of} = ModulcName Asserti onName Hierarch i cal Name Levels is the number of levels of hierarchy affected, with 1 meaning the specified levels of hierarchy only, and 0 meaning the specified levels, and all instances below. If no arguments are given, all the assertions in the design are affected. $assertkill aborts execution of any currently executing specified assertions and then stops the checking of all specified assertions, until a subsequent $asserton. $assertoff stops the checking of all specified assertions until a subsequent $asserton. An assertion that is already executing is not affected. $asserton re-enables the execution of all specified assertions. Assertion System Functions {one of} S isun known ( Expression) ; SonehoL (Exprcssi on) ; SonehotO ( 1-:xpression) ; These system functions facilitates assertion functionality. They access the values of signals at the time of evaluation of the boolean expression, All functions above return a bit type. 1'b1 indicates true, 1'b0 indicates false. $isunknown returns true if any bit of the expression is X or Z. $onehot returns true if one and only one bit of expression is high. $onehot0 returns true if one and only one bit of expression is low. Scountones ( expression) ; $countones counts the number of 1 s in a bit-vector expression. The X and Z values of a bit are not counted. Sampled Value System Functions ( one of) $sampled ( Expression I , ClockingEven L ) ) ; Srose ( expression ( , ClockingEvcn L ) ) ; Sfell ( Expressi on [ , Cl ockingEven t ) ) ; Sstablc ( Expression ( , ClockingEven L ] ) ; $past (Expressi on [ , NumberOfTi cks) [ , [ , Cl o cki ngEven t ) ) ; eopynght 0 1995-2006 by DOUios Ltd Expressi on2 ) 363
  • 363. System Tasks and Functions These functions are used to access the sampled values of an expression, including values in the past. $rose, $fell and $stable are used to detect changes in sampled values. The clocking event must be explicitly specified as an argument, or i nferred from the code where it is used. if used in an assertion, the appropriate clocking event from the assertion is used: • if used in an action block of a singly-clocked assertion, the clock of the assertion is used. • if used in a procedural block, the inferred clock, if any, for the procedural code is used. Otherwise, default clocking is used. $sampled returns the valued of the expression on the last clock event, or 'x before the first clock event. $rose, $fell and $stable detect changes in values between two adjacent clock ticks. The return value for all three functions is true or false and can be used as a boolean expression. At the first clock tick after the assertion is started, the functions compare the current value to 'X'. $rose returns true if the least significant bit of the expression changed to 1 . $fell returns true i f the least significant bit of the expression changed to 0. $stable returns true if the value of the expression did not change. $past accesses past values of the Expression. NumberOfTicks specifies the number of clock ticks in the past (it defaults to 1 ). Expressions2 is a clock gate expression. $past returns the sampled value of the expression that was present NumberOfTicks prior to the time of evaluation of $past. If NumberOfTicks is before the start of the simulation, $past returns 'x. Example: a lw a ys @ (posedge clock} previous q - $pa s L ( q , , enable) previous_q will contain the value of q on the previous posedge clock i f f enable . Assertion Severity System Tasks {one of) Sfata l ; $ [aLa l (Fini shNum [ , Messagellrguments, . . .]}; $error ; $error (MessageArgumcnts, . . . ) ; $warn ing ; $warning (MessagcArguments , . . . } ; 364 Copl'flght o 1095-2006 b1 Ooulos Ltd
  • 364. System Tasks and Functions $ i n fo ; S i n fo (MessageArgumen Ls , . . .) ; Fini shNum - I one of) 0 1 2 Messagellrqument - {one of) S t r i ng Expression Assertions have a severity level associated with any assertion failures detected. The default severity is "error". The severity levels may be specified by including one of the tasks above in the assertion fail statement. All these tasks print a tool-specific message, indicating the severity of the failure, and specific information about the failure, which may include: File name and line number of the assertion statement Hierarchical name of the assertion, or the scope of the assertion The simulation run-time at which the task is called (for simulation tools) The FinishNum argument of $fatal must match the corresponding argument of $finish system task. $info indicates that the assertion failure carries no specific severity. Array Querying System Functions tone of) Sdime n s i ons ( A rrayName ) Sdimen s i on s ( I n tegerTypeNamc) Sunpacked_dimensions (ArrayName) $unpacked_dimen s i o n s ( I n l cgerTypeName) Expression ] ) Shigh (ArrayName [ , $ i n c rement (Arra yNarnc [ , Expressi on) ) S s i ze { ArrayName [ , Slow ( A r rayNamc [ , Expression) ) Expressi on ) ) S l c f L !ArrayNarne [ , Express i on ] ) $ rig h t ( ArrayName [ , Expression ] ) These system functions return information about an array. For fixed-sized arrays, they are constant functions, so can be used to initialize parameters. The default value of the optional Expression is 1. $1efV$right return the MSB and the LSB respectively, of the dimension expression. $low/$ high return the minimum and the maximum, respectively, of $left and $right of the dimension. $increment returns 1 if $left >= $right, and - 1 if $left < $right. $size returns the number of elements in the dimension. (The function was called il $length in SystemVer og 3.1 ) Copyughl 0 1g95-2000 by Doulo• Lid. 365
  • 365. System Tasks and Functions $dimensions returns the number of dimensions in an array or array type, 1 for the string type or any non-array type that is equivalent to a simple bit vector type (such as integer) or 0 for a scalar object. $unpacked_dimensions is similar to $dimensions, but only counts the unpacked dimensions. The dimensions of an array are numbered as follows: the slowest varying dimension is 1 , and successively faster dimensions have sequentially higher dimension numbers. Example: II Dimension numbers II reg 3 [7:0) 1 4 [15:0] llnArray [ 0 : 7 ) 2 [0 : 15 ] ; If an out-of-range dimension is specified, these functions will return a logic X. The array-querying system functions also work on associative arrays with integral index types, dynamic arrays and queues, and return information about the current state of the array. It is an error to use them on a dynamically sized type identifier or an associative array with a non-integral index type. For associative arrays, the functions returns these values: $left returns 0; $right returns the highest possible index value. $low and $high return the lowest and highest currently allocated index values respectively. $increments returns -1 . $size returns the number of elements currently allocated. Coverage System Functions Sset_coverage db name ( Fi l eNamc ) $load coverage_db ( Fi l eName) Sget_covcrage ( ) $set_coverage_db_name sets the name of the file into which the simulator writes coverage data. $1oad_coverage_db loads cumulative coverage information from the specified file. $get_coverage returns the overall coverage value as a percentage. This is a real number, calculated from the overall coverage of all coverage group types. (SystemVerilog also includes a number of built-in coverage access system functions, which are part of the Coverage API. These are outside the scope of this Guide.) 366 Copynght o 1995-2006 by Dootos Ltd
  • 366. System Tasks and Functions y Non-standard S stem Tasks and Functions The following system tasks and functions are mentioned in the LRM, but are not part of the IEEE standard. Some of these tasks and functions concern the "interactive mode" of a SystemVerilog simulator. If a simulator supports an interactive mode of operation, it may accept these tasks and functions as commands. $countdrivers Scountdrivers ( Ne t , [ IsForccd, NoOfDri vers, NoOfDri versToO, NoOfDri versTol , NoOfDri vcrsToX] ) ; System function to show the number of drivers on a specified scalar net or bit select of a vector net. Drivers include outputs of primitives and continuous assignments, but not an active force. $countdrivers returns 0 if the net has no more than one driver, and 1 otherwise. All the arguments, except the first, return integer values. IsForced returns 1 if the net is forced, and 0 otherwise. NoOfDrivers returns the number of drivers. The remaining arguments return values which add up to NoOfDrivers. $list Slist [ (Modulelnstance) ] ; Called interactively to list the source code for the current scope, or a specified scope in the design. $input S i npu L ( " FileName " ) ; Reads interactive commands from a text file. $scope and $showscopes Sscope (ModuleinsLancc) ; Sshowscopc s [ (N) ] ; Interactive commands to set the current scope and show the scopes in the current scope, and below (if N is present, and is non-zero). $key, $nokey, $log and $nolog Sk.ey[ ( "FileName" ) ] ; Snokey; S l og [ ( " Fi leName " ) J ; Snolog; eopynghl o 1995-2006 by Doulos Lid 367
  • 367. System Tasks and Functions The "key" file records commands that are entered interactively. The "log" file records all messages that are written to the standard output during a simulation run. $nokey and $nolog disable recording. With no argument, $key and $log re­ enable recording. With a file name argument, they create new files. $reset, $reset_count and $reset_value $rese t ( (StopValue ( , ResetVa l uc [ , DiagnosticsValue) ) ) ; ( Returns an integer) $reset count; $reset_value; ( Returns an integer) $reset resets a simulator so that simulation can restart from the beginning. A StopValue of 0 means that the simulator resets in its interactive mode, allowing the user to start and control simulation. A non-zero value means that simulation will automatically restart from the beginning. ResetValue can be read by the $reset_value function. • Diagnostics Value specifies the kind of messages the tool displays before resetting. $reset_count returns the number of times $reset has been called. $reset_value returns the value passed to $reset. $save, $restart and $incsave $save ( " Fl l eName" ) ; $ i ncave ( " FileName" ) ; $resLart ( " FileName " ) ; $save saves the complete state of the simulation to a file, so that it can be read using $restart. $incsave saves only what has changed since the last call to $save. $restart resets the simulation from a full or incremental save file. For an incremental save, the previous full save file must be present: it is referenced in the incremental save file. $showvars $sh01�vars I (NetOrVariable, . . .)]; Displays the status of nets and variables on the standard output. This task is used interactively. The status information displayed is not defined in the LRM. It might include the current values of nets and var iables, any scheduled events on those nets and variables, and the drivers of the nets. If no list of variables is given, information is displayed for all the nets and variables in the current scope. 368 Copy<;ght C 1995-2006 by Doulos Lid.
  • 368. System Tasks and Functions $getpattern $geLpatter n ( MemoryEJ emen t ) ; $getpattern is a system function which may only be used in a continuous assignment. The left hand side of the continuous assignment must be a concatenation of scalar nets. $getpattern is used together with $readmemb and $readmemh to apply test vectors from a text file. $getpattern provides fast processing when there are large numbers of scalar inputs involved. $sreadmemb and $sreadmemh ; $sreadmemb (Memory, StartAddr, FinishAddr, String, . . .) $sreadmcmh (Memory, Sta rtAddr, FinistJAddr, Slring, . . .); These tasks are similar to $readmemb and $readmemh, except that the memory is initialized from data supplied in one or more character strings rather than from files. The format of the character strings is the same as that of the corresponding text files for $readmemb and $readmemh. $scale $scale ( DclayName ) ; ( Returns realtime} Converts a time value in one module to the time units of the module from which $scale is called. $scale takes a hierarchical reference to a delay value, such as a parameter in another module, and scales it to the time units of the module from which it was called. Copyright C t99S.2006 by Doulos Ltd. 369
  • 369. $cast System Tasks and Functions Used to assign an expression of a one data type to a variable of a different type that would otherwise be illegal. $cast can be called as a task or as a function. ..,.. This feature was added in SystemVerilog function i n t $cast ( si ngular DcstVariable, singu l a r SourceExpression ) ; task $cast ( singular DescVariable, s i ngular SourceExprcssi on ) ; See Expression. $cast assigns the SourceExpression to the Des/Variable. • If $cast is called as a task and the assignment is invalid, a runtime error occurs and Des/Variable is left unchanged. If $cast is called as a function, it returns 1 if the cast is legal. If the assignment is invalid, Des/Variable is left unchanged.and returns 0. Gotchasl The difference between using $cast and the static SystemVerilog cast operation is that the static cast does not provide for error checking or warn if the expression lies outside the valid range of values that can be assigned to the Des/Variable. Still, the static compile-time cast is faster. Exam les p typedcf enum { A , B , C, ABCD Letter; $cast ( Le L L c r , 1 +1 ) ; D } ABCD; I I Equivalent to r.eLLer - IIDCD ' ( l +1 ) ; 1 1 Check if the assignment is legal i f ( ! $cast ( Letter, 1 + 4 ) ) I I S: invalid cast $displ a y { "Casting Error" ) ; See Also Casting 370 Copynght C> t99S.2006 by Doutos ltd.
  • 370. System Tasks and Functions $display and $write Writes formatted text to the standard output and the simulator log, to a file, or to a reg variable. $display (Argumen t , . . . ) ; $ fdlsplu y ( Mcd, Argument, . . . ) ; $write ( Argumen t , . . . ) ; $fwri te (Ned, Argumen t , . . . ) ; $swrile ( O u tputReg0rString, Argument, . . . ) ; $ s format ( Outpu tRcg, format, Argument, . . . ) ; Mcd • = { Integer value J l' xpression : The only difference between $display and $wr is that $display writes out ite, a newline character at the end of the text. whereas $write does not. The only difference between $swrite and $fwrite is that the first parameter to $swrite is a reg variable to which the resulting string shall be written, instead of a variable specifying the file to which to write the resulting string. $sformat is similar to $swrite. with one major difference: it always interprets its second argument and only its second argument as a format string. This format argument can be a static string or a reg variable. $sformat supports all the format specifiers supported by $display. Arguments may be strings or expressions, or blank (two adjacent commas). Format arguments - except for $sformat - must be string literals, not expressions of SystemVerilog's string type. • Strings to be written may contain format specifiers (see below). If so, each string must be followed by enough expressions to provide values for all the format specifiers in the string (except %m). Strings may also include the following escaped characters: In Newline It Tab " Double quote Back slash nnn ASCII value of character (octal) Copyright c 1995-2006 byDoulos Lid, 371
  • 371. System Tasks and Functions $display and $write • Unknown and high impedance values are written as follows. Note that for octal and hexadecimal numbers, one digit represents either 3 or 4 bits, respectively. For decimal numbers, unknown and high impedance values are written as one digit. • • • Lower-case x or z means all the bits represented by the digit are unknown. Upper-case X or Z means that some, but not all, of the bits represented by the digit are unknown. If an argument list contains two adjacent commas, a space is wr itten out at that point. Format S ecifiers p • The following format specifiers are allowed in strings: %b %B Binary o/oo %0 Octal %d %D Decimal %h %H Hexadecimal %e %E %f %F %g %G Real %c %C Character %s %S String %v %V Binary and Strength %t %T Time %m %M Hierarchical Instance %u %U Unformatted 2 value data %z%Z Unformatted 4 value data %1 %L Display library binding information • %v prints strengths as follows: supply - Su, strong - St, Pull - Pu, Large ­ La, Weak - We, Medium - Me, Small - Sm, Highz - Hi. %v also prints the values H and L (these are printed as X with %b) • A minimum field width value may be included after the % character (e.g. %10d). For decimal numbers, leading zeroes are replaced by spaces, but 372 COpjrightO t995·2006 by Doolos Ltd.
  • 372. System Tasks and Functions $display and $write for other radixes, the leading zeroes are printed. A minimum field width of 0 means that the field will always be just big enough to display the value. The format specifiers for real numbers (%e . %f and %g) have the full formatting capabilities available in the C programming language. For example %1 0.3g specifies a minimum field width of 10, with 3 digits following the decimal point. Expressions that are not written using a format specifier are written in decimal format. There are additional tasks which have different default formats, for example $displayb, $fwriteo and $displayh write out numerical expressions as binary, octal and hex values respectively when a format specifier is not used. Exam les p $display ( " Illegal opcode h in %m a L % t " , Opcodc, $realtime ) ; $wri Lch ( "Variable values (hex . ) : " , rcg l , , reg2 , , reg 3 , , reg4, " n " ) ; See Also $monitor, $strobe Copyright0 1995-2006 by llouJos ltd 373
  • 373. $open and $close System Tasks and Functions $fopen is a system function to open a file for writing, and $fclose is a system task to close a file. Text is written to the files using the system tasks $fdisplay, $fmonitor etc. S ntax y 1 Returns an integer} $fopen ( " Fi leName " ) ; $ fc l o s e (Mcd) ; Mcd = Expression $fopen ( " FileNamc " , ModeArgumenL r - ! Integer value 1 ModeArgumen L , [b] , f+] ) ; {one of} { Read mode} w 1 Write a f Append mode } model See Statement. • Up to 31 files may be opened at once, although the maximum may be lower, depending on the operating system. • When the function $fopen is called, it returns a 32-bit multichannel descriptor that is associated with the file, or 0 if the file could not be opened for writing. • The multichannel descriptor can be thought of as 31 flags, each representing a separate file (channel). Bit 0 is associated with the standard output, bit 1 with the first opened file, bit 2 with the second opened file etc. When a file output system task such as $fdisplay is called, the first argument is a multichannel descriptor, which specifies where to write the text. The text is written in each file whose flag is set in the multichannel descriptor. To allow existing output routines (e.g. $fdisplay) to work with traditional multichannel descriptors (MCDs) as well as new file descr ors, bit 31 of ipt the MCD is reserved. The optional character b can be used to treat the file as binary (ignored by Unix); the optional character + indicates that the file can be both read and written. 374 Copyright 0 1995-2006 by Doutos Ltd
  • 374. System Tasks and Functions $open and $close Exam les p integer Mcssagcsfi le , DiagnosLics Fi l e , All Files ; initial begin MessagesFi le = Sfope n ( "messages . tx t" ) ; i f ( ! �1essagesF" i l c ) begin Sdisplay ( "Co u l d not open " messages . Lx L " " ) ; $finish; end DiagnosLicsFile $ [opcn ( "diagnos t i cs . LxL" ) ; i f ( ! Diagnoslicsfi l e ) begin Sdispla y ( "Could not open "diagnoslics . txt " " ) ; $finish; end • AllFiles - McssagesFi l e I DiagnosLicsFi l e I 1 ; Sfdi spl ay (Allfiles, "Starting simulation . . . " ) ; Stdisplay (Messagcsfil e , "Messages [rom %m" ) ; S fdispla y ( DiagnosticsF"i l e , "Diagnostics from %m" ) ; S fclosc (Messagesfile ) ; S f c lose ( Diagnos LicsFi le ) ; end fd = $ fopen ( " f ilc _name" , rb+) ; I I open for update (reading and I I writing) See Also $display, $monitor, $strobe Copyright Cl t9952006 by Ooulos ltd 375
  • 375. $tread System Tasks and Functions Reads a binary data from a file into a variable or a memory. $ f read (MyReg, fd) ; $fread (MemoryName, £d) ; $ E read (MemoryName, fd, StarLAddr) ; $fread (MemoryNamc, fd, S t a r tAddr, Coun t ) ; $fread ( MemoryName, .[d, , Coun t ) ; StartAddr is the address of the first element in the memory to be loaded. It is optional. If not present, the lowest numbered location in the memory is used. • Count is the maximum number of locations in MemoryName that is loaded. It is optional. If not supplied the memory shall be filled with what data is available. • StartAddr and Count are ignored if $fread is loading a reg. If no addressing information is specified within the system task, nor in the data file, then the default start address is the lowest address given in the declaration of the memory. Consecutive words are loaded towards the highest address until either the memory is full or the data file is completely read. • The data is read from the file in a big endian manner. The first byte read is used to fill the most significant location in the memory element. If the memory width is not evenly divisible by 8 (8, 16,24,32), not all data in the file is loaded into memory because of truncation. • It is not possible to read a value of X or Z using $fread. • If an error occurs reading from the file, then zero is returned. Otherwise the number of characters read is returned. Gotchasl The data in the file is read byte by byte. An 8-bit wide memory is loaded using one byte per memory word, while a 9-bit wide memory is loaded using 2 bytes per memory word. • There is not a binary mode and an ASCII mode. Binary and formatted read commands from the same file may be freely combined. $fread allows you to read unformatted two-valued (o/ou-style) binary data into a memory, just as $readmemb allows you to read formatted binary data into a memory. Therefore a file destined for use by $fread will be at least 376 C4>yng111 0 1995-2006 by Dautos Ltd.
  • 376. System Tasks and Functions $tread four times smaller than the corresponding $readmemb file (but not human­ readable!). Exam les p paramete r NumPa tterns integer Pattern; 100; reg [ 3 : 0 ] StimUp [ l : NumPatterns ] ; req [ 3 : 0 ] S t i mDown [NumPatterns : l ] ; Sfread ( StimUp, " ::; t imulus . txt " , 5 ) ; I I First loaded data I I is StimUp[S] then StimUp[6] S f read ( S L imDown, " s l imulus . tx t " , 5 ) ; I I First loaded data I I is StimDown[S] then StimDown[6] See Also $readmemb and $readmemh Cop�·0 199S.2006 by Doulos Lid. 377
  • 377. $monitor etc. System Tasks and Functions ites out a line of text whenever one or more of a specified list of nets or Wr variables changes value. Used in testbenches to monitor simulated behaviour. $mon i tor ( Argumen t , $fmonilor (Mcd, . . . ) ; Argumen t , . . . ) ; $monitoro f f ; { Turns monitor flag on 1 { Turns monitor flag off) Mcd = Expression { Integer value 1 $moni Loron ; The syntax of the arguments to these system tasks and the text they write is exactly the same as for the equivalent $display tasks. Only one $monitor process, and any number of $fmonitor processes can be running simultaneously. • A second or subsequent call to $monitor cancels any existing $monitor process, and replaces it with a new $monitor process. $monitoroff disables monitoring, $monitoron re-enables monitoring. $monitoron produces a display immediately, based on the current $monitor process, and whether or not a value change has taken place. There is no $fmonitor equivalent to $monitoron and $monitoroff The system functions $time, $slime and $realtime do not trigger a line of display from $monitor etc. or $fmonitor etc. Use $monitor in testbenches for obtaining simulation results from any compliant SystemVerilog simulator. Tasks used to create graphical displays of waveforms are usually simulator dependent. Exam les p initial $monilo r ( " 'll t a = 'lib, f % b" , $real Lime , a , f) ; See Also $display, $fopen, $strobe 378 Cop)1oghl 0 1995-2006 by Dwlos Ud.
  • 378. System Tasks and Functions $readmemb/h, $writememb/h Initializes (or dumps) an array with values from (to) a text file. The contents of the text file may be in binary format (for $readmemb or $wr itememb) or hexadecima l format (for $readmemh or $writememh) )II. $readmemblh were extended in SystemVerilog; $writememb/h were added in System Verilog { System task call 1 Sreadmemb ( " F i l e " , 1r rayName [ , S t artAddr ! , Fi ni sllAddr] ] Sreadmemh ( " Fi l e " , ArrayName ! , StartAddr ! , FinishAddr] ] Swri Lememh ( " F"i 1 e " , ArrayName ! , StartAddr [ , l·"ini shAddr] Swritememh ( " File" , ArrayName [ , StartAddr [ , Fi ni shAddr] ); ); ]) ; )); [ Text file} {one of} Whi teSpa ce lvhi teSpacc = Da taValue @Address tone of} Space Tab Newline Formfecd Data Va l ue - t one of] BinaryDi gi t . . . 1 Sreadmemb 1 1/cxDigi t . . . 1 Sreadmemh 1 Address - llcxDigit . . . The first argument is the name of an ASCII file. For $readmemb/h the file may contain only white space, SystemVerilog comments, (hex) address values and binary or hex data. $writememb/h does not write addresses (except for associative arrays) or comments The second argument is the name of an array. This may be an unpacked array, a dynamic array or an associative array with an integral index type. Any packed type is allowed, including enumerations. Data values must be the same width as the number of packed bits of each array element, and be separated by white space. They are read into successive memory locations, starting at the start of the array, or the start address, if specified. Data values continue to be read until the end of the file or the end address, if specified, is reached. For arrays with more than one unpacked dimension, the values are read in row-major order - i.e. the lowest (last) dimension varies most quickly. For arrays of a enumerated type, the data in the file corresponds to the enumerated value's data type (i.e. the default would be lnt) If the array is a two-valued type such as bit or int, X and Z values are treated as 0. Cop)Toghl C 199S.2006 by DouloS Ltd 379
  • 379. System Tasks and Functions $readmemb/h, $writememb/h • Address values are hexadecimal numbers (even for $readmemb and Swr itememb) preceded by @. When an address value is encountered by $readmemb, the next data word is read into that address . For arrays with more than one unpacked dimension, the address refers to the highest (first) dimension only. Addreess values are only written out be $writememb/h for associative arrays, when the index type must be integral. $readmemb and $readmemh provide a convenient way to initialize arrays, for example to model RAMs and ROMs. Exam les p module Test; reg a , b , c , d; parameter NumPatterns integer Pattern; 100; reg [ 3 : 0 ] Stimulus [ l : NumPatterns ] ; MyDesign UUT ( a , b, c , d, f) ; initial begin $readmemb ( "Stimulus . txt" , Stimulus ) ; Pattern - 0 ; repeat (NumPatterns) begin Pattern - Pattern + 1 ; ( a , b, c , d } = S t i mulu s [ Pattern ] ; #110; end end ini tial Smonl tor ( " lt a-lb b-%b c=%b -lb : f- b " , $realtime, a , b , c , d , f ) ; endmodulc 380 Copyrightc 1995-2006 by Doolos Lid
  • 380. System Tasks and Functions $root Not a system task, but the top level of the hierarchy .,.. This feature was added in SystemVerilog $root is used to refer unambiguously to a top-level instance. $ root In S stemVerilo 3.0 and 3.1 y g In SystemVerilog 3.1a and IEEE 1 800-2005, $root simply provides a way to refer unambiguously to a top-level instance. In SystemVerilog 3.0 and 3 . 1 , $root refers to the global name space, i.e. declarations outside any modules, interfaces etc. This concept was replaced by compilation units in SystemVerilog 3.1a. Exam les p $root . t1yModule . U l / / Absolute name See Also Instantiation, Module, Name, Compilation Unit, $unit Cop)11ghl0 1995-2006 by Doulos ltd 381
  • 381. $unit System Tasks and Functions Not a system task, but used to access identifiers in the compilation unit scope. � This f eature was added in SystemVeri/og $unit is used to refer unambiguously to names that are declared in a compilation unit, outside of any packages, modules etc. Exam les p $ u n i t . scmi_global sig I I Compilation unit name See Also Name, Compilation Unit, $root 382 Copyngt>l C 1995-2006 by Oouloa Lid.
  • 382. $strobe System Tasks and Functions Prints a formatted line of text at the end of a lime step, once all events at that lime have been processed. $sLrobc (Argument, . . . ) ; $fstrobe (Mcd, Argumen t , . . . ) ; Mcd = Expression { Integer value ) • The syntax of the arguments to these system tasks and the text they write is exactly the same as for the equivalent $display tasks. • $strobe only prints the text when all activity at the time at which it was called has completed. This includes the effects of all blocking and nonblocking assignments. Use $strobe in preference to $display or $write when writing simulation results. This guarantees that the steady values of the strobed nets and variables will be wr itten. Exam les p initial begin a - 0; $display ( a ) ; I I Displays 0 $strobe ( a ) ; 1 1 Displays 1 a - 1; I 1 ... because of this statement See Also $display, $monitor, $write Copyrlgtot C t995-2006 by Douloo Lid 383
  • 383. $timeformat System Tasks and Functions Defines the format for printing simulation time. $1imeformat is used in conjunction with the format specifier %1. $ t imeformat [ (Units, • Preci s i on, Suffix, MinFieldiVidLh) ] ; Units is an integer between 0 and -15 which indicates the units in which times are to be printed: 0 means seconds, -3 means milliseconds, -6 microseconds, -9 nanoseconds, -12 picoseconds and - 1 5 femtoseconds. Intermediate values may also be used: for example -10 means 100 ps units. Precision is the number of decimal digits to be printed after the decimal point. Suffix is a string that is printed after the time value. MinFieldWidth is the minimum number of characters to be printed, including leading spaces. If more characters are required, more will be printed. The defaults, if no arguments are specified, are as follows. Units: the simulation precision; Precision: 0; Suffix: null string; MinFieldWidth: 20 characters. Use 'timescale, $timeformat and $realtime (with %t) to specify and display simulation times using $display, $monitor, or one of the other display tasks. Exam les p SLime format ( - 1 0 , 2, " xlOOps " , 20) ; I I 20.12 x1 00ps Sea Also 'timescale, $display 384 COpy!lght () 1995-2006 by Ooutos Ltd,
  • 384. System Tasks and Functions Stochastic Modelling SystemVerilog provides a set of system tasks and functions to support stochastic modelling by enabling the creation and management of queues. Sq_initialize ( q_id, q_ type, max_ lcngth, sta t us ) ; $q_add (q_id, job id, inform i d , status) ; Sq_remove ( q id, job_ i d , i n foL·m_ i d , s t a t u s ) ; { Returns an integer} $q_exam (q_id, q_stat code, cLstat value, status ) ; Sq_full ( q _id, s t a t us ) ; See Statement. General Comments All arguments to these system tasks and functions are integers. • Each of these system tasks and functions returns a status integer, which has one of the following values: 0 - Okay 1 - The queue is full: can't add the job ($q_add) 2- Undefined q_id 3 - The queue is empty: can't remove the job ($q_remove) • 4- Unsupported queue type: can't create the queue ($q_initialize) 5 Maximum length is zero or less: can't create the queue ($q_initialize) - • 6 - Duplicate q_id: can't create the queue ($q_initialize) 7 - Insufficient memory: can't create the queue ($q_initialize) Sa Initialize Creates a queue. • q_id (output) is a unique queue identifier, which is used to refer to that queue when calling the other queue tasks and functions. q_type (input) is either 1 for a first-in, first-out (FIFO), or 2 for last-in, first­ out (LIFO) queue. Cq>ynght 0 199�2006 by Doulos ltd 385
  • 385. Stochastic Modelling System Tasks and Functions max_length (input) is the maximum number of entries that are allowed in the queue. Adds an entry to a queue. q_id (input) indicates to which queue to add the entry. job_id (input) identifies the job. This is usually an integer that is incremented by the user each time an element is added to the queue, and can be used to identify the element when it is removed. • inform_id (input) is used to associate information with the queue entry. Its meaning is user defined. $g remove Gets an entry from a queue. • q_id (input) indicates from which queue to remove the entry. job_id (output) identifies the job (see $q_add). • inform_id (output) is the value stored by $q_add. Checks to see if a queue is full. The returned value is 1 when the queue is full, and 0 when it is not. $g exam Requests statistics about a queue. The times referred to in the following descriptions are based on when elements are added to the queue (arrival time), and the difference in time between when an element was added and when it was removed (wait time). The unit of time is the simulation precision. q_stat_code (input) indicates the information requested: 1 - Current queue length • 2 - Mean inter-arr ival time • 3 Maximum queue length - 4 - Shortest wait time ever 5 - Longest wait time for jobs still in the queue • 386 6 Average wait time in the queue. - Copyrighl c 199S.2006 by Doulos Lid
  • 386. System Tasks and Functions Stochastic Modelling q_stat_value (output) returns the requested information. Exam les p module Queues; parameter Queu e � 1 ; I I Q_id parameter r i fo = 1 , Li fo 2; parameter QueueMaxLen - 8 ; integer Status, Code, Job, Value, Info; reg IsFu l l ; = t a s k Error; I I Write error message and quit endtask i n itial begin I 1 Create the queue Sq_inilialize (Queue, l.i fo, QueueMaxLcn, Slalus ) ; i f ( Status ) Error ( "Couldn ° t initi a l i ?.e the queue" ) ; I I Add jobs for (Job - 1 ; Job <= QueueMaxLen; Job - Job + 1 ) begin 1 1 0 I n f o = Job + 1 00 ; $q add (Queue, Job, Info, Status) ; if ( Status ) Error ( "Couldn ° L add to the queue " ) ; Sdispl a y ( "Added Job % 0d, Info = % 0 d " , Job, In fo) ; Swrile ( "Statistics : " ) ; for ( Code - 1 ; Code <= 6 ; Code = Code 1 1 begin Sq_exam (Queue, Code, Va l ue , Status ) ; i f ( Status ) �rror ( "Couldn ° L examine the queue" ) ; $write ( " %8d" , Value ) ; end Sdi splay ( o o o o ) ; end I I Queue should now be full r s Fu l l � Sq_ f u l l (Queue , Status ) ; ( Status ) if Copyright " 1995-2006 byDootos ltd 387
  • 387. System Tasks and Functions Stochastic Modelling Error ( " Couldn ' L see i f queue i s ful l " ) ; if ( ! IsE'ull ) Erro r ( "Queue is NOT fu ll " ) ; I I Remove jobs repeat ( 1 0 ) begin # 5 $q_remove (Queue , Job, Info, SLaLus ) ; i f ( Status ) Error ( "Couldn ' t remove from the queue " ) ; Sdisplay ( " Removed Job 'i.Od, Info = % 0 d " , Job, I n fo ) ; Swrite ( " Statistics : " ) ; for ( Code 1 ; Code <= 6 ; Code = Code + 1 ) begin $q_exam(Queue, Code, Value , SLatus ) ; i f I Status ) Error ( "Couldn ' L examine the queue " ) ; $write ( " %8d" , Value ) ; end $display ( " " ) ; end end end