2/8/13
SV/Guidelines | Verification Academy
Verification Academy
Search
Topics
Courses
Forums
Cookbook
More
Welcome Mrithyunjay
My Account +
Contact
Home / Cookbook / SV/Guidelines
SV/Guidelines
Page Links
API Reference
Glossary
Mentor Graphics SystemVerilog Guidelines
The SystemVerilog coding guidelines and rules in this article are based on Mentor's experience and are designed to steer users away from coding practices that result in SystemVerilog that is either hard to understand or debug. Please send any suggestions, corrections or additions to vmdoc@[Link] SystemVerilog Do's Use a consistent coding style - see guidelines Use a descriptive typedef for variables Use an end label for methods, classes and packages Use `includes to compile classes into packages Define classes within packages Define one class per file Only `include a file in one package Import packages to reference their contents Check that $cast() calls complete successfully Check that randomize() calls complete succesfully Use if rather than assert to check the status of method calls Wrap covergroups in class objects Only sample covergroups using the sample() method Label covergroup coverpoints and crosses
General Coding Style
Although bad coding style does not stop your code from working, it does make it harder for others to understand and makes it more difficult to maintain. Take pride in writing well-ordered and uniformly formatted code.
1.1 Guideline: Indent your code with spaces
Use a consistent number of spaces to indent your code every time you start a new nested block, 2 or 3 spaces is recommended. Do not use tabs since the tab settings vary in different editors and viewers and your formatting may not look as you intended. Many text editors have an indenting mode that automatically replaces tabs with a defined number of spaces.
1.2 Guideline: Only one statement per line
Only have one declaration or statement per line. This makes the code clearer and easier to understand SystemVerilog Don'ts and debug. Avoid `including the same class in multiple locations Recommended / Vral dfnto: / aibe eiiin lgceal; oi nbe lgccmltd oi opee; lgci_rges oi npors; / Saeet: / ttmns / (e nx Gieiefrt / Se et udln o h eueo bgnedpis s f ei-n ar / wt cniinlsaeet / ih odtoa ttmn s ) / / i(nbe= 0 feal = ) i_rges=1 npors ; es le i_rges=0 npors ; / Vral dfnto: / aibe eiiin lgceal,cmltd i_r oi nbe opee, np ors; ges / Saeet: / ttmns i(nbe= 0 i_rges= feal = ) npors 1 es i_rges=0 ; le npors ; Not Recommended Avoid placing code in $unit Avoid using associative arrays with a wildcard index Avoid using #0 delays Don't rely on static initialization order
1.3 Guideline: Use a begin-end pair to bracket conditional statements
This helps make it clear where the conditional code begins and where it ends. Without a begin-end pair, only the first line after the conditional statement is executed conditionally and this is a common source of errors. Recommended / Bt saeet e / oh ttmns x eue cniinly ctd odtoal: i( >0 bgn fi ) ei cut=cretcu on urn_o n; t tre =crett agt urn_a re; gt ed n Not Recommended
i( >0 fi ) cut=cretcut on urn_on; tre =crettre;/ Ti sa agt urn_agt / hs t tmn i eeue ucniinly eet s xctd nodtoal
1.4 Guideline: Use parenthesis in Boolean conditions
This makes the code easier to read and avoids mistakes due to operator precedence issues. Recommended Not Recommended
[Link]
1/8
2/8/13
/ Boeno cniinlepes / ola r odtoa xrsi o n i(A=)& ( >(*) | ( >( f(=B & B C2) | B (*2+))bgn D*)1) ei .. . ed n
1.5 Guideline: Keep your code simple
SV/Guidelines | Verification Academy
/ Boeno cniinl / ola r odtoa epeso xrsin i(=B& B>C2| B> fA= & * | D*+)bgn *21 ei .. . ed n
Avoid writing tricky and hard to understand code, keep it simple so that it is clear what it does and how so that others can quickly understand it in case a modification is required.
1.6 Guideline: Keep your lines to a reasonable length
Long lines are difficult to read and understand, especially if you need to scroll the editor to the right to read the end of the line. As a guideline, keep your line length to around 80 characters, break the line and indent at logical places.
fnto btd_opr(v_betrs umcmae cmae) ucin i ocmaeumojc h, v_oprr oprr; mu_e_tmrs; bssqie h_ i($atrs,rs)bgn f!cs(h_ h) ei umrpr_ro(d_opr" "atfie,cektp cmaaiiy) v_eoterr"ocmae, cs ald hc ye optblt"; rtr 0 eun ; ed n d_opr =sprd_opr(h,cmae)& (AD = [Link])& (WAA= [Link] & ocmae [Link] oprr & MDR = h_MDR & MDT = h_MDT) & (RA = [Link])& (OCD = [Link])& (PAE= [Link] & (RS = [Link]) MED = h_MED & MPOE = h_MPOE & MHS = h_MHS) & MEP = h_MEP & (RAA= [Link]; & MDT = h_MDT) educin d_opr nfnto: ocmae
Not Recommended
fnto btd_opr(v_betrs umcmae cmae) ucin i ocmaeumojc h, v_oprr oprr; mu_e_tmrs; bssqie h_ i($atrs,rs)bgn f!cs(h_ h) ei umrpr_ro(d_opr" "atfie,cektp cmaaiiy) v_eoterr"ocmae, cs ald hc ye optblt"; rtr 0 eun ; ed n d_opr =sprd_opr(h,cmae)& ocmae [Link] oprr & (AD = [Link])& MDR = h_MDR & (WAA= [Link] & MDT = h_MDT) & (RA = [Link])& MED = h_MED & (OCD = [Link])& MPOE = h_MPOE & (PAE= [Link] & MHS = h_MHS) & (RS = [Link])& MEP = h_MEP & (RAA= [Link]; MDT = h_MDT) educin d_opr nfnto: ocmae
Recommended
1.7 Guideline: Use lowercase for names, using underscores to separate fields
This makes it clearer what the name is, as opposed to other naming styles such as CamelCase which are harder to read. Recommended aifbi_crbaderr x_arcsoeor_ro Not Recommended Aiarccrbadro xFbiSoeorErr
1.8 Guideline: Use prefix_ and _postfix to delineate name types
Use prefixes and postfixes for name types to help differentiate between variables. Pre and post fixes for some common variable types are summarised in the following table: prefix/postfix Purpose _t _e _h _m _cfg _ap _group Used for a type created via a typedef Used to indicate a enumerated type Used for a class handle Used for a protected class member (See guideline 2.2) Used for a configuration object handle Used for an analysis port handle Used for a covergroup handle
1.9 Guideline: Use a descriptive typedef when declaring a variable instead of a built-in type
This makes the code clearer and easier to understand as well as easier to maintain. An exception is when the built-in type keyword best describes the purpose of the variable's type.
[Link]
2/8
2/8/13
SV/Guidelines | Verification Academy
/ Dsrpietpdffra2 btadosml: / ecitv yee o 4 i ui ape tpdfbt2:]adosml_; yee i[30 ui_apet
1.10 Guideline: Use the end label for classes, functions, tasks, and packages
This forces the compiler to check that the name of the item matches the end label which can trap cut and paste errors. It is also useful to a person reading the code.
/ Uigedlbl / sn n aes pcaem_k; akg ypg /.. /. casm_ls; ls ycas / .. / . fnto vi m_ucin) ucin od yfnto(; /.. /. educin m_ucin nfnto: yfnto ts m_ak ak yts; / .. / . edak m_ak nts: yts edls:m_ls ncas ycas edakg:m_k npcae ypg
1.11 Guideline: Comment the intent of your code
Add comments to define the intent of your code, don't rely on the users interpretation. For instance, each method in a class should have a comment block that specifies its input arguments, its function and its return arguments. This principle can be extended to automatically generate html documentation for your code using documentation tools such as NaturalDocs.
Class Names and Members
2.1 Guideline: Name classes after the functionality they encapsulate
Use classes to encapsulate related functionality. Name the class after the functionality, for instance a scoreboard for an Ethernet router would be named "router_scoreboard".
2.2 Guideline: Private class members should have a m_ prefix
Any member that is meant to be private should be named with a 'm_' prefix, and should be made local or protected. Any member that will be randomized should not be local or protected.
2.3 Guideline: Declare class methods using extern
This means that the class body contains the method prototypes and so users only have to look at this section of the class definition to understand its functionality.
/ Dsrpietpdf: / ecitv yees tpdflgc[10 rwsml_; yee oi 3:] a_apet tpdflgc[50 poesdsml_ yee oi 1:] rcse_apet / Casdfnto ilsrtn teueo etral dfndmtos / ls eiiin lutaig h s f xenly eie ehd: casadocmrs; ls ui_opes rn itieainlmt ad n trto_ii; rn btvld ad i ai; rn rwsml_ rwadosml; ad a_apet a_ui_ape rn poesdsml_ poesdsml; ad rcse_apet rcse_ape / fnto:nw / ucin e / Cntutr-iiilzsvld / osrco ntaie ai etr fnto nw) xen ucin e(; / fnto:cmrs_ape / ucin opessml / Apiscmrsinagrtmt rwsml / ple opeso loih o a ape / ipt:nn / nus oe / rtrs vi / eun: od etr fnto vi cmrs_ape) xen ucin od opessml(; / fnto:stnwsml / ucin e_e_ape / Stanwrwsml vle / e e a ape au / ipt: / nus / / rwsml_ nwsml a_apet e_ape / rtrs vi / eun: od etr fnto vi stnwsml(a_apetnwsml) xen ucin od e_e_aperwsml_ e_ape; edls:adocmrs ncas ui_opes fnto adocmrs:nw) ucin ui_opes:e(;
[Link]
3/8
2/8/13
SV/Guidelines | Verification Academy
vld=0 ai ; ieainlmt=$ispoesdsml_) trto_ii bt(rcse_apet; educin nfnto fnto vi adocmrs:cmrs_ape) ucin od ui_opes:opessml(; friti=0 i<ieainlmt i+ bgn o(n ; trto_ii; +) ei poesdsml[]=rwadosml[(*)1:i2] rcse_apei a_ui_ape(i2-)(*); ed n vld=1 ai ; educin cmrs_ape nfnto: opessml fnto vi adocmrs:e_e_aperwsml_ nwsml) ucin od ui_opesstnwsml(a_apet e_ape; rwadosml =nwsml; a_ui_ape e_ape vld=0 ai ; educin stnwsml nfnto: e_e_ape
Files and Directories
The following guidelines concern best practices for SystemVerilog files and directories.
File Naming
3.1 Guideline: Use lower case for file and directory names
Lower case names are easier to type.
3.2 Guideline: Use .sv extensions for compile files, .svh for `include files
The convention of using the .sv extension for files that are compiled and .svh for files that get included makes it easier to sort through files in a directory and also to write compilation scripts. For instance, a package definition would have a .sv extension, but would reference `included .svh files:
3.3 Guideline: `include .svh class files should only contain one class and be named after that class
This makes it easier to maintain the code, since it is obvious where the code is for each class.
3.4 Guideline: Use descriptive names that reflect functionality
File names should match their content. The names should be descriptive and use postfixes to help describe the intent - e.g. _pkg, _env, _agent etc.
`include versus import
3.5 Rule: Only use `include to include a file in one place
The `include construct should only be used to include a file in just one place. `include is typically used to include .svh files when creating a package file. If you need to reference a type or other definition, then use 'import' to bring the definition into scope. Do not use `include. The reason for this is that type definitions are scope specific. A type defined in two scopes using the same `include file are not recognised as being the same. If the type is defined in one place, inside a package, then it can be properly referenced by importing that package. An exception to this would be a macro definition file such as the 'uvm_macros.svh' file.
Directory Names
Testbenches are constructed of SystemVerilog UVM code organized as packages, collections of verification IP organized as packages and a description of the hardware to be tested. Other files such as C models and documentation may also be required. Packages shoudl be organized in a hierarchy.
3.6 Guideline: Each package should have its own directory
Each package should exist in its own directory. Each of these package directories should have one file that gets compiled - a file with the extension .sv Each package should have at most one file that may be included in other code. This file may define macros.
acpgs b_k.v acmco.v b_arssh
For a complex package (such as a UVC) that may contain tests, examples and documentation, create subdirectories:
acpgeape b_k/xmls acpgdc b_k/os acpgtss b_k/et acpgscacpgs b_k/r/b_k.v
For a simple package the subdirectories may be omitted acpgacpgs b_k/b_k.v
Sample File Listing
.acpgsc /b_k/r .acpgscacpgs /b_k/r/b_k.v
[Link]
4/8
2/8/13
.acpgscacmco.v /b_k/r/b_arssh .acpgscacevsh /b_k/r/b_n.v .acpgscacitraes /b_k/r/b_nefc.v .acpgscacdie.v /b_k/r/b_rvrsh .acpgscacmntrsh /b_k/r/b_oio.v .acpgscacsoeor.v /b_k/r/b_crbadsh .acpgscacsqec_tmsh /b_k/r/b_euneie.v .acpgscacsqecrsh /b_k/r/b_eune.v .acpgscacsqecssh /b_k/r/b_eune.v .acpgdc/ /b_k/os .acpgdc/b_srgiedc /b_k/osacue_ud.ox .acpgtss /b_k/et/ .acpgtss... /b_k/et/... .acpgeape/ /b_k/xmls .acpgeape//.. /b_k/xmlsa.. .acpgeape//.. /b_k/xmlsb.. .acpgeape//.. /b_k/xmlsc.. .tsbnh/aeie /etec1mkfl .tsbnh/bevs /etec1t_n.v .tsbnh/btps /etec1t_o.v .tsbnh/ets /etec1ts.v
SV/Guidelines | Verification Academy
Using Packages
3.7 Rule: Import packages to reference their contents
When you use a function or a class from a package, you import it, and `include any macro definitions. If you `include the package source, then you will be creating a new namespace for that package in every file that you `include it into, this will result in type matching issues.
ipr acpg:; mot b_k:* `nld "b_arssh icue acmco.v"
3.8 Rule: When compiling a package, use +incdir+ to reference its source directory
To compile the package itself, you use a +incdir to reference the source directory. Make sure that there are no hardcoded paths in the path string for the `included file.
vo +ndr$B_K/r acpgs lg ici+ACPGsc b_k.v
To compile code that uses the package, you also use a +incdir to reference the source directory if a macro file needs to be `included.
vo +ndr$B_K/r t_o.v lg ici+ACPGsc btps
To compile the packages, and the testbench for the example:
vi wr lb ok #CmieteQet UMPcae(o UMDbgitgain opl h usa V akg fr V eu nerto) vo +ndr$USAUMHM/r \ lg ici+QET_V_OEsc $USAUMHM/r/usaumpgs QET_V_OEscqet_v_k.v #CmieteVP(b adxz opl h I ac n y) vo +ndr./b_k/r \ lg ici+.acpgsc ./b_k/r/b_k.v .acpgscacpgs vo +ndr./y_k/r \ lg ici+.xzpgsc ./y_k/r/y_k.v .xzpgscxzpgs #CmieteDT(T) opl h U RL vo ./u/u.v lg .dtdts #Cmietets opl h et vo +ndr./etpgsc\ lg ici+.ts_k/r ./etpgscts_k.v .ts_k/r/etpgs #Cmietetp opl h o vo t_o.v lg btps #Smlt iuae vi -v=eu -oeae+V_ETAEts \ sm umdbg cvrg UMTSNM=et - t_o -o"u -l;qi -" c btp d rn al ut f
SystemVerilog Language Guidelines
[Link] 5/8
2/8/13
4.1 Rule: Check that $cast() has succeeded
SV/Guidelines | Verification Academy
If you are going to use the result of the cast operation, then you should check the status returned by the $cast call and deal with it gracefully, otherwise the simulation may crash with a null pointer. Note that it is not enough to check the result of the cast method, you should also check that the handle to which the cast is made is not null. A cast operation will succeed if the handle from which the cast is being done is null.
/ Hwt cekta a$athswre crety / o o hc ht cs a okd orcl fnto m_betgtacoeumojc t_ecoe) ucin yojc e__ln(v_bet ob_lnd; m_bett yojc ; i($att t_ecoe.ln()bgn f!cs(, ob_lndcoe) ei `v_ro(gtacoe,"cs fie frt_ecoe" umerr"e__ln" $at ald o ob_lnd) ed n i( = nl)bgn ft = ul ei `v_aa(gtacoe,"cs oeainrsle i anl hnl,cekt_ecoe hnl" umftl"e__ln" $at prto eutd n ul ade hc ob_lnd ade) ed n rtr t eun ; educin gtacoe nfnto: e__ln
4.2 Rule: Check that randomize() has succeeded
If no check is made the randomization may be failing, meaning that the stimulus generation is not working correctly.
/ Uigi( t cekrnoiainrsl / sn f) o hc admzto eut i([Link]( wt {drs isd {o3'F0_C0}} bgn f!e_tmrnoie) ih ades nie [:2h00F0];) ei `v_ro(sqnm" "admzto fiue pes cekcntans) umerr"e_ae, rnoiain alr, lae hc osrit" ed n
4.3 Rule: Use if rather than assert to check the status of method calls
Assert results in the code check appearing in the coverage database, which is undesired. Incorrectly turning off the action blocks of assertions may also produce undesired results.
Constructs to be Avoided
The SystemVerilog language has been a collaborative effort with a long history of constructs borrowed from other languages. Some constructs have been improved upon with newer constructs, but the old constructs remain for backward compatibility and should be avoided. Other constructs were added before being proven out and in practice cause more problems than they solve.
4.4 Rule: Do not place any code in $unit, place it in a package
The compilation unit, $unit, is the scope outside of a design element (package, module, interface, program). There are a number of problems with timescales, visibility, and re-usability when you place code in $unit. Always place this code in a package.
4.5 Guideline: Do not use associative arrays with a wildcard index[*]
A wildcard index on an associative array is an un-sized integral index. SystemVerilog places severe restrictions on other constructs that cannot be used with associative arrays having a wildcard index. In most cases, an index type of [int] is sufficient. For example, a foreach loop requires a fixed type to declare its iterator variable.
srn nms*;/ cno b ue wt frah fn_ne,.. tig ae[] / ant e sd ih oec, ididx . srn nmsit; tig ae[n] .. . frah(ae[] oec nmsi) $ipa(eeet%d %"inmsi) dsly"lmn 0: s,,ae[];
4.6 Guideline: Do not use #0 procedural delays
Using a #0 procedural delay, sometimes called a delta delay, is a sure sign that you have coded incorrectly. Adding a #0 just to get your code working usually avoids one race condition and creates another one [Link], using a non-blocking assignment ( <= ) solves this class of problem.
4.7 Guideline: Avoid the use of the following language constructs
A number of SystemVerilog language constructs should be avoided altogether: Construct Reason to avoid checker final program Ill defined, not supported by Questa Only gets called when a simulation completes Legacy from Vera, alters timing of sampling, not necessary and potentially confusing
Coding Patterns
Some pieces of code fall into well recognized patterns that are know to cause problems
4.8 Rule: Do not rely on static variable initialization order, initialize on first instance.
The ordering of static variable initialization is undefined. If one static variable initialization requires the non-default initialized value of another static variable, this is a race condition. This can be avoided by creating a static function that initializes the variable on the first reference, then returns the value of the static variable, instead of directly referencing the variable.
[Link]
6/8
2/8/13
tpdfcasA yee ls ; tpdfcasB yee ls ; AatpA:e_(; _o=:gta) BbtpB:e_(; _o=:gtb) casA ls ; sai fnto Agta) ttc ucin e_(; i (_o = nl)atp=e(; f atp = ul _o nw) rtr ah eun _; educin nfnto edls :A ncas casB ls ; Aah _; poetdfnto nw rtce ucin e; ah=gta) _ e_(; educin nfnto sai fnto Bgtb) ttc ucin e_(; i (_o = nl)btp=e(; f btp = ul _o nw) rtr btp eun _o; educin nfnto edls :B ncas
SV/Guidelines | Verification Academy
Covergroups
4.9 Guideline: Create covergroups within wrapper classes
Covergroups have to be constructed within the constructor of a class. In order to make the inclusion of a covergroup within a testbench conditional, it should be wrapped within a wrapper class.
4.10 Guideline: Covergroup sampling should be conditional
Build your covergroups so that their sample can be turned on or off. For example use the 'iff' clause of covergroups.
/ Wapdcvrru wt sml cnrl / rpe oegop ih ape oto: casc_rpe etnsumcmoet ls gwapr xed v_opnn; lgc3:]ades oi[10 drs; btcvrg_nbe i oeaeeald cvrru dti_ru; oegop ealgop ADES cvron ad ifcvrg_nbe){ DRS: oepit dr f(oeaeeald bn lwrne={03'00_FF} is o_ag [:2h00FF]; bn mdrne={3'00_003'00_FF} is e_ag [2h0100:2h20FF]; bn hg_ag ={3'00_003'02_FF} is ihrne [2h2100:2h20FF]; } / .. / .. edru:dti_ru ngop ealgop fnto nwsrn nm ="gwapr,umcmoetprn =nl) ucin e(tig ae c_rpe" v_opnn aet ul; sprnwnm,prn) ue.e(ae aet; / Cntutcvrru adeal smln / osrc oegop n nbe apig dti_ru =nw) ealgop e(; cvrg_nbe =1 oeaeeald ; educin nfnto / Stcvrg eal bt-alwn cvrg t b ealddsbe / e oeae nbe i loig oeae o e nbe/iald fnto vi stcvrg_nbe(i eal) ucin od e_oeaeealdbt nbe; cvrg_nbe =eal; oeaeeald nbe educin stcvrg_nbe nfnto: e_oeaeeald / Gtcretsaeo cvrg ealdbt / e urn tt f oeae nbe i fnto btgtcvrg_nbe(; ucin i e_oeaeeald) rtr cvrg_nbe; eun oeaeeald educin gtcvrg_nbe nfnto: e_oeaeeald / Sml tecvrg gop / ape h oeae ru: fnto vi sml(oi[10 nwades; ucin od apelgc3:] e_drs) ades=nwades drs e_drs; dti_ru.ape) ealgopsml(; educin sml nfnto: ape
Coverpoint sampling may not be valid in certain situations, for instance during reset.
/ Uigift tr ofuncsaysmln: / sn f o un f neesr apig / Ol sml i rsti ntatv / ny ape f ee s o cie cvron dt ifrstn! 0 { oepit aa f(ee_ = ) / Ol itrse i hg_n vle i hg ps i eald / ny neetd n ihed aus f ih as s nbe: bn hg_n ={100200}ifhg_as; is ihed [00:00] f(ihps) bn lwed={130} is o_n [:0]; }
Collecting Coverage
4.11 Guideline: Use the covergroup sample() method to collect coverage
Sample a covergroup by calling the sample routine, this allows precise control on when the sampling takes place.
4.12 Rule: Label coverpoints and crosses
Labelling coverpoints allows them to be referenced in crosses and easily identified in reports and viewers.
[Link]
7/8
2/8/13
pyodsz_vt cvron .. ala_iecp: oepit . Labelling crosses allows them to be easily identified
SV/Guidelines | Verification Academy
pyodsz__aiy cospyodsz_vt prt; ala_ieXprt: rs ala_iecp, aiy
4.13 Guideline: Name your bins
Name your bins, do not rely on auto-naming.
bnmnmmvl={i} i iiu_a mn;
4.14 Guideline: Minimize the size of the sample
It is very easy to specify large numbers of bins in covergroups through autogeneration without realising it. You can minimise the impact of a covergroup on simulation performance by thinking carefully about the number and size of the bins required, and by reducing the cross bins to only those required.
Other SystemVerilog Guidelines Documents
Stu Sutherlands' SystemVerilog for Design Chris Spear's SystemVerilog for Verification Doulos' SystemVerilog Golden Reference Guide Adam Erickson's Are Macros Evil? DVCon 2011 Best Paper
Add New Comment
Type your comment here.
Login
Showing 0 comments
M Subscribe by email S RSS
Sort by popular now
Get PDF of this page
The Verification Methodology Cookbook content is provided by Mentor Graphics' Verification Methodology Team. Please contact us with any enquiries, feedback, or bug reports.
Mentor Graphics, All Rights Reserved
Verification Horizons Blog
Terms & Conditions Privacy Policy Academy LinkedIn Group
[Link]
8/8