├── DVCodingStyle.md ├── LICENSE ├── README.md └── VerilogCodingStyle.md /DVCodingStyle.md: -------------------------------------------------------------------------------- 1 | # lowRISC SystemVerilog Coding Style Guide for Design Verification 2 | 3 | This document is a supplemental Style Guide to the [lowRISC Verilog style 4 | guide](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md), 5 | with emphasis on writing code for Design Verification (DV) in SystemVerilog, 6 | following the [UVM methodology](https://www.accellera.org/images//downloads/standards/uvm/uvm_users_guide_1.2.pdf). 7 | 8 | ## Table of Contents 9 | 10 | * [Introduction](#introduction) 11 | * [Naming and Style](#naming-and-style) 12 | * [Directory Structure and Packages](#directory-structure-and-packages) 13 | * [UVM Agent Directory Structure](#uvm_agent-directory-structure) 14 | * [UVM Env Directory Structure](#uvm_env-directory-structure) 15 | * [UVM Guidelines](#uvm-guidelines) 16 | * [Class Definitions](#class-definitions) 17 | * [UVM new functions](#uvm-new-functions) 18 | * [uvm_scoreboard usage](#uvm_scoreboard-usage) 19 | * [uvm_agent usage](#uvm_agent-usage) 20 | * [uvm_driver usage](#uvm_driver-usage) 21 | * [Macro Usage](#macro-usage) 22 | * [Guidelines for UVM library macros](#guidelines-for-uvm-library-macros) 23 | * [Guidelines for macros within dv_macros.svh](#guidelines-for-macros-within-dv_macrossvh) 24 | * [General macro use guidelines](#general-macro-use-guidelines) 25 | * [Typical gotchas with macro usage](#typical-gotchas-with-macro-usage) 26 | * [Factory](#factory) 27 | * [Configuration Mechanism](#configuration-mechanism) 28 | * [Sequences](#sequences) 29 | * [Sequence Items](#sequence-items) 30 | * [RAL Usage](#ral-usage) 31 | * [Objections and Coordinating End of Test](#objections-and-coordinating-end-of-test) 32 | * [Logging and Print Messages](#logging-and-print-messages) 33 | * [DPI and C Connections](#dpi-and-c-connections) 34 | * [SystemVerilog Language Features](#systemverilog-language-features) 35 | * [Function Declarations](#function-declarations) 36 | * [Randomization](#randomization) 37 | * [Enums](#enums) 38 | * [Interfaces, Clocking Blocks, Modports](#interfaces,-clocking-blocks,-modports) 39 | * [Loop Operators](#loop-operators) 40 | * [Code Within Asserts](#code-within-asserts) 41 | * [Wait and Fork](#wait-and-fork) 42 | * [Wait And Non-Forever Loop](#wait-and-non-forever-loop) 43 | * [Void Casts](#void-casts) 44 | * [Associative Arrays](#associative-arrays) 45 | * [Bind Statements](#bind-statements) 46 | * [Simulator Specific Code](#simulator-specific-code) 47 | * [Forbidden System Tasks and Functions](#forbidden-system-tasks-and-functions) 48 | * [Backdoor Force and Probe in Chip-level](#Backdoor Force and Probe in Chip-level) 49 | * [SystemVerilog Assertions](#systemverilog-assertions) 50 | 51 | ## Introduction 52 | 53 | This guide defines the Comportable style for DV-specific SystemVerilog code. The 54 | goal is to use this common set of guidelines when implementing testbenches using 55 | the UVM methodology to allow all developed Comportable DV code to be uniform, 56 | reusable, and portable. 57 | This document assumes previous experience and working knowledge of UVM, and 58 | as such all included code snippets will be fairly concise. 59 | 60 | 61 | ## Naming and Style 62 | 63 | Refer to [lowRISC Verilog naming 64 | conventions](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md#naming) 65 | for any general naming style guidelines. In general, common UVM testbench 66 | components must be declared and assigned handles as follows: 67 | 68 | | Testbench component | Style | 69 | | --------------------------------- | -------------------------------------------- | 70 | | Virtual interfaces | `virtual _if _vif;` | 71 | | Environment | `_env env;` | 72 | | Env level config object | `rand _env_cfg cfg;` | 73 | | Env coverage collection object | `_env_cov cov;` | 74 | | Agent | `_agent m__agent;` | 75 | | Agent level config object | `rand _agent_cfg m__agent_cfg;` | 76 | | Agent coverage collection object | `_agent_cov cov;` | 77 | | Driver | `_driver driver;` | 78 | | Monitor | `_monitor monitor;` | 79 | | Scoreboard | `_scoreboard scoreboard;` | 80 | | Virtual sequencer | `_virtual_sequencer virtual_sequencer;` | 81 | | Sequencer | `_sequencer _sequencer;` | 82 | 83 | Additional naming guidelines: 84 | 85 | 1. The top level testbench file that instantiates the DUT must be named `tb.sv`. 86 | The testbench module must be named `tb`, and the instance name of the DUT in 87 | `tb.sv` must be `dut`. Using this standardized naming allows universal usage 88 | of any supporting DV sources (coverage cfg files, and so on). 89 | 2. When instantiating any objects, the `name` argument to `type_id::create()` 90 | must match the name of the variable being assigned to. 91 | This ensures that any reporting messages refer to the right objects. 92 | 3. To avoid name collisions, it is recommended that global types and types defined 93 | within a package have unique prefixes. This includes typedefs, enumerated 94 | types/values, package parameters, package localparams, any functions/tasks, and 95 | macros. This prefixing is not necessary for any types defined within a class, 96 | module, or interface, as they will be scoped by the parent entity. 97 | 4. Note that all package variables (parameters, etc.) must have a specified type. 98 | 5. When instantiating a user-defined class member variable that is a class object, 99 | it is recommended (but not necessary) to follow this prefixing scheme: 100 | * Prefix the instance name of the class object with `m_`, as such: 101 | 102 | ```systemverilog 103 | my_animal m_my_animal; 104 | ``` 105 | 106 | This scheme does not apply to any class member variables that are 107 | not themselves class objects. 108 | 109 | * If multiple instantiations of the class are desired without an array 110 | to store them, use ` m_` to declare a variable, 111 | and use an informative instance name. 112 | 113 | ```systemverilog 114 | my_animal m_my_cat; 115 | my_animal m_my_dog; 116 | my_animal m_my_fish; 117 | ``` 118 | 119 | * If an array of class handles or `logic` is desired, choose a name such 120 | that it follows one of the following schemes: 121 | 122 | ```systemverilog 123 | int NUM_ANIMALS = 10; 124 | // This plural convention is recommended, but both are equally acceptable 125 | my_animal m_my_animals[NUM_ANIMALS]; 126 | my_animal m_my_animal_array[NUM_ANIMALS]; 127 | ``` 128 | 129 | 130 | ## Directory Structure and Packages 131 | 132 | Define one class per file, and the filename should match the name of the class. 133 | The class files must be `` `include``-ed into the package file. 134 | Directory structure of the UVM agent and UVM environment testbench components 135 | along with their related files are shown below, with some additional guidance on 136 | declaring functions from a package context. 137 | 138 | 139 | 140 | 141 | ### `uvm_agent` directory structure 142 | 143 | * All DV code for a particular agent will be placed under a single directory 144 | `_agent/` separate from the DV code for the corresponding environment. 145 | * It is highly recommended that all agent directories be placed in a common area 146 | to create a repository of UVM agents that allows for more vertical reuse. 147 | 148 | ```systemverilog 149 | _agent/ 150 | _if.sv 151 | _item.sv 152 | _agent.sv 153 | _agent_pkg.sv 154 | _agent_cfg.sv 155 | _agent_cov.sv 156 | _driver.sv 157 | _host_driver.sv (Only if block requires a separate driver for host mode) 158 | _device_driver.sv (Only if block requires a separate driver for device mode) 159 | _monitor.sv 160 | _sequencer.sv 161 | seq_lib/ 162 | _base_seq.sv 163 | ``` 164 | 165 | 166 | ### `uvm_env` directory structure 167 | * All DV code for the UVM environment, UVM tests, and top level block 168 | testbench will be placed in a directory `/dv/` in three corresponding 169 | subdirectories `/dv/env/, /dv/tests/, /dv/tb/`. 170 | * The `_env_pkg` should import the `_agent_pkg`. 171 | * All UVM virtual sequences for a given DUT will be placed under `env/seq_lib/`, 172 | along with a `_vseq_list.sv` file that `` `include``-es all of the virtual 173 | sequence files. This virtual sequence list file must be `` `include``-ed by 174 | `env/_env_pkg.sv`. 175 | * If applicable, `env/_env_pkg.sv` must import the `_agent_pkg`. 176 | * `tests/_test_pkg.sv` must import the `_env_pkg` package. 177 | * All files `` `include``-ed into a single package must be in the same single directory. 178 | 179 | ```systemverilog 180 | /dv/ 181 | env/ 182 | _env.sv 183 | _env_pkg.sv 184 | _env_cfg.sv 185 | _env_cov.sv 186 | _scoreboard.sv 187 | _virtual_sequencer.sv 188 | seq_lib/ 189 | // These allow basic functionality to be added to the environment 190 | _base_vseq.sv 191 | _sanity_vseq.sv 192 | tb/ 193 | tb.sv 194 | tests/ 195 | _base_test.sv 196 | _test_pkg.sv 197 | ``` 198 | `_agent_pkg.sv, _env_pkg.sv, _test_pkg.sv, and tb/tb.sv` 199 | must include these `` `include``-es and imports: 200 | 201 | ```systemverilog 202 | `include "dv_macros.svh" 203 | `include "uvm_macros.svh" 204 | import uvm_pkg::*; 205 | ``` 206 | 207 | An example environment level package file for an arbitrary block `newblock` should look similar to this: 208 | 209 | ```systemverilog 210 | package newblock_env_pkg; 211 | // dep packages 212 | import uvm_pkg::*; 213 | import newblock_agent_pkg::*; 214 | 215 | // macro includes 216 | `include "uvm_macros.svh" 217 | `include "dv_macros.svh" 218 | 219 | // define any parameters 220 | parameter int NEW_BLOCK_PARAMETER = 10; 221 | 222 | // define any local types/functions/tasks 223 | typedef enum bit { 224 | NewblockBooleanZero, 225 | NewblockBooleanTrue 226 | } newblock_boolean_e; 227 | 228 | // Functions declared within packages must be automatic 229 | function automatic bit newblock_test_function(newblock_boolean_e test_boolean); 230 | //function definition 231 | endfunction 232 | endpackage 233 | ``` 234 | 235 | 236 | ## UVM Guidelines 237 | 238 | Always call `run_test()` without the test name argument. This allows command 239 | line test overrides to be performed using `+UVM_TESTNAME=` without 240 | having to recompile and allows testlists to be created for regression runs. 241 | 242 | 243 | ### Class Definitions 244 | 245 | 1. After variable declarations, register any objects and components with the 246 | factory using the `uvm_component_utils` and `uvm_object_utils` macros. 247 | * Declare any member variables to be registered with the UVM factory field 248 | automation macros `uvm_field_int, uvm_field_enum, uvm_field_object, 249 | uvm_field_array_int`, etc. within `uvm_object/component_utils_begin` and 250 | `uvm_object/component_utils_end`. 251 | 2. For all field automation macros, use `UVM_DEFAULT` as the flag argument. 252 | For example, if it is desired that everything except comparing and printing 253 | be enabled for some `rx_delay` field, the macro would look like this: 254 | 255 | ```systemverilog 256 | `uvm_field_int(rx_delay, UVM_DEFAULT | UVM_NOCOMPARE | UVM_NOPRINT) 257 | ``` 258 | 259 | 3. After factory registration, a constructor must be defined. Use the 260 | `uvm_object_new` macro for UVM objects and the `uvm_component_new` macro for UVM components. 261 | Both of these macros are defined in `dv_macros.svh`. 262 | 4. Any constructors written manually should contain a call to 263 | `super.new(name [,parent])` as the first line. Any other lines in the 264 | constructor are optional. 265 | 5. Do not add any extra arguments to the constructor other than `name` and `parent`. 266 | 6. All objects should generally be instantiated in the `build_phase()` function 267 | for components, or in the beginning of the `body()` task for sequences, unless 268 | there is a good reason not to. 269 | This is to enable proper usage of `uvm_factory` overrides. 270 | 7. When extending any user-defined component class, `super._phase` 271 | must be called for every phase method that is being overridden. 272 | 8. Transaction classes are usually logical representations of the data 273 | communicated over one or more interfaces executing a particular protocol. 274 | These classes: 275 | * Should extend `uvm_sequence_item`. 276 | * Should contain only information that is relevant to the data being 277 | transmitted over an interface, and not to the means of transmit. 278 | * Should result in a legal transaction when randomized. 279 | 280 | 281 | ### UVM `new()` functions 282 | 283 | The `new()` function of any class derived from `uvm_object` must have the 284 | default value of its `name` argument set to `""`, since the default name 285 | argument will be set by `type_id::create()`. 286 | The `new()` function of any class not derived from `uvm_object` must not 287 | have default values set for its arguments. 288 | Examples: 289 | 290 | :+1: 291 | ```systemverilog 292 | // class derived from uvm_object with correct default value 293 | function new (string name = ""); 294 | super.new(name); 295 | endfunction : new 296 | 297 | // class derived from uvm_component with no default values 298 | function new(string name, uvm_component parent); 299 | super.new(name, parent); 300 | endfunction : new 301 | ``` 302 | 303 | :-1: 304 | ```systemverilog 305 | // Incorrect default value used for class derived from uvm_object 306 | function new(string name = "my_rand_seq"); 307 | super.new(name); 308 | endfunction : new 309 | 310 | // Incorrect because default values for class derived from uvm_component are provided 311 | function new(string name = "", uvm_component parent); 312 | super.new(name, parent); 313 | endfunction : new 314 | ``` 315 | 316 | 317 | ### `uvm_scoreboard` usage 318 | 319 | Use `uvm_tlm_analysis_fifo` - can be directly connected to analysis ports, 320 | and has an unbounded size so that writes will always succeed without blocking, 321 | in situations where transactions need to be stored for some time before being 322 | consumed by the scoreboard for processing. 323 | 324 | 325 | ### `uvm_agent` usage 326 | 327 | 1. Interface agents should contain only a sequencer, driver, monitor, and config object. 328 | 2. Use one agent for every interface of the DUT, with an optional sequencer and 329 | driver whose instantiation is determined by the value of `.is_active`. 330 | This is placed in the agent config object to allow for better access throughout the testbench. 331 | 3. For any DUT interfaces that have multiple operation modes 332 | (such as host and device modes), two drivers should be created, one for each mode, 333 | and arbitration done in the `uvm_agent::build_phase` function to determine 334 | which driver to instantiate. 335 | Each driver should have different sequences that correspond to it. 336 | 337 | 338 | ### `uvm_driver` usage 339 | 340 | 1. A driver must only communicate with one sequencer on one SystemVerilog 341 | interface, and should not have any analysis ports. 342 | 2. A driver should not randomize any data received from transaction 343 | items sent through analysis ports. 344 | 3. A driver must assign `X` to any buses it controls during "don't-care" clock 345 | cycles in which no valid transaction is present. 346 | 347 | 348 | ### Macro Usage 349 | 350 | The UVM library provides several macros as shortcuts for commonly used sequences 351 | of code. In addition to this, the provided `dv_macros.svh` file defines other 352 | utility macros for even more common code sequences. 353 | 354 | #### Guidelines for UVM library macros 355 | 356 | 1. All lowercase `` `uvm_... `` expressions denote library macros, and do not 357 | require trailing semicolons. 358 | 2. `uvm_object_*` and `uvm_component_*` macros 359 | * Use these macros to register classes with the `uvm_factory`. 360 | 3. `uvm_field_*` macros 361 | * Use these macros for members of sequence items. While these macros 362 | implement expensive versions of common functions required for sequence items, 363 | the overhead is generally not worth implementing custom versions 364 | for every sequence item. Additionally, these macros add a great deal of 365 | readability and help avoid coding mistakes with custom implementations. 366 | Only implement custom versions of these macros if performance becomes a 367 | very noticeable issue. Do not use these macros with classes derived from `uvm_component`. 368 | 4. Do not use `uvm_do` macros. Instead, start sequence items on a sequencer 369 | using the following high level steps: 370 | * `start_item(, )`. 371 | * Randomize the sequence item. 372 | * `finish_item(, )`. 373 | * `get_response()`. 374 | 375 | #### Guidelines for macros within `dv_macros.svh` 376 | 377 | 1. UVM print macros - `gfn`, `gtn`, `gn`, `gmv` 378 | * These macros provide a concise wrapper for `get_full_name()`, 379 | `get_type_name()`, `get_name()`, and `uvm_reg.get_mirrored_value()`, respectively. 380 | By using these it is possible to drastically reduce line length 381 | and improve readability. 382 | 2. `downcast(, )` 383 | * Use this macro to cast a handle for any base class object that 384 | contains a handle to an extended class to the extended class type, useful 385 | for situations that require polymorphism. 386 | 3. `uvm_object_new` and `uvm_component_new` 387 | * Use these macros to include the `new()` constructor for classes 388 | derived from `uvm_object` and `uvm_component`, respectively. 389 | If any additional logic must be included in the constructor, 390 | these macros must not be used, and a constructor must be written manually. 391 | 4. `uvm_create_obj` and `uvm_create_comp` 392 | * Use these macros to call `create()` and 393 | `create(, this)`, respectively. 394 | 5. `DV_CHECK_*` comparison checking macros 395 | * These macros must be used to perform checks on the input arguments 396 | and invoke one of the `uvm_info`, `uvm_error`, or `uvm_fatal` 397 | reporting macros if the check fails. 398 | These are much more concise than hand-writing the comparison checks and 399 | the corresponding UVM report macro and provide efficient readability. 400 | * The severity of the invoked report macro can be specified with the 401 | `` argument, the default reporting macro is `uvm_error`. 402 | * Append `_FATAL` to the end of these macro names to invoke variants of 403 | these macros that will automatically throw fatal errors upon check failure 404 | (e.g. `DV_CHECK_EQ_FATAL`, `DV_CHECK_LE_FATAL`, etc..). 405 | 6. Randomization macros 406 | * `dv_macros.svh` provides three sets of macros which must be used for 407 | all randomization functionality: 408 | * `DV_CHECK_RANDOMIZE_FATAL` - Shorthand for `foo.randomize()` 409 | with a `uvm_fatal` check. 410 | * `DV_CHECK_STD_RANDOMIZE_FATAL` - Shorthand for 411 | `std::randomize(foo)` with a `uvm_fatal` check. 412 | * `DV_CHECK_MEMBER_RANDOMIZE_FATAL` - Shorthand for 413 | `this.randomize(foo)` with a `uvm_fatal` check. 414 | * Variants of all three macros that allow constraints to be specified 415 | also exist, these macros are invoked by inserting `WITH` into the macro name: 416 | `DV_..._RANDOMIZE_WITH_FATAL`. 417 | 7. `DV_EOT_PRINT_..._CONTENTS` TLM fifo display macros 418 | * It is recommended to use these macros to display the status of the 419 | various TLM fifos and queues in the scoreboard at the end of the test 420 | to ensure that those data structures have been emptied. There should be no 421 | pending transactions that have not yet been compared before the simulation 422 | ends. 423 | If used, these macros must be used during the `check_phase`. 424 | 8. `DV_SPINWAIT` 425 | * It is recommended to use this macro in situations that require an 426 | isolation fork to disable some process after waiting for a specified 427 | amount of time, as it provides proper process isolation such as the example 428 | below: 429 | 430 | ```systemverilog 431 | // forked threads should be labeled if they serve a specific purpose, 432 | // like the isolation thread below 433 | fork : isolation_fork 434 | begin 435 | fork 436 | begin 437 | 438 | end 439 | begin 440 | 441 | end 442 | join_any 443 | disable fork; 444 | end 445 | join 446 | ``` 447 | 448 | #### General macro use guidelines 449 | 450 | 1. Macro Naming: 451 | * If the macro wraps some fundamental UVM functionality and deals 452 | directly with UVM functions, like `uvm_component_new`, and so on, the 453 | macro must be named all in `lower_snake_case`. 454 | * If the macro expands into a block of code that does not deal directly 455 | with UVM functionality, and is for convenience, like the 456 | `DV_CHECK_*` macros, the macro must be named in `UPPER_SNAKE_CASE`. 457 | 2. Macro vs. Parameters: 458 | * If the intent is to define a constant that is a basic data type or 459 | that is the result of an expression involving basic data types, a 460 | parameter (or localparam) must be used, depending on where the 461 | constants are being defined. 462 | * If the intent is to abstract away a code snippet or to represent a 463 | slice of an array, a macro must be used. 464 | If the macro is defined in a local perspective, it must be undefined at 465 | the end of the file, otherwise it will pollute the global namespace. 466 | 467 | #### Typical gotchas with macro usage: 468 | 469 | While it is better to avoid macros altogether, they do make our lives easier by 470 | shortening pieces of repeated code, in a manner that cannot be achieved with a 471 | function or a task. In general, the following describes the best practices to 472 | avoid common gotchas with macro usage. 473 | 474 | 1. Always wrap macro arguments in parentheses. If the macro evaluates to an 475 | expression, also wrap the whole expansion in parentheses.The following 476 | example illustrates how failing to do this can cause an unexpected 477 | behavior. 478 | 479 | :-1: 480 | ```systemverilog 481 | `define AND(a, b) a && b 482 | 483 | assign x = `AND(p || q, r) || s; 484 | // Bad: Wrong operator precedence! This results in: p || (q && r) || s 485 | // which is not equal to ((p || q) && r) || s. 486 | ``` 487 | :+1: 488 | ```systemverilog 489 | `define AND(a, b) ((a) && (b)) 490 | 491 | assign x = `AND(p || q, r) || s; 492 | // Good: Output in-line with the expectation. 493 | ``` 494 | 2. Macro usage scope and avoiding namespace collisions. 495 | 496 | Macros have a global scope regardless of where they are defined. Once 497 | compiled, they are visible to ALL subsequent sources in the same 498 | compilation unit as well as to all subsequent compilation units. Hence, 499 | care must be taken to prevent macro re-definitions. Some tools do not even 500 | warn about name collisions, causing unnecessary debug overhead. 501 | 502 | * Macro names must be appropriately prefixed with a thematically chosen 503 | string. It is typical to use the file name or the package name as the 504 | prefix string for all macros defined within that source. 505 | 506 | :-1: 507 | ```systemverilog 508 | // file: dv_macros.h 509 | `define STRINGIFY(s) `"s`" 510 | // Bad: UVM library code also defines a macro with the same name. 511 | // Depending on the tool, this may be flagged as an error. 512 | ``` 513 | 514 | :+1: 515 | ```systemverilog 516 | // file: dv_macros.h 517 | `define DV_STRINGIFY(s) `"s`" 518 | ``` 519 | 520 | * If the scope of the macros defined are global in nature (useful for 521 | the entire testbench), then place them in a separate SystemVerilog 522 | header file with `` `ifndef`` guards. It must only contain macro 523 | definitions and nothing else. The file name must be suffixed with 524 | `_macros` and have the `.svh` extension to denote that it is a header 525 | file. 526 | 527 | :-1: 528 | ```systemverilog 529 | // file: dv_macros.h 530 | automatic function void get_nco(); 531 | ... 532 | endfunction 533 | // Bad: Putting functions and tasks in a header file that is potentially 534 | // included multiple times. 535 | 536 | `define DV_FOO(...) ... 537 | // Bad: No ifndef guard. Macro re-definition warnings will be thrown if 538 | // this header file is included in multiple sources. 539 | ``` 540 | 541 | :+1: 542 | ```systemverilog 543 | // file: dv_macros.svh 544 | `ifndef DV_FOO 545 | `define DV_FOO(...) ... 546 | `endif 547 | 548 | `ifndef DV_BAR 549 | `define DV_BAR xyz 550 | `endif 551 | ``` 552 | 553 | * If the scope of the macros defined is limited to a package or source 554 | (individual interface, module or a class), then place them at the top of 555 | the file. Always `` `undef`` them at the end of the file so that they 556 | are no longer visible to subsequent sources during compilation. Do not 557 | put `` `ifndef`` guards on these macros, so that the re-definitions 558 | if encountered, are flagged. 559 | 560 | :-1: 561 | ```systemverilog 562 | // file: foo_init_seq.sv 563 | `ifndef GET_DATA 564 | `define GET_DATA(baz) ... 565 | `endif 566 | // Bad: Macro-redefinition if encountered, will be ignored due to the 567 | // ifndef guard. Previously defined macro is invoked instead. 568 | // Bad: Macro name is not specific enough. 569 | 570 | class foo_init_seq; 571 | ... 572 | endclass 573 | // EOF 574 | // Bad: Macro is not undefined at the end of the file. 575 | ``` 576 | 577 | :+1: 578 | ```systemverilog 579 | // file: foo_init_seq.sv 580 | `define GET_FOO_TX_FIFO_DATA_AFTER_OP(baz) ... 581 | 582 | class foo_init_seq; 583 | ... 584 | endclass 585 | 586 | `undef GET_FOO_TX_FIFO_DATA_AFTER_OP 587 | ``` 588 | 589 | :+1: 590 | ```systemverilog 591 | // file: foo_env_pkg.sv 592 | `define GET_FOO_TX_FIFO_DATA(baz) ... 593 | 594 | ... 595 | 596 | // Package sources 597 | `include "foo_env_cfg.sv" 598 | ... 599 | `include "foo_scoreboard.sv" 600 | `include "foo_env.sv" 601 | 602 | 603 | `undef GET_FOO_TX_FIFO_DATA 604 | // Good: Only the package sources can invoke this macro. It is not 605 | visible in any other code. 606 | ``` 607 | 608 | 3. Wrap macros that resolve to multiple statements within `begin` and `end`. 609 | 610 | Multi-statement macros are typically problematic when invoked in a single 611 | line conditional expression without `begin`..`end`. It is better to preempt 612 | this bug by wrapping the macro definition itself in `begin`..`end`. 613 | 614 | :-1: 615 | ```systemverilog 616 | `define UPDATE_VALUES(a, b) \ 617 | a = 88; \ 618 | b = 1955; 619 | 620 | if (power_gw == 1.21) `UPDATE_VALUES(speed, year) 621 | // Great Scott! The year is unconditionally set to 1955. 622 | ``` 623 | 624 | :+1: 625 | ```systemverilog 626 | `define UPDATE_VALUES(a, b) \ 627 | begin \ 628 | a = 88; \ 629 | b = 1955; \ 630 | end 631 | 632 | if (power_gw == 1.21) `UPDATE_VALUES(speed, year) 633 | // Good: Both values are set only if the condition is met. 634 | ``` 635 | 636 | Please see this [paper](https://www.veripool.org/papers/Preproc_Good_Evil_SNUGBos10_pres.pdf) 637 | for more details and examples. 638 | 639 | ### Factory 640 | 641 | To use the UVM factory, these guidelines should be followed: 642 | 643 | 1. All classes must be registered with the factory. Use the 644 | `uvm_object_utils` and `uvm_component_utils` macros to register all 645 | non-parameterized classes, and use `uvm_object_param_utils` and 646 | `uvm_component_param_utils` to register all parameterized classes. 647 | 2. The `create()` API must be used to create all objects and components. 648 | Exceptions for this rule are any TLM related objects and covergroup objects, 649 | which should be created by directly calling `new()`, as they should not be 650 | registered with the factory. 651 | 3. When using the factory to create objects with `::type_id::create()`, 652 | the `` must be explicitly declared, parameters representing types 653 | must not be used here. 654 | 4. When using the factory to create objects, it is recommended to use the 655 | same name for both the name of the object and the variable used as a handle to 656 | the object to prevent unnecessary confusion from error messages. 657 | 658 | ```systemverilog 659 | // create a single agent 660 | m_myblock_agent = myblock_agent::type_id::create("m_myblock_agent", this); 661 | ``` 662 | 663 | 5. When using the factory to create an array of objects, decorate the name of 664 | the object in the `create()` call with the index of the object in the array. 665 | 666 | ```systemverilog 667 | // create an array of objects 668 | foreach (myobject_array[i]) begin 669 | myobject_array[i] = myobject::type_id::create($sformatf("myobject_array[%0d]", i), this); 670 | end 671 | ``` 672 | 673 | 6. For classes derived from `uvm_component`, the `parent` argument should be 674 | the keyword `this`, so that the object hierarchy can be built correctly. 675 | 676 | ```systemverilog 677 | m_axi_driver = axi_driver::type_id::create("m_axi_driver", this); 678 | ``` 679 | 680 | 7. For classes derived from `uvm_object`, use `gfn` as part of the name 681 | argument to append the full hierachy name, since `uvm_object` hierarchies are 682 | not automatically built. Note that this only applies to class instances that 683 | are not instantiated within a `uvm_component` in the test hierarchy, 684 | as in this case the full hierarchy name will already be provided. 685 | 686 | ```systemverilog 687 | m_my_txn = my_txn::type_id::create({`gfn, ".m_my_txn"}); 688 | ``` 689 | 690 | 8. All type or instance overrides must be in place before creating the class instance. 691 | Factory usage examples: 692 | 693 | ```systemverilog 694 | // Override all drivers in testbench with my_driver 695 | factory.set_type_override_by_type(current_driver::get_type(), my_driver::get_type()); 696 | 697 | // Override all drivers in testbench with my_driver - alternative syntax 698 | current_driver::type_id::set_type_override(my_driver::get_type()); 699 | 700 | // Override specific instance of current_driver with my_driver 701 | factory.set_inst_override_by_type("env1.m_agent1.driver", current_driver::get_type(), my_driver::get_type()); 702 | 703 | // Override specific instance of current driver - alternative syntax 704 | current_driver::type_id::set_inst_override(my_driver::get_type(), "env.m_agent1.driver"); 705 | ``` 706 | 707 | 708 | ### Configuration Mechanism 709 | 710 | When using the UVM configuration database, these guidelines should be followed: 711 | 712 | 1. The `uvm_config_db` API must be used. Do not use `uvm_resource_db`. Do not use 713 | `set/get_config_object()`, `set/get_config_string()`, or `set/get_config_int()`, 714 | these have been deprecated. 715 | 2. In general, a designated configuration object extended from `uvm_object` 716 | should be used for every `uvm_env` and `uvm_agent` component in the testbench. 717 | 3. It is recommended that the environment's configuration object contain the 718 | agent's configuration object. 719 | 4. The `uvm_config_db` API should be used to pass configuration objects to 720 | locations where they are needed. It should not be used to pass integers, 721 | strings, or other basic data types, since it is much easier for namespace 722 | collisions to occur when using lower level types. 723 | 5. Checks for success must always be performed when using the `uvm_config_db`. 724 | If the lookup fails, issue a `uvm_fatal` to terminate the simulation. 725 | This should be done as follows: 726 | 727 | ```systemverilog 728 | if (!uvm_config_db#(...)::get(...)) begin 729 | `uvm_fatal(...) 730 | end 731 | ``` 732 | 6. Wildcards must not be used in the field argument of `uvm_config_db::set(...)` calls. 733 | It is allowed to use wildcards in the inst_name argument of these calls, 734 | with proper precautions. 735 | 736 | 737 | ### Sequences 738 | 739 | 1. It is recommended to keep sequences as generic as possible and to avoid 740 | writing directed sequences unless absolutely necessary. 741 | 2. It is recommended to avoid explicit delays in terms of absolute time to 742 | make code emulation friendly. Delays in terms of clock cycles are allowed. 743 | 3. The `body()` method should only execute the raw functional behavior of 744 | the sequence. 745 | Any associated housekeeping code should be placed elsewhere, such as in the 746 | `pre_start()` and `post_start()` methods. 747 | * `pre_start()` and `post_start()` must be used instead of `pre_body()` 748 | and `post_body()`, as these will always be called, even for subsequences 749 | called from a parent sequence. 750 | 4. When creating a sequence object, always randomize the sequence before starting it. 751 | 5. Virtual sequences must be used to coordinate the behavior of multiple agents and multiple sequences. 752 | 6. Virtual sequences must be started on the null sequencer or on a valid virtual sequencer. 753 | 754 | 755 | ### Sequence Items 756 | 757 | It is recommended, but not necessary, to create small "unit tests" for 758 | transactions objects to ensure the randomization constraints are working as 759 | intended. 760 | 761 | 762 | ### RAL Usage 763 | 764 | When using the UVM RAL model, care must be taken when using `uvm_reg::set()` and 765 | `uvm_reg::update()`, as these are both non-atomic operations that can easily 766 | cause race conditions if there are any parallel threads. 767 | 768 | 769 | ### Objections and Coordinating End of Test 770 | 771 | 772 | As a general principle, a phase should not end when either there is more stimulus to 773 | send during that phase or the DUT has yet to respond to some stimulus that has 774 | been sent. 775 | 776 | To prevent a phase from ending when there is more stimulus to send, a test class 777 | must raise and lower objections. 778 | 779 | To prevent a phase from ending before the DUT has responded to some stimulus, 780 | classes derived from `uvm_component` should raise and lower objections in their 781 | `phases_ready_to_end()` method. 782 | 783 | It is also recommended to only include objections in the monitor component. 784 | When using this approach, these guidelines should be followed: 785 | 786 | 1. The monitor's `phase_ready_to_end()` method should implement a watchdog timer 787 | that raises an objection if any traffic is seen on the bus and lowers it once 788 | no traffic is seen within the timeout period. If traffic is seen, the 789 | watchdog resets its timer. 790 | Refer to the example below: 791 | 792 | ```systemverilog 793 | // Example code for the monitor class. 794 | // This code assumes that the associated configuration object has an integer 795 | // property "ok_to_end_delay_ns", which gives the window timeout in 796 | // nanoseconds. 797 | 798 | protected bit ok_to_end = 1'b1; 799 | protected bit watchdog_done = 1'b0; 800 | 801 | function void phase_ready_to_end(uvm_phase phase); 802 | if (phase.is(uvm_run_phase::get())) begin 803 | if (watchdog_done) fork 804 | monitor_ready_to_end(); 805 | join_none 806 | if (!ok_to_end || !watchdog_done) begin 807 | phase.raise_objection(this, $sformatf("%s objection raised", `gfn)); 808 | fork 809 | begin 810 | // wait until ok_to_end is set 811 | watchdog_ok_to_end(); 812 | phase.drop_objection(this, $sformatf("%s, objection dropped", 813 | `gfn)); 814 | end 815 | join_none 816 | end 817 | end 818 | 819 | endfunction 820 | 821 | // This watchdog waits for ok_to_end_delay_ns nanoseconds while checking for 822 | // any traffic seen on the bus during this period. 823 | // If traffic is seen, the watchdog will restart until it sees no traffic. 824 | task watchdog_ok_to_end(); 825 | fork 826 | begin : isolation_fork 827 | bit watchdog_reset; 828 | fork 829 | forever begin 830 | // check bus interface for traffic 831 | @(ok_to_end or watchdog_reset); 832 | if (!ok_to_end && !watchdog_reset) watchdog_reset = 1; 833 | end 834 | forever begin 835 | #(cfg.ok_to_end_delay_ns * 1ns); 836 | if (!watchdog_reset) begin 837 | break; 838 | end else begin 839 | watchdog_reset = 0; 840 | end 841 | end 842 | join_any; 843 | disable fork; 844 | 845 | watchdog_done = 1; 846 | end : isolation_fork 847 | join 848 | endtask 849 | 850 | // This task is invoked as a non-blocking thread when phase_ready_to_end() 851 | // is first entered. 852 | // 853 | // This task should monitor the DUT's interface and control ok_to_end: it 854 | // should be cleared whenever there are any pending transactions and 855 | // set to 1 if there are no pending transactions. 856 | virtual task monitor_ready_to_end(); 857 | endtask 858 | ``` 859 | 860 | 2. It is recommended not to use other objections in the scoreboard; the 861 | scoreboard should just make use of information already available to it 862 | (like fifo size, etc...) to determine when it is ready to end, as the 863 | monitor has already guaranteed that no more traffic is seen on the bus. 864 | These fifo checks should be checked during its `check_phase()`. 865 | 866 | The more general guidelines below should be followed when dealing with 867 | end-of-test timeouts or objections: 868 | 869 | 1. When calling `raise_objection` or `drop_objection`, a string must be passed 870 | as a second argument to describe the objection to help with debugging. 871 | 872 | ```systemverilog 873 | phase.raise_objection(this, $sformatf("%s objection raised", `gfn)); 874 | ... 875 | phase.drop_objection(this, $sformatf("%s objection dropped", `gfn)); 876 | ``` 877 | 878 | 2. It is recommended to use the built-in UVM timeout mechanism, 879 | `uvm_root::set_timeout(, 1)`. 880 | The base test in every testbench should specify a default timeout limit, 881 | which can be overridden by every derivative test. 882 | A standard plusarg `+UVM_TIMEOUT=...` is recommended to be used for this 883 | override mechanism. 884 | 885 | 886 | ### Logging and Print Messages 887 | 888 | 1. Print messages sent to the console should be kept to a minimum. 889 | Logs should be as concise as possible, by only writing key information when 890 | activity is present. 891 | 2. Whenever possible, log any data directly to log files instead of the console. 892 | It is recommended that only critical information/errors be sent to both the 893 | console and the log files. 894 | 3. Logging messages should be architected to be parsing "friendly" 895 | * All related information should be kept on a single line. 896 | * Only the relevant data should be logged, for example, there is no need 897 | to log all fields of a transaction object when only a small subset is 898 | valid and relevant to the transaction being performed. 899 | * Log files should format lines consistently, starting with the 900 | simulation time that the logging event occurs, enabling easier post-processing. 901 | * The build in `print()` function of `uvm_object` classes is not 902 | parsing "friendly", it is recommended not to use this function. 903 | 4. Do not use the `uvm_report_*` messaging functionality, or `$display` to 904 | print any messages. 905 | The `uvm_{info/error/fatal}` macros must be used instead. 906 | 5. Do not use the `uvm_warning` macro, use `uvm_error` or `uvm_fatal` instead. 907 | 6. The first argument to these report macros must be one of the `gfn` or 908 | `gtn` shorthand macros used in place of `get_full_name()` and `get_type_name()`. 909 | This will allow for easier debugging should something go wrong. 910 | 7. The `UVM_NONE` and `UVM_FULL` verbosity levels must not be used for any 911 | report messages. 912 | Recommended criteria for the choice of `VERBOSITY` value for `uvm_info` 913 | messages: 914 | * `UVM_LOW` - important messages that occur a small number of times 915 | during a simulation. 916 | * Instantiation of testbench components. 917 | * Reset assert/deassert, start/end of DUT initialization. 918 | * Start/end of traffic generation. 919 | * `UVM_MEDIUM` - slightly more detailed messages. 920 | * Contents of CSR fields during CSR transactions. 921 | * Reporting of significant events inside the DUT - fifo full, 922 | fifo empty, and so on. 923 | * `UVM_HIGH` - Any information about DUT activity, reference model, 924 | and testbench that could be helpful for monitoring stimulation progress. 925 | * Parsing/interpretation of fields in requests to the DUT and reference model. 926 | * Read/write operations to a memory model. 927 | * Status of transactions over SystemVerilog interfaces. 928 | * Values of data output by the DUT. 929 | * `UVM_DEBUG` - Extremely specific information used for debugging 930 | failures. 931 | * Any CSR exclusions. 932 | * Interface buses used to drive the interface protocol. 933 | 934 | 935 | ### DPI and C Connections 936 | 937 | 1. DPI and native SystemVerilog calls have the same semantics and 938 | are thus indistinguishable. 939 | To preserve readability, a decorator must be added as such: 940 | * Functions/tasks exported from SV to C must be prefixed with `sv_dpi_`. 941 | 942 | ```systemverilog 943 | export "DPI" sv_dpi_adder = adder_function; 944 | ``` 945 | 946 | * Functions imported from C to SV must be prefixed with `c_dpi_`. 947 | 948 | ```systemverilog 949 | extern int c_dpi_adder(const int a, const int b); 950 | ``` 951 | 952 | 2. DPI usage is recommended in the following scenarios: 953 | * Interfacing with C/C++ based reference models. 954 | * Usage of optimized C/C++ libraries. 955 | * Emulation. 956 | 3. DPI usage is not recommended when the functionality can be handled natively 957 | in SV. 958 | 4. General DPI coding guidelines 959 | * Do not cross the language boundary frequently. 960 | * If a SV->C call consumes time and the C routine is not thread safe, 961 | protect the call with a semaphore to avoid synchronization issues. 962 | * In general, pass only basic data types as arguments to DPI calls. 963 | 964 | 965 | ## SystemVerilog Language Features 966 | 967 | ### Function Declarations 968 | 969 | Functions declared within packages, as well as any other static entities such as 970 | modules and interfaces, must be explicitly scoped with either the `static` or 971 | `automatic` keyword. 972 | 973 | ### Randomization 974 | 975 | Good constraint coding style is important for faster simulations and better 976 | simulation performance. 977 | 978 | 1. Give all constraints a name that matches with what is being constrained, and 979 | suffix the constraint name with `_c`. 980 | 981 | ```systemverilog 982 | constraint num_packets_c { 983 | num_packets < 8; 984 | } 985 | ``` 986 | 2. Avoid using loops in constraints whenever possible. In some cases, `foreach` 987 | can be replaced by `inside`. 988 | 989 | :-1: 990 | ```systemverilog 991 | constraint con_c { 992 | foreach (data[i]) { 993 | a != data[i]; 994 | } 995 | } 996 | ``` 997 | 998 | :+1: 999 | ```systemverilog 1000 | constraint con_c { 1001 | !(a inside {data}); 1002 | } 1003 | ``` 1004 | 1005 | 3. If using loops in constraints is necessary, avoid doing calculations inside 1006 | the loops. 1007 | 4. Whenever possible, use bitmasking operations over modulus operations, as 1008 | bitmasking operations are much faster. 1009 | 5. If a constraint becomes too complex, it is highly recommended to split the 1010 | constraint and separately randomize all relevant variables. 1011 | 6. When randomizing an array of objects, it is generally recommended to not 1012 | directly randomize the array, but to iterate through it and directly 1013 | randomize each object to see better simulation performance. 1014 | 1015 | 1016 | ### Enums 1017 | 1018 | Enum names should be written in `lower_snake_case`, and should include the block 1019 | name for clarity. 1020 | The enumerated values should be written in `UpperCamelCase` and should include 1021 | the name of the enum for clarity. 1022 | 1023 | ```systemverilog 1024 | typedef enum bit { 1025 | UartInterruptFrameErr, 1026 | UartInterruptRxBufferFull, 1027 | ... 1028 | } uart_interrupt_e; 1029 | ``` 1030 | 1031 | 1032 | ### Interfaces, Clocking Blocks, Modports 1033 | 1034 | 1. Do not use the `program` construct. 1035 | 2. Clocks and reset must be generated in SystemVerilog modules, interfaces, 1036 | or in the UVM component hierarchy. 1037 | Do not do this generation in `uvm_object` derived classes. 1038 | 3. Use clocking blocks in a SystemVerilog interface to sample and drive 1039 | synchronous DUT interfaces. 1040 | 4. It is recommended to implement a reusable interface scheme for block level 1041 | testbenches that will be included in integration/system level testbenches. 1042 | 1043 | 1044 | ### Loop Operators 1045 | 1046 | It is highly recommended to use `foreach` loops as often as possible over any 1047 | equivalent loop operators, as they are much more concise and less prone to any 1048 | subtle errors. 1049 | 1050 | 1051 | ### Code Within Asserts 1052 | 1053 | For any randomization that is required, the macros specified in the 1054 | [Randomization Macros section](#macro-usage) must be used. Do not use `assert()` 1055 | to check manual randomization calls, use the provided macros instead. 1056 | More broadly, do not place any expression with side effects into an 1057 | `assert()` statement. 1058 | 1059 | :-1: 1060 | ```systemverilog 1061 | // Do not assert the output of randomize() calls 1062 | // 1. 1063 | ret = item.randomize() with {}; 1064 | assert(ret); 1065 | // 2. 1066 | assert(randomize() with {}); 1067 | // 3. 1068 | assert(item.randomize() with {}); 1069 | // 4. 1070 | assert(function_that_has_side_effects()); 1071 | ``` 1072 | 1073 | ### Wait and Fork 1074 | 1075 | Always put `wait fork` and `disable fork` constructs inside of an 1076 | `isolation fork...join` block to avoid erroneous waiting. 1077 | It is recommended to use the `DV_SPINWAIT` macro whenever possible, 1078 | [as described here](#macro-usage). 1079 | 1080 | When disabling subprocesses, this may be done by using `disable fork` to 1081 | terminate all processes or by `disable thread_label` to disable a specific 1082 | thread. You may not use `disable fork_label` to disable all threads in a fork 1083 | statement because there is inconsistent support for this among EDA tools. The 1084 | use of `disable fork_label` is not compliant to the SystemVerilog-2017 1085 | standard (see Section 9.6.2 and 9.6.3 of the SV2017 LRM). Example code: 1086 | 1087 | ``` 1088 | fork: fork_label 1089 | begin: thread_label 1090 | end 1091 | ... 1092 | join_any 1093 | 1094 | // INCORRECT. 1095 | disable fork_label; 1096 | // Valid, but does not respect parent child process relationships. 1097 | disable thread_label; 1098 | // Kills all threads spawned by the parent thread, including the ones in the 1099 | // past. 1100 | disable fork; 1101 | ``` 1102 | 1103 | ### Wait And Non-Forever Loop 1104 | 1105 | Always create a watchdog timer along with the wait statement or the non-forever 1106 | loop. Recommend to use the following macros. 1107 | 1108 | ```systemverilog 1109 | // This does `wait (condition);` with a default watchdog timer. 1110 | `DV_WAIT(condition) 1111 | ``` 1112 | 1113 | ```systemverilog 1114 | `DV_SPINWAIT(while (condition) begin 1115 | ... 1116 | end) 1117 | ``` 1118 | 1119 | ### Void Casts 1120 | 1121 | Do not void cast any function/task calls that have useful return values, 1122 | EXCEPT the following: 1123 | * system functions. 1124 | * RAL `predict()` calls. 1125 | * fifo/queue methods. 1126 | 1127 | 1128 | ### Associative Arrays 1129 | 1130 | Do not use wildcard indexed `[*]` associative arrays. 1131 | Always specify a particular index type. 1132 | 1133 | 1134 | ### Bind Statements 1135 | 1136 | `bind` statements are the preferred approach for using assertion-based monitors. 1137 | For these situations, using `.*` is allowed for making implicit port 1138 | declarations when binding a module whose ports are all inputs. 1139 | 1140 | 1141 | ### Simulator-specific Code 1142 | 1143 | Always wrap simulator-specific code inside preprocessor guards. 1144 | The macro names `VCS`, `INCA`, `XCELIUM` are defined for the VCS, 1145 | Incisive/NCsim/Irun, and Xcelium/xrun simulators respectively, 1146 | these must be used to wrap relevant code, as shown below: 1147 | 1148 | ```systemverilog 1149 | `ifdef VCS 1150 | $stack(); 1151 | `endif 1152 | ``` 1153 | 1154 | 1155 | ### Forbidden System Tasks and Functions 1156 | 1157 | Do not use the following system functions 1158 | 1159 | * `$psprintf`, this is not in the SystemVerilog LRM. Use `$sformatf` instead. 1160 | * `$random` and `$dist_*`, these functions are not part of the SystemVerilog 1161 | random stability model and can break simulation reproducibility. 1162 | Use `$urandom` or a randomization macro instead. 1163 | * `$srandom`, this is not part of the SystemVerilog standard. 1164 | Use `process::self().srandom()` instead. 1165 | 1166 | 1167 | ### Backdoor Force and Probe in Chip-level 1168 | 1169 | Chip-level tests could be run in both RTL and gate sim. Since some signals may not 1170 | be preserved in the same path after synthesis, we need follow these rules to use 1171 | backdoor force or probe. This assumes gate-level netlist won't be flattened. 1172 | 1173 | * Reference module inputs/outputs rather than the internal nets, as input/output ports will be 1174 | preserved in non-flattened netlist. 1175 | * Reference logic if possible. If that is not possible, structs are likely converted to a giant 1176 | vector. We can cast that vector to the struct and thus still access the individual members. 1177 | * Do not reference internal nets, as those will likely not be preserved. If we really need to do so, 1178 | they should be placed in an anchored buffer, in order to preserve the path. 1179 | * Do not reference to internal clocks/resets, as they may not be preserved, even if the 1180 | clocks/resets are in the module inputs/outputs. If we have to, place it in an anchored buffer. 1181 | * CSR hierarchies are likely to be preserved, so CSR backdoor access will still work. 1182 | 1183 | 1184 | ## SystemVerilog Assertions 1185 | 1186 | Most, if not all design properties are captured as in-line assertions within 1187 | the RTL itself. The guidance on usage and implementation of assertions can be 1188 | found in the adjoining [lowRISC Verilog style guide](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md#assertion-macros). 1189 | 1190 | In some cases, it may be useful to capture specific design behaviors and their 1191 | expected outcomes as assertion checks, rather than checks in the scoreboard, or 1192 | other UVM testbench components. Such properties may reference internal RTL 1193 | signals at the same or different hierarchies. They may be too complex to embed 1194 | within the RTL itself. So, they may instead be captured in a separate 1195 | SystemVerilog assertion (SVA) module. 1196 | 1197 | The following guidelines help maximize the reuse of these SVA modules 1198 | horizontally (an IP design is enhanced externally, and thus, has an extended 1199 | testbench that reuses heavily from the original testbench) and vertically (an 1200 | IP instantiated in a larger design, such as an SoC). 1201 | 1202 | 1. The SVA module ports must all be inputs only. Since they are passive 1203 | checkers, they must not drive or force internal signals. Doing so may lead 1204 | to confusion and increase the debug overhead. 1205 | 1206 | 1. Use the [assertion macros](https://github.com/lowRISC/opentitan/blob/master/hw/ip/prim/rtl/prim_assert.sv). 1207 | 1208 | :-1: 1209 | ```systemverilog 1210 | // Manually typing the complete assertion statement is tedious and error- 1211 | // prone. 1212 | OneHotCheck_A: assert property((@posedge clk) disable iff (!rst_n) 1213 | valid |=> $onehot(data)); 1214 | else $error(...); 1215 | ``` 1216 | 1217 | :+1: 1218 | ```systemverilog 1219 | // Assertion macros are concise and hide some extra functionalities 1220 | // underneath. 1221 | `ASSERT(OneHotCheck_A, valid |=> $onehot(data)) 1222 | ``` 1223 | 1224 | 1. Do not instantiate the SVA module in the testbench. Instead, `bind` it to 1225 | the RTL module within which it references the signals. When the SVA module 1226 | is bound to the RTL module, an instance of the SVA module is created 1227 | underneath all instances of the RTL module. 1228 | 1229 | :-1: 1230 | ```systemverilog 1231 | // Instantiating the SVA module in the testbench forces the user to use 1232 | // absolute hierarchical paths to signals within the assertion properties 1233 | // in the SVA module. This hampers reuse, since those paths may not exist 1234 | // in other testbenches. 1235 | sva_module_for_aes_core u_sva_module_for_aes_core(.clk(...), ...); 1236 | ``` 1237 | 1238 | :+1: 1239 | ```systemverilog 1240 | // Bind the SVA module to the RTL module directly. All instances of 1241 | // `aes_core` in the design will benefit from the SVA checks. The SVA 1242 | // module can also be reused in other testbenches, which may contain 1243 | // additional instances of this RTL module elsewhere in the design. 1244 | bind aes_core sva_module_for_aes_core 1245 | u_sva_module_for_aes_core(.clk(...), ...); 1246 | ``` 1247 | 1248 | 1. Do not use absolute hierarchical paths to signals in the SVA modules (the 1249 | previous bullet explains why). The bind enables cross module references to 1250 | signals in the RTL module and its sub-hierarchies using partial paths in 1251 | the SVA module. 1252 | 1253 | :-1: 1254 | ```systemverilog 1255 | // Path tb.dut.u_aes.u_aes_core.u_foo does not exist in other 1256 | // testbenches. This module is not reusable in other testbenches. 1257 | `ASSERT(CheckProp_A, valid |=> $onehot(tb.dut.u_aes.u_aes_core.u_bar.u_baz.u_quux.data_q)) 1258 | `ASSERT(CheckProp_A, 1259 | tb.dut.u_aes.u_aes_core.u_foo.state_q == Idle |=> `AES_CORE_BAR_HIER.u_baz.u_quux.data_q == 0) 1260 | ``` 1261 | 1262 | :+1: 1263 | ```systemverilog 1264 | // Binding the SVA module to `aes_core` obviates the need to specify the 1265 | // absolute hierarchical paths to internal signals. Cross module 1266 | // reference with partial paths is sufficient. This SVA module can now be 1267 | // reused in the other testbenches. 1268 | `ASSERT(CheckProp_A, valid |=> $onehot(u_bar.u_baz.u_quux.data_q)) 1269 | `ASSERT(CheckOtherProp_A, 1270 | u_foo.state_q == Idle |=> u_bar.u_baz.u_quux.data_q == 0) 1271 | ``` 1272 | 1273 | 1. If the assertions reference signals at different sub-hierarchies, then bind 1274 | the SVA module to the closest common ancestor RTL module. In previous 1275 | examples, that would be the `aes_core` module. 1276 | 1277 | 1. Consolidate all SVA binds in a dedicated bindfile. The `bind` invocations 1278 | are placed in a dedicated SystemVerilog module, called the 'bindfile'. 1279 | Bindfiles are treated as entities that are separate from the testbench 1280 | module. They are passed to the simulator as one of the 'top level' modules 1281 | for elaboration. The bindfiles themselves, can be reused in other 1282 | testbenches, by simply passing them as a 'top level' entity to the 1283 | simulator in those other testbenches as well. 1284 | 1285 | :-1: 1286 | ```systemverilog 1287 | // The testbench module which instantiates the design under test (DUT). 1288 | module tb; 1289 | 1290 | // This module is considered 'unreusable'. The `bind` invocations below 1291 | // must hence be replicated in other testbenches where the SVA module can 1292 | // be reused. 1293 | bind aes_core sva_module_for_aes_core 1294 | u_sva_module_for_aes_core(.clk(...), ...); 1295 | 1296 | endmodule 1297 | ``` 1298 | 1299 | :+1: 1300 | ```systemverilog 1301 | // A dedicated bindfile for all AES assertions. 1302 | module aes_sva_bind; 1303 | 1304 | // This module is reusable in other testbenches. The `bind` invocations 1305 | // need not be replicated in other testbenches. 1306 | bind aes_core sva_module_for_aes_core 1307 | u_sva_module_for_aes_core(.clk(...), ...); 1308 | 1309 | endmodule 1310 | ``` 1311 | 1312 | 1. Bind SVA modules to RTL modules and not to specific instances of the RTL 1313 | module. Binding the SVA module to an instance again, creates reusability 1314 | issues - other testbenches may have additional instances of the RTL module 1315 | elsewhere in the design, which will miss out on the SVA checks. If there is 1316 | a strong justifiable reason to bind the SVA module to a specifc instance, 1317 | then refrain from specifying the absolute hierarchical path to the 1318 | instance. Instead, use the `bind : ` notation. 1319 | 1320 | :-1: 1321 | ```systemverilog 1322 | // This bindfile is not reusable in other testbenches, because the `bind` 1323 | // is applied to an instance with absolute hierarchical path, which may 1324 | // not exist in other testbenches. 1325 | bind tb.dut.u_aes.u_aes_core sva_module_for_aes_core 1326 | u_sva_module_for_aes_core(.clk(...), ...); 1327 | ``` 1328 | 1329 | :-1: 1330 | ```systemverilog 1331 | // SVA module is only bound to `u_aes_core` instance of `aes_core`. This 1332 | // bindfile is reusable in other testbenches. But note that only the 1333 | // `aes_core` instance named `u_aes_core` will receive the SVA checks. 1334 | // Discouraged, but fine reusablility-wise. 1335 | bind aes_core: u_aes_core sva_module_for_aes_core 1336 | u_sva_module_for_aes_core(.clk(...), ...); 1337 | ``` 1338 | 1339 | :+1: 1340 | ```systemverilog 1341 | // This bindfile is reusable in other testbenches. 1342 | bind aes_core sva_module_for_aes_core 1343 | u_sva_module_for_aes_core(.clk(...), ...); 1344 | ``` 1345 | 1346 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | 397 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lowRISC Style Guides 2 | 3 | This repository contains style guides curated by lowRISC for use in our 4 | code and documentation. 5 | 6 | - [SystemVerilog style guide](VerilogCodingStyle.md) 7 | - [Coding Style Guide for Design Verification](DVCodingStyle.md) 8 | 9 | We invite issues and pull requests to add clarity to these guides. 10 | 11 | All documents in this repository are licensed under Creative Commons 12 | Attribution 4.0 International 13 | ([CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/deed)). 14 | -------------------------------------------------------------------------------- /VerilogCodingStyle.md: -------------------------------------------------------------------------------- 1 | # lowRISC Verilog Coding Style Guide 2 | 3 | ## Basics 4 | 5 | ### Summary 6 | 7 | Verilog is the main logic design language for lowRISC Comportable IP. 8 | 9 | Verilog and SystemVerilog (often generically referred to as just "Verilog" in 10 | this document) can be written in vastly different styles, which can lead to code 11 | conflicts and code review latency. This style guide aims to promote Verilog 12 | readability across groups. To quote the 13 | [Google C++ style guide](https://google.github.io/styleguide/cppguide.html): 14 | "Creating common, required idioms and patterns makes code much easier to 15 | understand." 16 | 17 | This guide defines the Comportable style for Verilog. The goals are to: 18 | 19 | * promote consistency across hardware development projects 20 | * promote best practices 21 | * increase code sharing and re-use 22 | 23 | This style guide defines style for both Verilog-2001 and SystemVerilog compliant 24 | code. Additionally, this style guide defines style for both synthesizable and 25 | test bench code. 26 | 27 | See the [Appendix](#appendix---condensed-style-guide) for a condensed tabular 28 | representation of this style guide. 29 | 30 | **Table of Contents** 31 | 32 | - [lowRISC Verilog Coding Style Guide](#lowrisc-verilog-coding-style-guide) 33 | - [Basics](#basics) 34 | - [Summary](#summary) 35 | - [Terminology Conventions](#terminology-conventions) 36 | - [Default to C-like Formatting](#default-to-c-like-formatting) 37 | - [Style Guide Exceptions](#style-guide-exceptions) 38 | - [Which Verilog to Use](#which-verilog-to-use) 39 | - [Verilog/SystemVerilog Conventions](#verilogsystemverilog-conventions) 40 | - [Summary](#summary-1) 41 | - [File Extensions](#file-extensions) 42 | - [General File Appearance](#general-file-appearance) 43 | - [Characters](#characters) 44 | - [POSIX File Endings](#posix-file-endings) 45 | - [Line Length](#line-length) 46 | - [No Tabs](#no-tabs) 47 | - [No Trailing Spaces](#no-trailing-spaces) 48 | - [Begin / End](#begin--end) 49 | - [Indentation](#indentation) 50 | - [Indented Sections](#indented-sections) 51 | - [Line Wrapping](#line-wrapping) 52 | - [Preprocessor Directives](#preprocessor-directives) 53 | - [Spacing](#spacing) 54 | - [Comma-delimited Lists](#comma-delimited-lists) 55 | - [Tabular Alignment](#tabular-alignment) 56 | - [Expressions](#expressions) 57 | - [Array Dimensions in Declarations](#array-dimensions-in-declarations) 58 | - [Parameterized Types](#parameterized-types) 59 | - [Labels](#labels) 60 | - [Case items](#case-items) 61 | - [Function And Task Calls](#function-and-task-calls) 62 | - [Macro Calls](#macro-calls) 63 | - [Line Continuation](#line-continuation) 64 | - [Space Around Keywords](#space-around-keywords) 65 | - [Parentheses](#parentheses) 66 | - [Ternary Expressions](#ternary-expressions) 67 | - [Comments](#comments) 68 | - [Declarations](#declarations) 69 | - [Basic Template](#basic-template) 70 | - [Naming](#naming) 71 | - [Summary](#summary-2) 72 | - [Constants](#constants) 73 | - [Parameterized Objects (modules, etc.)](#parameterized-objects-modules-etc) 74 | - [Macro Definitions](#macro-definitions) 75 | - [Suffixes](#suffixes) 76 | - [Enumerations](#enumerations) 77 | - [Signal Naming](#signal-naming) 78 | - [Use descriptive names](#use-descriptive-names) 79 | - [Prefixes](#prefixes) 80 | - [Hierarchical consistency](#hierarchical-consistency) 81 | - [Clocks](#clocks) 82 | - [Resets](#resets) 83 | - [Language Features](#language-features) 84 | - [Preferred SystemVerilog Constructs](#preferred-systemverilog-constructs) 85 | - [Package Dependencies](#package-dependencies) 86 | - [Module Declaration](#module-declaration) 87 | - [Module Instantiation](#module-instantiation) 88 | - [Constants](#constants-1) 89 | - [Signal Widths](#signal-widths) 90 | - [Always be explicit about the widths of number literals.](#always-be-explicit-about-the-widths-of-number-literals) 91 | - [Port connections on module instances must always match widths correctly.](#port-connections-on-module-instances-must-always-match-widths-correctly) 92 | - [Do not use multi-bit signals in a boolean context.](#do-not-use-multi-bit-signals-in-a-boolean-context) 93 | - [Bit Slicing](#bit-slicing) 94 | - [Handling Width Overflow](#handling-width-overflow) 95 | - [Blocking and Non-blocking Assignments](#blocking-and-non-blocking-assignments) 96 | - [Delay Modeling](#delay-modeling) 97 | - [Sequential Logic (Latches)](#sequential-logic-latches) 98 | - [Sequential Logic (Registers)](#sequential-logic-registers) 99 | - [Don't Cares (`X`'s)](#dont-cares-xs) 100 | - [Catching errors where invalid values are consumed](#catching-errors-where-invalid-values-are-consumed) 101 | - [Specific Guidance on Case Statements and Ternaries](#specific-guidance-on-case-statements-and-ternaries) 102 | - [Dynamic Array Indexing](#dynamic-array-indexing) 103 | - [Combinational Logic](#combinational-logic) 104 | - [Case Statements](#case-statements) 105 | - [Wildcards in case items](#wildcards-in-case-items) 106 | - [Generate Constructs](#generate-constructs) 107 | - [Signed Arithmetic](#signed-arithmetic) 108 | - [Number Formatting](#number-formatting) 109 | - [Functions and Tasks](#functions-and-tasks) 110 | - [Problematic Language Features and Constructs](#problematic-language-features-and-constructs) 111 | - [Floating begin-end blocks](#floating-begin-end-blocks) 112 | - [Hierarchical references](#hierarchical-references) 113 | - [Design Conventions](#design-conventions) 114 | - [Summary](#summary-3) 115 | - [Declare all signals](#declare-all-signals) 116 | - [Use `logic` for synthesis](#use-logic-for-synthesis) 117 | - [Logical vs. Bitwise](#logical-vs-bitwise) 118 | - [Packed Ordering](#packed-ordering) 119 | - [Unpacked Ordering](#unpacked-ordering) 120 | - [Finite State Machines](#finite-state-machines) 121 | - [Active-Low Signals](#active-low-signals) 122 | - [Differential Pairs](#differential-pairs) 123 | - [Delays](#delays) 124 | - [Wildcard import of packages](#wildcard-import-of-packages) 125 | - [Assertion Macros](#assertion-macros) 126 | - [A Note on Security Critical Applications](#a-note-on-security-critical-applications) 127 | - [Appendix - Condensed Style Guide](#appendix---condensed-style-guide) 128 | - [Basic Style Elements](#basic-style-elements) 129 | - [Construct Naming](#construct-naming) 130 | - [Suffixes for signals and types](#suffixes-for-signals-and-types) 131 | - [Language features](#language-features-1) 132 | 133 | 134 | ### Terminology Conventions 135 | 136 | Unless otherwise noted, the following terminology conventions apply to this 137 | style guide: 138 | 139 | * The word ***must*** indicates a mandatory requirement. Similarly, ***do 140 | not*** indicates a prohibition. Imperative and declarative statements 141 | correspond to ***must***. 142 | * The word ***recommended*** indicates that a certain course of action is 143 | preferred or is most suitable. Similarly, ***not recommended*** indicates 144 | that a course of action is unsuitable, but not prohibited. There may be 145 | reasons to use other options, but the implications and reasons for doing so 146 | must be fully understood. 147 | * The word ***may*** indicates a course of action is permitted and optional. 148 | * The word ***can*** indicates a course of action is possible given material, 149 | physical, or causal constraints. 150 | 151 | ### Default to C-like Formatting 152 | 153 | ***Where appropriate, format code consistent with 154 | https://google.github.io/styleguide/cppguide.html*** 155 | 156 | Verilog is a C-like language, and where appropriate, we default to being 157 | consistent with 158 | [Google's C++ Style Guide](https://google.github.io/styleguide/cppguide.html). 159 | 160 | In particular, we inherit these specific formatting guidelines: 161 | 162 | * Generally, [names](#naming) should be descriptive and avoid abbreviations. 163 | * Non-ASCII characters are forbidden. 164 | * Indentation uses spaces, no tabs. Indentation is two spaces for nesting, 165 | four spaces for line continuation. 166 | * Place a space between `if` and the parenthesis in 167 | [conditional expressions](https://google.github.io/styleguide/cppguide.html#Conditionals). 168 | * Use horizontal whitespace around operators, and avoid trailing 169 | whitespace at the end of lines. 170 | * Maintain consistent and good 171 | [punctuation, spelling, and grammar](https://google.github.io/styleguide/cppguide.html#Punctuation,_Spelling_and_Grammar) 172 | (within comments). 173 | * Use standard formatting for [comments](#comments), including C-like formatting for [TODO](https://google.github.io/styleguide/cppguide.html#TODO_Comments) and [deprecation](https://google.github.io/styleguide/cppguide.html#Deprecation_Comments). 174 | 175 | ### Style Guide Exceptions 176 | 177 | ***Justify all exceptions with a comment.*** 178 | 179 | No style guide is perfect. There are times when the best path to a working 180 | design, or for working around a tool issue, is to simply cut the Gordian Knot 181 | and create code that is at variance with this style guide. It is always okay to 182 | deviate from the style guide by necessity, as long as that necessity is clearly 183 | justified by a brief comment, as well as a lint waiver pragma where appropriate. 184 | 185 | ### Which Verilog to Use 186 | 187 | ***Prefer SystemVerilog-2017.*** 188 | 189 | All RTL and tests should be developed in SystemVerilog, following the 190 | [IEEE 1800-2017 (SystemVerilog-2017) standard](https://ieeexplore.ieee.org/document/8299595), except for [prohibited features](#problematic-language-features-and-constructs). 191 | 192 | The standards document is available free of cost through [IEEE GET](https://ieeexplore.ieee.org/browse/standards/get-program/page/series?id=80) (a registration is required). 193 | 194 | ## Verilog/SystemVerilog Conventions 195 | 196 | ### Summary 197 | 198 | This section addresses primarily aesthetic aspects of style: line length, 199 | indentation, spacing, etc. 200 | 201 | ### File Extensions 202 | 203 | ***Use the `.sv` extension for SystemVerilog files (or `.svh` for files 204 | that are included via the preprocessor).*** 205 | 206 | File extensions have the following meanings: 207 | 208 | * `.sv` indicates a SystemVerilog file defining a module or package. 209 | * `.svh` indicates a SystemVerilog header file intended to be included in 210 | another file using a preprocessor `` `include`` directive. 211 | * `.v` indicates a Verilog-2001 file defining a module or package. 212 | * `.vh` indicates a Verilog-2001 header file. 213 | 214 | Only `.sv` and `.v` files are intended to be compilation units. `.svh` and `.vh` 215 | files may only be `` `include``-ed into other files. 216 | 217 | With exceptions of netlist files, each .sv or .v file should contain only one 218 | module, and the name should be associated. For instance, file `foo.sv` should 219 | contain only the module `foo`. 220 | 221 | ### General File Appearance 222 | 223 | #### Characters 224 | 225 | ***Use only ASCII characters with UNIX-style line endings(`"\n"`).*** 226 | 227 | #### POSIX File Endings 228 | 229 | ***All lines on non-empty files must end with a newline (`"\n"`).*** 230 | 231 | #### Line Length 232 | 233 | ***Wrap the code at 100 characters per line.*** 234 | 235 | The maximum line length for style-compliant Verilog code is 100 characters per 236 | line. 237 | 238 | Exceptions: 239 | 240 | - Any place where line wraps are impossible (for example, an include path 241 | might extend past 100 characters). 242 | 243 | [Line-wrapping](#line-wrapping) contains additional guidelines on how to wrap 244 | long lines. 245 | 246 | #### No Tabs 247 | 248 | ***Do not use tabs anywhere.*** 249 | 250 | Use spaces to indent or align text. See [Indentation](#indentation) for rules 251 | about indentation and wrapping. 252 | 253 | To convert tabs to spaces on any file, you can use the 254 | [UNIX `expand`](http://linux.die.net/man/1/expand) utility. 255 | 256 | #### No Trailing Spaces 257 | 258 | ***Delete trailing whitespace at the end of lines.*** 259 | 260 | ### Begin / End 261 | 262 | ***Use `begin` and `end` unless the whole statement fits on a single line.*** 263 | 264 | If a statement wraps at a block boundary, it must use `begin` and `end.` Only if 265 | a whole semicolon-terminated statement fits on a single line can `begin` and 266 | `end` be omitted. 267 | 268 | 👍 269 | ```systemverilog {.good} 270 | // Wrapped procedural block requires begin and end. 271 | always_ff @(posedge clk) begin 272 | q <= d; 273 | end 274 | ``` 275 | 276 | 👍 277 | ```systemverilog {.good} 278 | // The exception case, where begin and end may be omitted as the entire 279 | // structure fits on a single line. 280 | always_ff @(posedge clk) q <= d; 281 | ``` 282 | 283 | 👎 284 | ```systemverilog {.bad} 285 | // Incorrect because a wrapped statement must have begin and end. 286 | always_ff @(posedge clk) 287 | q <= d; 288 | ``` 289 | 290 | `begin` must be on the same line as the preceding keyword, and ends the line. 291 | `end` must start a new line. `end else begin` must be together on one line. The 292 | only exception is if `end` has a label, a following `else` should be on a new 293 | line. 294 | 295 | 👍 296 | ```systemverilog {.good} 297 | // "end else begin" are on the same line. 298 | if (condition) begin 299 | foo = bar; 300 | end else begin 301 | foo = bum; 302 | end 303 | ``` 304 | 305 | 👍 306 | ```systemverilog {.good} 307 | // begin/end are omitted because each semicolon-terminated statement fits on 308 | // a single line. 309 | if (condition) foo = bar; 310 | else foo = bum; 311 | ``` 312 | 313 | 👎 314 | ```systemverilog {.bad} 315 | // Incorrect because "else" must be on the same line as "end". 316 | if (condition) begin 317 | foo = bar; 318 | end 319 | else begin 320 | foo = bum; 321 | end 322 | ``` 323 | 324 | 👍 325 | ```systemverilog {.good} 326 | // An exception is made for labeled blocks. 327 | if (condition) begin : a 328 | foo = bar; 329 | end : a 330 | else begin : b 331 | foo = bum; 332 | end : b 333 | ``` 334 | 335 | The above style also applies to individual case items within a case statement. 336 | `begin` and `end` may be omitted if the entire case item (the case expression 337 | and the associated statement) fits on a single line. Otherwise, use the `begin` 338 | keyword on the same line as the case expression. 339 | 340 | 👍 341 | ```systemverilog {.good} 342 | // Consistent use of begin and end for each case item is good. 343 | unique case (state_q) 344 | StIdle: begin 345 | state_d = StA; 346 | end 347 | StA: begin 348 | state_d = StB; 349 | end 350 | StB: begin 351 | state_d = StIdle; 352 | foo = bar; 353 | end 354 | default: begin 355 | state_d = StIdle; 356 | end 357 | endcase 358 | ``` 359 | 360 | 👍 361 | ```systemverilog {.good} 362 | // Case items that fit on a single line may omit begin and end. 363 | unique case (state_q) 364 | StIdle: state_d = StA; 365 | StA: state_d = StB; 366 | StB: begin 367 | state_d = StIdle; 368 | foo = bar; 369 | end 370 | default: state_d = StIdle; 371 | endcase 372 | ``` 373 | 374 | 👎 375 | ```systemverilog {.bad} 376 | unique case (state_q) 377 | StIdle: // These lines are incorrect because we should not wrap 378 | state_d = StA; // case items at a block boundary without using begin 379 | StA: // and end. Case items should fit on a single line, or 380 | state_d = StB; // else the procedural block must have begin and end. 381 | StB: begin 382 | foo = bar; 383 | state_d = StIdle; 384 | end 385 | default: begin 386 | state_d = StIdle; 387 | end 388 | endcase 389 | ``` 390 | 391 | ### Indentation 392 | 393 | ***Indentation is two spaces per level.*** 394 | 395 | Use spaces for indentation. Do not use tabs. You should set your editor to emit 396 | spaces when you hit the tab key. 397 | 398 | #### Indented Sections 399 | 400 | Always add an additional level of indentation to the enclosed sections of all 401 | paired keywords. Examples of SystemVerilog keyword pairs: `begin / end`, 402 | `module / endmodule`, `package / endpackage`, `class / endclass`, 403 | `function / endfunction`. 404 | 405 | #### Line Wrapping 406 | 407 | When wrapping a long expression, indent the continued part of the expression by 408 | four spaces, like this: 409 | 410 | 👍 411 | ```systemverilog {.good} 412 | assign zulu = enabled && ( 413 | alpha < bravo && 414 | charlie < delta 415 | ); 416 | 417 | assign addr = addr_gen_function_with_many_params( 418 | thing, other_thing, long_parameter_name, x, y, 419 | extra_param1, extra_param2 420 | ); 421 | 422 | assign structure = '{ 423 | src: src, 424 | dest: dest, 425 | default: '0 426 | }; 427 | ``` 428 | 429 | Or, if it improves readability, align the continued part of the expression with 430 | a grouping open parenthesis or brace, like this: 431 | 432 | :+1: 433 | ```systemverilog {.good} 434 | assign zulu = enabled && (alpha < bravo && 435 | charlie < delta); 436 | 437 | assign addr = addr_gen_function(thing, other_thing, 438 | long_parameter_name, 439 | x, y); 440 | 441 | assign structure = '{src: src, 442 | dest: dest, 443 | default: '0}; 444 | ``` 445 | 446 | Operators in a wrapped expression can be placed at either the end or the 447 | beginning of each line, but this must be done consistently within a file. 448 | 449 | Open syntax characters such as `{` or `(` that end one line of a multi-line 450 | expression should be terminated with close characters (`}`, `)`) on their 451 | own line. Examples: 452 | 453 | :+1: 454 | ```systemverilog {.good} 455 | assign bus_concatenation = { 456 | bus_valid, 457 | bus_parity[7:0], 458 | bus_valid[63:0] 459 | }; 460 | 461 | inst_type inst_name1 ( 462 | .clk_i (clk), 463 | .data_valid_i(data_valid), 464 | .data_value_i(data_value), 465 | .data_ready_o(data_ready) 466 | ); 467 | ``` 468 | 469 | #### Preprocessor Directives 470 | 471 | ***Keep branching preprocessor directives left-aligned and un-indented.*** 472 | 473 | Keep branching preprocessor directives (`` `ifdef``, `` `ifndef``, `` `else``, 474 | `` `elsif``, `` `endif``) aligned to the left, even if they are nested. Indent 475 | the conditional branches of text as if the preprocessor directives were absent. 476 | Non-branching preprocessor directives must follow the same indentation rules as 477 | the regular code. 478 | 479 | 👍 480 | ```systemverilog {.good} 481 | package foo; 482 | `ifdef FOO // good: branching directive left-aligned 483 | `include "foo.sv"; // normal indentation for non-branching directives 484 | parameter bit A = 1; // normal indentation for the regular code 485 | `ifdef BAR // good: branching directive left-aligned 486 | parameter bit A = 2; 487 | `else 488 | parameter bit A = 3; 489 | `endif 490 | `endif 491 | endpackage : foo 492 | ``` 493 | 494 | Un-indented branching preprocessor directives disrupt the flow of reading to 495 | emphasize that there is conditional text. Leaving conditional branch text 496 | un-indented will result in post-preprocessed text looking properly indented. 497 | 498 | ### Spacing 499 | 500 | #### Comma-delimited Lists 501 | 502 | ***For multiple items on a line, one space must separate the comma and 503 | the next character.*** 504 | 505 | Additional whitespace is allowed for readability. 506 | 507 | 👍 508 | ```systemverilog {.good} 509 | bus = {addr, parity, data}; 510 | a = myfunc(lorem, ipsum, dolor, sit, amet, consectetur, adipiscing, elit, 511 | rhoncus); 512 | mymodule mymodule(.a(a), .b(b)); 513 | ``` 514 | 515 | 👎 516 | ```systemverilog {.bad} 517 | {parity,data} = bus; 518 | a = myfunc(a,b,c); 519 | mymodule mymodule(.a(a),.b(b)); 520 | ``` 521 | 522 | #### Tabular Alignment 523 | 524 | Tabular alignment groups two or more similar lines so that the identical parts are directly above one another. 525 | This alignment makes it easy to see which characters are the same and which characters are different between lines. 526 | 527 | ***The use of tabular alignment is generally encouraged.*** 528 | 529 | ***The use of tabular alignment is required for some constructs as detailed in the corresponding subsection of this guide.*** 530 | 531 | Constructs which require tabular alignment: 532 | 533 | * [Port expressions in module instantiations](#module-instantiation) 534 | 535 | Each block of code, separated by an empty line, is treated as separate "table". 536 | 537 | Use spaces, not tabs. 538 | 539 | For example: 540 | 541 | :+1: 542 | ```systemverilog 543 | logic [7:0] my_interface_data; 544 | logic [15:0] my_interface_address; 545 | logic my_interface_enable; 546 | 547 | logic another_signal; 548 | logic [7:0] something_else; 549 | ``` 550 | 551 | :+1: 552 | ```systemverilog 553 | mod u_mod ( 554 | .clk_i, 555 | .rst_ni, 556 | .sig_i (my_signal_in), 557 | .sig2_i (my_signal_out), 558 | // comment with no blank line maintains the block 559 | .in_same_block_i(my_signal_in), 560 | .sig3_i (something), 561 | 562 | .in_another_block_i(my_signal_in), 563 | .sig4_i (something) 564 | ); 565 | ``` 566 | 567 | #### Expressions 568 | 569 | ***Include whitespace on both sides of all binary operators.*** 570 | 571 | Use spaces around binary operators. Add sufficient whitespace to aid 572 | readability. 573 | 574 | For example: 575 | 576 | 👍 577 | ```systemverilog {.good} 578 | assign a = ((addr & mask) == My_addr) ? b[1] : ~b[0]; // good 579 | ``` 580 | 581 | is better than 582 | 583 | 👎 584 | ```systemverilog {.bad} 585 | assign a=((addr&mask)==My_addr)?b[1]:~b[0]; // bad 586 | ``` 587 | 588 | **Exception:** when declaring a bit vector, it is acceptable to use the compact 589 | notation. For example: 590 | 591 | 👍 592 | ```systemverilog {.good} 593 | wire [WIDTH-1:0] foo; // this is acceptable 594 | wire [WIDTH - 1 : 0] foo; // fine also, but not necessary 595 | ``` 596 | 597 | When splitting alternation expressions into multiple lines, use a format that is 598 | similar to an equivalent if-then-else line. For example: 599 | 600 | 👍 601 | ```systemverilog {.good} 602 | assign a = ((addr & mask) == `MY_ADDRESS) ? 603 | matches_value : 604 | doesnt_match_value; 605 | ``` 606 | 607 | #### Array Dimensions in Declarations 608 | 609 | Add a space around packed dimensions. 610 | 611 | Do not add a space: 612 | 613 | - between identifier and unpacked dimensions. 614 | - between multiple dimensions. 615 | 616 | Applies to packed and unpacked arrays as well as dynamic arrays, associative 617 | arrays, and queues. 618 | 619 | 👍 620 | ```systemverilog {.good} 621 | logic [7:0][3:0] data[128][2]; 622 | typedef logic [31:0] word_t; 623 | bit bit_array[512]; 624 | data_t some_array[]; 625 | data_t some_map[addr_t]; 626 | data_t some_q[$]; 627 | ``` 628 | 629 | 👎 630 | ```systemverilog {.bad} 631 | // There must not be a space between dimensions. 632 | logic [7:0] [3:0] data[128] [2]; 633 | // There must be a space around packed dimensions. 634 | typedef logic[31:0]word_t; 635 | // There must not be a space between identifier and unpacked dimension. 636 | bit bit_array [512]; 637 | // Dynamic, associative, and queue "dimensions" are treated the same as unpacked 638 | // dimensions. There must not be a space. 639 | data_t some_array []; 640 | data_t some_map [addr_t]; 641 | data_t some_q [$]; 642 | ``` 643 | 644 | #### Parameterized Types 645 | 646 | ***Add one space before type parameters, except when the type is part 647 | of a qualified name.*** 648 | 649 | A qualified name contains at least one scope `::` operator connecting its 650 | segments. A space in a qualified name would break the continuity of a reference 651 | to one symbol, so it must not be added. Parameter lists must follow the 652 | [space-after-comma](#comma-delimited-lists) rule. 653 | 654 | 👍 655 | ```systemverilog {.good} 656 | my_fifo #(.WIDTH(4), .DEPTH(2)) my_fifo_nibble ... 657 | 658 | class foo extends bar #(32, 8); // unqualified base class 659 | ... 660 | endclass 661 | 662 | foo_h = my_class#(.X(1), .Y(0))::type_id::create("foo_h"); // static method call 663 | 664 | my_pkg::x_class#(8, 1) bar; // package-qualified name 665 | ``` 666 | 667 | 👎 668 | ```systemverilog {.bad} 669 | my_fifo#(.WIDTH(4), .DEPTH(2)) my_fifo_2by4 ... 670 | 671 | class foo extends bar#(32, 8); // unqualified base class 672 | ... 673 | endclass 674 | 675 | foo_h = my_class #(.X(1), .Y(0))::type_id::create("foo_h"); // static method call 676 | 677 | my_pkg::x_class #(8, 1) bar; // package-qualified name 678 | ``` 679 | 680 | #### Labels 681 | 682 | ***When labeling code blocks, add one space before and after the colon.*** 683 | 684 | For example: 685 | 686 | 👍 687 | ```systemverilog {.good} 688 | begin : foo 689 | end : foo 690 | ``` 691 | 692 | 👎 693 | ```systemverilog {.bad} 694 | end:bar // There must be a space before and after the colon. 695 | endmodule: foobar // There must be a space before the colon. 696 | ``` 697 | 698 | #### Case items 699 | 700 | There must be no whitespace before a case item's colon; there must be at least 701 | one space after the case item's colon. 702 | 703 | The `default` case item must include a colon. 704 | 705 | For example: 706 | 707 | 👍 708 | ```systemverilog {.good} 709 | unique case (my_state) 710 | StInit: $display("Shall we begin"); 711 | StError: $display("Oh boy this is Bad"); 712 | default: begin 713 | my_state = StInit; 714 | interrupt = 1; 715 | end 716 | endcase 717 | ``` 718 | 719 | 👎 720 | ```systemverilog {.bad} 721 | unique case (1'b1) 722 | (my_state == StError) : interrupt = 1; // Excess whitespace before colon 723 | default:begin end // Missing space after colon 724 | endcase 725 | ``` 726 | 727 | #### Function And Task Calls 728 | 729 | ***Function and task calls must not have any spaces between the function 730 | name or task name and the open parenthesis.*** 731 | 732 | For example: 733 | 734 | 👍 735 | ```systemverilog {.good} 736 | process_packet(pkt); 737 | ``` 738 | 739 | 👎 740 | ```systemverilog {.bad} 741 | process_packet (pkt); // There must not be a space before "(" 742 | ``` 743 | 744 | #### Macro Calls 745 | 746 | ***Macro calls must not have any spaces between the macro name and the 747 | open parenthesis.*** 748 | 749 | For example: 750 | 751 | 👍 752 | ```systemverilog {.good} 753 | `uvm_error(ID, "you fail") 754 | `ASSERT(name, a & b, clk, rst) 755 | ``` 756 | 757 | 👎 758 | ```systemverilog {.bad} 759 | `uvm_error (ID, "you fail") // There must not be a space before "(" 760 | `ASSERT (name, a & b, clk, rst) 761 | ``` 762 | 763 | #### Line Continuation 764 | 765 | ***It is mandatory to right-align line continuations.*** 766 | 767 | Aligning line continuations ('`\ `' character) helps visually mark the end of a 768 | multi-line macro. The position of alignment only needs to be beyond the 769 | rightmost extent of a multi-line macro by at least one space, when a space does 770 | not split a token, but should not exceed the maximum line length. 771 | 772 | ```systemverilog 773 | `define REALLY_LONG_MACRO(arg1, arg2, arg3) \ 774 | do_something(arg1); \ 775 | do_something_else(arg2); \ 776 | final_action(arg3); 777 | ``` 778 | 779 | #### Space Around Keywords 780 | 781 | ***Include whitespace before and after SystemVerilog keywords.*** 782 | 783 | Do not include a whitespace: 784 | 785 | - before keywords that immediately follow a group opening, such as an open 786 | parenthesis. 787 | - before a keyword at the beginning of a line. 788 | - after a keyword at the end of a line. 789 | 790 | For example: 791 | 792 | ```systemverilog 793 | // Normal indentation before if. Include a space after if. 794 | if (foo) begin 795 | end 796 | // Include a space after always, but not before posedge. 797 | always_ff @(posedge clk) begin 798 | end 799 | ``` 800 | 801 | ### Parentheses 802 | 803 | ***Use parentheses to make operations unambiguous.*** 804 | 805 | In any instance where a reasonable human would need to expend thought or refer 806 | to an operator precedence chart, use parentheses instead to make the order of 807 | operations unambiguous. 808 | 809 | #### Ternary Expressions 810 | 811 | ***Ternary expressions nested in the true condition of another ternary 812 | expression must be enclosed in parentheses.*** 813 | 814 | For example: 815 | 816 | 👍 817 | ```systemverilog {.good} 818 | assign foo = condition_a ? (condition_a_x ? x : y) : b; 819 | ``` 820 | 821 | While the following nested ternary has only one meaning to the compiler, the 822 | meaning can be unclear and error-prone to humans: 823 | 824 | 👎 825 | ```systemverilog {.bad} 826 | assign foo = condition_a ? condition_a_x ? x : y : b; 827 | ``` 828 | 829 | ***Parentheses may be omitted if the code formatting conveys the same 830 | information, for example when describing a priority mux.*** 831 | 832 | 👍 833 | ```systemverilog {.good} 834 | assign foo = condition_a ? a : 835 | condition_b ? b : not_a_nor_b; 836 | ``` 837 | 838 | ### Comments 839 | 840 | ***C++ style comments (`// foo`) are preferred. C style comments 841 | (`/* bar */`) can also be used.*** 842 | 843 | A comment on its own line describes the code that follows. A comment on a line 844 | with code describes that line of code. 845 | 846 | For example: 847 | 848 | ```systemverilog 849 | // This comment describes the following module. 850 | module foo; 851 | ... 852 | endmodule : foo 853 | 854 | localparam bit ValBaz = 1; // This comment describes the item to the left. 855 | ``` 856 | 857 | It can sometimes be useful to structure the code using header-style comments in 858 | order to separate different functional parts (like FSMs, the main datapath or 859 | registers) within a module. In that case, the preferred style is a single-line 860 | section name, framed with `//` C++ style comments as follows: 861 | 862 | ```systemverilog 863 | module foo; 864 | 865 | //////////////// 866 | // Controller // 867 | //////////////// 868 | ... 869 | 870 | /////////////////////// 871 | // Main ALU Datapath // 872 | /////////////////////// 873 | ... 874 | 875 | endmodule : foo 876 | ``` 877 | 878 | If the designer would like to use comments to mark the beginning/end of a 879 | particular section for better readability (e.g. in nested for loop blocks), the 880 | preferred way is to use a single-line comment with no extra delineators, as 881 | shown in the examples below. 882 | 883 | 👍 884 | ```systemverilog {.good} 885 | // begin: iterate over foobar 886 | for (...) begin 887 | ... 888 | end 889 | // end: iterate over foobar 890 | ``` 891 | 892 | 👍 893 | ```systemverilog {.good} 894 | for (...) begin // iterate over foobar 895 | ... 896 | end // iterate over foobar 897 | ``` 898 | 899 | 👎 900 | ```systemverilog {.bad} 901 | //-------------------------- iterate over foobar ------------------------------- 902 | for (...) begin 903 | ... 904 | end 905 | //-------------------------- iterate over foobar ------------------------------- 906 | ``` 907 | 908 | 👎 909 | ```systemverilog {.bad} 910 | /////////////////////////////// 911 | // begin iterate over foobar // 912 | /////////////////////////////// 913 | for (...) begin 914 | ... 915 | end 916 | /////////////////////////////// 917 | // end iterate over foobar // 918 | /////////////////////////////// 919 | ``` 920 | 921 | 922 | ### Declarations 923 | 924 | ***Signals must be declared before they are used. This means that 925 | implicit net declarations must not be used.*** 926 | 927 | Within modules, it is **recommended** that signals, types, enums, and 928 | localparams be declared close to their first use. This makes it easier for the 929 | reader to find the declaration and see the signal type. 930 | 931 | ### Basic Template 932 | 933 | ***A template that demonstrates many of the items is given below.*** 934 | 935 | Template: 936 | 937 | ```systemverilog 938 | // Copyright lowRISC contributors. 939 | // Licensed under the Apache License, Version 2.0, see LICENSE for details. 940 | // SPDX-License-Identifier: Apache-2.0 941 | // 942 | // One line description of the module 943 | 944 | module my_module #( 945 | parameter Width = 80, 946 | parameter Height = 24 947 | ) ( 948 | input clk_i, 949 | input rst_ni, 950 | input req_valid_i, 951 | input [Width-1:0] req_data_i, 952 | output req_ready_o, 953 | ... 954 | ); 955 | 956 | logic [Width-1:0] req_data_masked; 957 | 958 | submodule u_submodule ( 959 | .clk_i, 960 | .rst_ni, 961 | .req_valid_i, 962 | .req_data_i (req_data_masked), 963 | .req_ready_o(req_ready), 964 | ... 965 | ); 966 | 967 | always_comb begin 968 | req_data_masked = req_data_i; 969 | case (fsm_state_q) 970 | ST_IDLE: begin 971 | req_data_masked = req_data_i & MASK_IDLE; 972 | ... 973 | end 974 | 975 | ... 976 | 977 | endmodule 978 | ``` 979 | 980 | ## Naming 981 | 982 | ### Summary 983 | 984 | | Construct | Style | 985 | | ------------------------------------ | ----------------------- | 986 | | Declarations (module, class, package, interface) | `lower_snake_case` | 987 | | Instance names | `lower_snake_case` | 988 | | Signals (nets and ports) | `lower_snake_case` | 989 | | Variables, functions, tasks | `lower_snake_case` | 990 | | Named code blocks | `lower_snake_case` | 991 | | \`define macros | `ALL_CAPS` | 992 | | Tunable parameters for parameterized modules, classes, and interfaces | `UpperCamelCase` | 993 | | Constants | `ALL_CAPS` or `UpperCamelCase` | 994 | | Enumeration types | `lower_snake_case_e` | 995 | | Other typedef types | `lower_snake_case_t` | 996 | | Enumerated value names | `UpperCamelCase` | 997 | 998 | ### Constants 999 | 1000 | ***Declare global constants using parameters in the project package file.*** 1001 | 1002 | In this context, **constants** are distinct from tuneable parameters for objects 1003 | such as parameterized modules, classes, etc. 1004 | 1005 | Explicitly declare the type for constants. 1006 | 1007 | When declaring a constant: 1008 | 1009 | * within a package use `parameter`. 1010 | * within a module or class use `localparam`. 1011 | 1012 | The preferred method of defining constants is to declare a `package` and declare 1013 | all constants as a `parameter` within that package. If the constants are to be 1014 | used in only one file, it is acceptable to keep them defined within that file 1015 | rather than a separate package. 1016 | 1017 | Define project-wide constants in the project's main package. 1018 | 1019 | Other packages may also be declared with their own `parameter` constants to 1020 | facilitate the creation of IP that may be re-used across many projects. 1021 | 1022 | The preferred naming convention for all immutable constants is to use `ALL_CAPS`, but there are times when the use of `UpperCamelCase` might be considered more natural. 1023 | 1024 | | Constant Type | Style Preference | Conversation | 1025 | | ---- | ---- | ---- | 1026 | | \`define | `ALL_CAPS` | Truly constant | 1027 | | module parameter | `UpperCamelCase` | truly modifiable by instantiation, not constant | 1028 | | derived localparam | `UpperCamelCase` | while not modified directly, still tracks module parameter | 1029 | | tuneable localparam | `UpperCamelCase` | while not expected to change upon final RTL version, is used by designer to explore the design space conveniently | 1030 | | true localparam constant | `ALL_CAPS` | Example `localparam OP_JALR = 8'hA0;` | 1031 | | enum member true constant | `ALL_CAPS` | Example `typedef enum ... { OP_JALR = 8'hA0;` | 1032 | | enum set member | `ALL_CAPS` or `UpperCamelCase` | Example `typedef enum ... { ST_IDLE, ST_FRAME_START, ST_DYN_INSTR_READ ...`, `typedef enum ... { StIdle, StFrameStart, StDynInstrRead...`. A collection of arbitrary values, could be either convention. | 1033 | 1034 | The units for a constant should be described in the symbol name, unless the 1035 | constant is unitless or the units are "bits." For example, `FooLengthBytes`. 1036 | 1037 | Example: 1038 | 1039 | 👍 1040 | ```systemverilog {.good} 1041 | // package-scope 1042 | package my_pkg; 1043 | 1044 | parameter int unsigned NUM_CPU_CORES = 64; 1045 | // reference elsewhere as my_pkg::NUM_CPU_CORES 1046 | 1047 | endpackage 1048 | ``` 1049 | 1050 | #### Parameterized Objects (modules, etc.) 1051 | 1052 | ***Use `parameter` to parameterize, and `localparam` to declare 1053 | module-scoped constants. Within a package, use `parameter`.*** 1054 | 1055 | You can create parameterized modules, classes, and interfaces to facilitate 1056 | design re-use. 1057 | 1058 | Use the keyword `parameter` within the `module` declaration of a parameterized 1059 | module to indicate what parameters the user is expected to tune at 1060 | instantiation. The preferred naming convention for all parameters is 1061 | `UpperCamelCase`. Some projects may choose to use `ALL_CAPS` to differentiate 1062 | tuneable parameters from constants. 1063 | 1064 | Derived parameters within the `module` declaration should use `localparam`. 1065 | An example is shown below. 1066 | 1067 | ```systemverilog 1068 | module modname #( 1069 | parameter int Depth = 2048, // 8kB default 1070 | localparam int Aw = $clog2(Depth) // derived parameter 1071 | ) ( 1072 | ... 1073 | ); 1074 | 1075 | endmodule 1076 | ``` 1077 | 1078 | `` `define`` and `defparam` should never be used to parameterize a module. 1079 | 1080 | Use [package parameters](#constants) to transmit global constants through a 1081 | hierarchy instead of parameters. To declare a constant whose scope is internal 1082 | to the particular SystemVerilog module, [use `localparam` instead](#constants). 1083 | 1084 | Examples of when to use parameterized modules: 1085 | 1086 | - When multiple instances of a module will be instantiated, and need to be 1087 | differentiated by a parameter. 1088 | - As a means of specializing a module for a specific bus width. 1089 | - As a means of documenting which global parameters are permitted to change 1090 | within the module. 1091 | 1092 | Explicitly declare the type for parameters. 1093 | 1094 | Use the type of the parameter to help constrain the legal range. E.g. `int 1095 | unsigned` for general non-negative integer values, `bit` for boolean values. 1096 | Any further restrictions on tuneable parameter values must be documented with 1097 | assertions. 1098 | 1099 | Tuneable parameter values should always have reasonable defaults. 1100 | 1101 | For additional reading, see [New Verilog-2001 Techniques for Creating 1102 | Parameterized 1103 | Models](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-884-complex-digital-systems-spring-2005/related-resources/parameter_models.pdf). 1104 | 1105 | ### Macro Definitions 1106 | 1107 | ***Macros should be ALL\_CAPITALS with underscores.*** 1108 | 1109 | Macros should be all capitals with underscores. 1110 | 1111 | A **global define** is a tick-defined macro in a header file that is shared by 1112 | all source files in a project. To reduce namespace collisions, global defines 1113 | should be prefixed by the name of a group of related macros, followed by a pair 1114 | of underscores: 1115 | 1116 | ```systemverilog 1117 | // The following two constants are in the FOO namespace of the 1118 | // SN chip. 1119 | `define SN_FOO__ALPHA_BETA 5 1120 | `define SN_FOO__GAMMA_OMEGA 6 1121 | ``` 1122 | 1123 | A **local define** is a tick-defined macro that should only be used within the 1124 | scope of a single local file. It must be explicitly undefined after use, to 1125 | avoid polluting the global macro namespace. To indicate that a macro is only 1126 | meant to be used in the local scope, the macro name should be prefixed with a 1127 | single underscore. 1128 | 1129 | To ensure that local defines stay local, be careful not to `` `include`` other 1130 | files between the macro definition and `` `undef``. 1131 | 1132 | Example: 1133 | 1134 | ```systemverilog 1135 | `define _MAKE_THING(_x) \ 1136 | thing i_thing_##_x (.clk(clk), .i(i##_x) .o(o##_x)); 1137 | `_MAKE_THING(a) 1138 | `_MAKE_THING(b) 1139 | `_MAKE_THING(c) 1140 | `undef _MAKE_THING 1141 | ``` 1142 | 1143 | ### Suffixes 1144 | 1145 | Suffixes are used in several places to give guidance to intent. The following 1146 | table lists the suffixes that have special meaning. 1147 | 1148 | | Suffix(es) | Arena | Intent | 1149 | | --- | :---: | --- | 1150 | | `_e` | typedef | Enumerated types | 1151 | | `_t` | typedef | Other typedefs, including signal clusters | 1152 | | `_n` | signal name | Active low signal | 1153 | | `_n`, `_p` | signal name | Differential pair, active low and active high | 1154 | | `_d`, `_q` | signal name | Input and output of register | 1155 | | `_q2`,`_q3`, etc | signal name | Pipelined versions of signals; `_q` is one cycle of latency, `_q2` is two cycles, `_q3` is three, etc | 1156 | | `_i`, `_o`, `_io` | signal name | Module inputs, outputs, and bidirectionals | 1157 | 1158 | When multiple suffixes are necessary use the following guidelines: 1159 | 1160 | * Guidance suffixes are added together and not separated by additional `_` 1161 | characters (`_ni` not `_n_i`) 1162 | * If the signal is active low `_n` will be the first suffix 1163 | * If the signal is a module input/output the letters will come last. 1164 | * It is not mandatory to propagate `_d` and `_q` to module boundaries. 1165 | 1166 | Example: 1167 | 1168 | 👍 1169 | ```systemverilog {.good} 1170 | module simple ( 1171 | input clk_i, 1172 | input rst_ni, // Active low reset 1173 | 1174 | // writer interface 1175 | input [15:0] data_i, 1176 | input valid_i, 1177 | output ready_o, 1178 | 1179 | // bi-directional bus 1180 | inout [7:0] driver_io, // Bi directional signal 1181 | 1182 | // Differential pair output 1183 | output lvds_po, // Positive part of the differential signal 1184 | output lvds_no // Negative part of the differential signal 1185 | ); 1186 | 1187 | logic valid_d, valid_q, valid_q2, valid_q3; 1188 | assign valid_d = valid_i; // next state assignment 1189 | 1190 | always_ff @(posedge clk_i or negedge rst_ni) begin 1191 | if (!rst_ni) begin 1192 | valid_q <= '0; 1193 | valid_q2 <= '0; 1194 | valid_q3 <= '0; 1195 | end else begin 1196 | valid_q <= valid_d; 1197 | valid_q2 <= valid_q; 1198 | valid_q3 <= valid_q2; 1199 | end 1200 | end 1201 | 1202 | assign ready_o = valid_q3; // three clock cycles delay 1203 | 1204 | endmodule // simple 1205 | ``` 1206 | 1207 | ### Enumerations 1208 | 1209 | ***Name enumeration types `snake_case_e`. Name enumeration values `ALL_CAPS` or 1210 | `UpperCamelCase`.*** 1211 | 1212 | Always name `enum` types using `typedef`. The storage type of any enumerated 1213 | type must be specified. For synthesizable enums, the storage type must be a 1214 | 4-state data type (`logic` rather than `bit`). 1215 | 1216 | Anonymous `enum` types are not allowed as they make it harder to use the type in 1217 | other places throughout the project and across projects. 1218 | 1219 | Enumeration type names should contain only lower-case alphanumeric characters 1220 | and underscores. You must suffix enumeration type names with `_e`. 1221 | 1222 | Enumeration value names (constants) should typically be `ALL_CAPS`, for example, 1223 | `READY_TO_SEND`, to reflect their constant nature, especially for truly unchangeable 1224 | values like defined opcode assignments. There are times when `UpperCamelCase` 1225 | might be preferred, when the enumerated type's assigned value is effectively a 1226 | don't care to the designer, like state machine values. See the conversation on 1227 | [constants](#constants) for a discussion on how to think of this recommendation. 1228 | 1229 | 👍 1230 | ```systemverilog {.good} 1231 | typedef enum logic [7:0] { // 8-bit opcodes 1232 | OP_JALR = 8'hA0, 1233 | OP_ADDI = 8'h47, 1234 | OP_LDW = 8'h0B 1235 | } opcode_e; 1236 | opcode_e op_val; 1237 | ``` 1238 | 1239 | 👍 1240 | ```systemverilog {.good} 1241 | typedef enum logic [1:0] { // A 2-bit enumerated type 1242 | ACC_WRITE, 1243 | ACC_READ, 1244 | ACC_PAUSE 1245 | } access_e; // new named type is created 1246 | access_e req_access, resp_access; 1247 | ``` 1248 | 1249 | 👍 1250 | ```systemverilog {.good} 1251 | typedef enum logic [1:0] { // A 2-bit enumerated type 1252 | AccWrite, 1253 | AccRead, 1254 | AccPause 1255 | } access_e; // new named type is created 1256 | access_e req_access, resp_access; 1257 | ``` 1258 | 1259 | 👎 1260 | ```systemverilog {.bad} 1261 | enum { // Typedef is missing, storage type is missing. 1262 | Write, 1263 | Read 1264 | } req_access, resp_access; // anonymous enum type 1265 | ``` 1266 | 1267 | ### Signal Naming 1268 | 1269 | ***Use `lower_snake_case` when naming signals.*** 1270 | 1271 | In this context, a **signal** is meant to mean a net, variable, or port within a 1272 | SystemVerilog design. 1273 | 1274 | Signal names may contain lowercase alphanumeric characters and underscores. 1275 | 1276 | Signal names should never end with an underscore followed by a number (for 1277 | example, `foo_1`, `foo_2`, etc.). Many synthesis tools map buses into nets using 1278 | that naming convention, so similarly named nets can lead to confusion when 1279 | examining a synthesized netlist. 1280 | 1281 | Reserved [Verilog](http://www.xilinx.com/support/documentation/sw_manuals/xilinx13_1/ite_r_verilog_reserved_words.htm) or SystemVerilog keywords may never be used as names. 1282 | 1283 | When interoperating with different languages, be mindful not to use keywords 1284 | from other languages. 1285 | 1286 | #### Use descriptive names 1287 | 1288 | ***Names should describe what a signal's purpose is.*** 1289 | 1290 | Use whole words. Avoid abbreviations and contractions except in the most common 1291 | places. Favor descriptive signal names over brevity. 1292 | 1293 | #### Prefixes 1294 | 1295 | Use common prefixes to identify groups of signals that operate together. For 1296 | example, all elements of an AXI-S interface would share a prefix: `foo_valid`, 1297 | `foo_ready`, and `foo_data`. 1298 | 1299 | Additionally, prefixes should be used to clearly label which signal is in which 1300 | clock group for any module with multiple clocks. See the section on [clock 1301 | domains](#clocks) for more details. 1302 | 1303 | Examples: 1304 | 1305 | - Signals associated with controlling a blockram might share a `bram_` prefix. 1306 | - Signals that are synchronous with `clk_dram` rather than `clk` should share 1307 | a `dram_` prefix. 1308 | 1309 | Code example: 1310 | 1311 | 👍 1312 | ```systemverilog {.good} 1313 | module fifo_controller ( 1314 | input clk_i, 1315 | input rst_ni, 1316 | 1317 | // writer interface 1318 | input [15:0] wr_data_i, 1319 | input wr_valid_i, 1320 | output wr_ready_o, 1321 | 1322 | // reader interface 1323 | output [15:0] rd_data_o, 1324 | output rd_valid_o, 1325 | output [7:0] rd_fullness_o, 1326 | input rd_ack_i, 1327 | 1328 | // memory interface: 1329 | output [7:0] mem_addr_o, 1330 | output [15:0] mem_wdata_o, 1331 | output mem_we_o, 1332 | input [15:0] mem_rdata_i 1333 | ); 1334 | ``` 1335 | 1336 | This naming convention makes it easier to map port names onto similar signal 1337 | names using simple and consistent rules. See the section on [Hierarchical 1338 | Consistency](#hierarchical-consistency) for more information. 1339 | 1340 | #### Hierarchical consistency 1341 | 1342 | ***The same signal should have the same name at any level of the hierarchy.*** 1343 | 1344 | A signal that connects to a port of an instance should have the same name as 1345 | that port. By proceeding in this manner, signals that are directly connected 1346 | should maintain the same name at any level of hierarchy. 1347 | 1348 | Exceptions to this convention are expected, such as: 1349 | 1350 | * When connecting a port to an element of an array of signals. 1351 | 1352 | * When mapping a generic port name to something more specific to the design. 1353 | For example, two generic blocks, one with a `host_bus` port and one with a 1354 | `device_bus` port might be connected by a `foo_bar_bus` signal. 1355 | 1356 | In each exceptional case, care should be taken to make the mapping of port names 1357 | to signal names as unambiguous and consistent as possible. 1358 | 1359 | ### Clocks 1360 | 1361 | ***All clock signals must begin with `clk`.*** 1362 | 1363 | The main system clock for a design must be named `clk`. It is acceptable to use 1364 | `clk` to refer to the default clock that the majority of the logic in a module 1365 | is synchronous with. 1366 | 1367 | If a module contains multiple clocks, the clocks that are not the system clock 1368 | should be named with a unique identifier, preceded by the `clk_` prefix. For 1369 | example: `clk_dram`, `clk_axi`, etc. Note that this prefix will be 1370 | used to identify other signals in that clock domain. 1371 | 1372 | ### Resets 1373 | 1374 | ***Resets are active-low and asynchronous. The default name is `rst_n`.*** 1375 | 1376 | Chip wide all resets are defined as active low and asynchronous. Thus they are 1377 | defined as tied to the asynchronous reset input of the associated standard 1378 | cell registers. 1379 | 1380 | The default name is `rst_n`. If they must be distinguished by their clock, the 1381 | clock name should be included in the reset name like `rst_domain_n`. 1382 | 1383 | SystemVerilog allows either of the following syntax styles, but the style 1384 | guide prefers the former. 1385 | 1386 | ```systemverilog 1387 | // preferred 1388 | always_ff @(posedge clk or negedge rst_n) begin 1389 | if (!rst_n) begin 1390 | q <= 1'b0; 1391 | end else begin 1392 | q <= d; 1393 | end 1394 | end 1395 | 1396 | // legal but not preferred 1397 | always_ff @(posedge clk, negedge rst_n) begin 1398 | if (!rst_n) begin 1399 | q <= 1'b0; 1400 | end else begin 1401 | q <= d; 1402 | end 1403 | end 1404 | ``` 1405 | 1406 | ## Language Features 1407 | 1408 | ### Preferred SystemVerilog Constructs 1409 | 1410 | Use these SystemVerilog constructs instead of their Verilog-2001 equivalents: 1411 | 1412 | - `always_comb` is required over `always @*`. 1413 | - `logic` is preferred over `reg` and `wire`. 1414 | - Top-level `parameter` declarations are preferred over `` `define`` globals. 1415 | 1416 | 1417 | ### Package Dependencies 1418 | 1419 | ***Packages must not have cyclic dependencies.*** 1420 | 1421 | Package files may depend on constants and types in other package files, but 1422 | there must not be any cyclic dependencies. That is: if package A depends on a 1423 | constant from package B, package B must not depend on anything from package A. 1424 | While cyclic dependencies are permitted by the SystemVerilog language 1425 | specification, their use can break some tools. 1426 | 1427 | For example: 1428 | 1429 | ```systemverilog 1430 | package foo; 1431 | 1432 | // Package "bar" must not depend on anything in "foo": 1433 | parameter int unsigned PageSizeBytes = 16 * bar::Kibi; 1434 | 1435 | endpackage 1436 | ``` 1437 | 1438 | ### Module Declaration 1439 | 1440 | ***Use the Verilog-2001 full port declaration style, and use the format 1441 | below.*** 1442 | 1443 | Use the Verilog-2001 combined port and I/O declaration style. Do not use the 1444 | Verilog-95 list style. The port declaration in the module statement should fully 1445 | declare the port name, type, and direction. 1446 | 1447 | The opening parenthesis should be on the same line as the module declaration, 1448 | and the first port should be declared on the following line. 1449 | 1450 | The closing parenthesis should be on its own line, in column zero. 1451 | 1452 | Indentation for module declaration follows the standard indentation 1453 | rule of two space indentation. 1454 | 1455 | The clock port(s) must be declared first in the port list, followed by any and 1456 | all reset inputs. 1457 | 1458 | Example without parameters: 1459 | 1460 | 👍 1461 | ```systemverilog {.good} 1462 | module foo ( 1463 | input clk_i, 1464 | input rst_ni, 1465 | input [7:0] d_i, 1466 | output logic [7:0] q_o 1467 | ); 1468 | ``` 1469 | 1470 | Example with parameters: 1471 | 1472 | 👍 1473 | ```systemverilog {.good} 1474 | module foo #( 1475 | parameter int unsigned Width = 8, 1476 | ) ( 1477 | input clk_i, 1478 | input rst_ni, 1479 | input [Width-1:0] d_i, 1480 | output logic [Width-1:0] q_o 1481 | ); 1482 | ``` 1483 | 1484 | Do not use Verilog-95 style: 1485 | 1486 | 👎 1487 | ```systemverilog {.bad} 1488 | // WRONG: 1489 | module foo(a, b, c d); 1490 | input wire [2:0] a; 1491 | output logic b; 1492 | ... 1493 | ``` 1494 | 1495 | ### Module Instantiation 1496 | 1497 | ***Use named ports to fully specify all instantiations.*** 1498 | 1499 | When connecting signals to ports for an instantiation, use the named port style, 1500 | like this: 1501 | 1502 | ```systemverilog 1503 | my_module i_my_instance ( 1504 | .clk_i (clk_i), 1505 | .rst_ni(rst_ni), 1506 | .d_i (from_here), 1507 | .q_o (to_there) 1508 | ); 1509 | ``` 1510 | 1511 | If the port and the connecting signal have the same name, you can use the 1512 | `.port` syntax (without parentheses) to indicate connectivity. For example: 1513 | 1514 | ```systemverilog 1515 | my_module i_my_instance ( 1516 | .clk_i, 1517 | .rst_ni, 1518 | .d_i (from_here), 1519 | .q_o (to_there) 1520 | ); 1521 | ``` 1522 | 1523 | All declared ports must be present in the instantiation blocks. Unconnected 1524 | outputs must be explicitly written as no-connects (for example: 1525 | `.output_port()`), and unused inputs must be explicitly tied to ground (for 1526 | example: `.unused_input_port(8'd0)`) 1527 | 1528 | `.*` is not permitted. 1529 | 1530 | Do not use positional arguments to connect signals to ports. 1531 | 1532 | Instantiate ports in the same order as they are defined in the module. 1533 | 1534 | Align port expressions in [tabular style](#tabular-alignment). 1535 | Do not include whitespace before the opening parenthesis of the longest port name. 1536 | Do not include whitespace after the opening parenthesis, or before the closing parenthesis enclosing the port expression. 1537 | 1538 | :-1: 1539 | ```systemverilog 1540 | mod u_mod( 1541 | .clk_i, 1542 | .rst_ni, 1543 | 1544 | // Not allowed: avoid leading/trailing whitespace in expressions. 1545 | .sig_1_i( sig_1 ), 1546 | .sig_2_i( sig_2 ) 1547 | ); 1548 | 1549 | mod u_mod( 1550 | .clk_i, 1551 | .rst_ni, 1552 | 1553 | .short_sig_i (sig_1), 1554 | // Not allowed: avoid whitespace between the longest signal name and the opening parenthesis. 1555 | .a_very_long_signal_name_indeed_i (sig_2) 1556 | ); 1557 | ``` 1558 | 1559 | ***Use named parameters for all instantiations.*** 1560 | 1561 | When parameterizing an instance, specify the parameter using the named parameter 1562 | style. An exception is if there is only one parameter that is obvious such as 1563 | register width, then the instantiation can be implicit. 1564 | 1565 | Indentation for module instantiation follows the standard indentation 1566 | rule of two space indentation. 1567 | 1568 | ```systemverilog 1569 | my_module #( 1570 | .Height(5), 1571 | .Width(10) 1572 | ) my_module ( 1573 | // ... 1574 | ); 1575 | 1576 | my_reg #(16) my_reg0 ( 1577 | .clk_i, 1578 | .rst_ni, 1579 | .d_i (data_in), 1580 | .q_o (data_out) 1581 | ); 1582 | ``` 1583 | Do not specify parameters positionally, unless there is only one parameter and 1584 | the intent of that parameter is obvious, such as the width for a register 1585 | instance. 1586 | 1587 | Do not use `defparam`. 1588 | 1589 | ***Do not instantiate recursively.*** 1590 | 1591 | Modules may not instantiate themselves recursively. 1592 | 1593 | ### Constants 1594 | 1595 | ***It is recommended to use symbolicly named constants instead of 1596 | raw numbers.*** 1597 | 1598 | Try to give commonly used constants symbolic names rather than repeatedly typing 1599 | raw numbers. 1600 | 1601 | Local constants should always be declared using `localparam`. 1602 | 1603 | Global constants should always be declared in a separate `.vh` or `.svh` include 1604 | file. 1605 | 1606 | For SystemVerilog code, global constants should always be declared as package 1607 | parameters. For Verilog-2001 compatible code, top-level parameters are not 1608 | supported and `` `define`` macros must be used instead. 1609 | 1610 | Include the units for a constant as a suffix in the constant's symbolic name. 1611 | The exceptions to this rule are for constants that are inherently unitless, or 1612 | if the constant is describing the default unit type, "bits." 1613 | 1614 | Example: 1615 | 1616 | ```systemverilog 1617 | localparam int unsigned INTERFACE_WIDTH = 64; // Bits 1618 | localparam int unsigned INTERFACE_WIDTH_BYTES = (INTERFACE_WIDTH + 7) / 8; 1619 | localparam int unsigned INTERFACE_WIDTH_64B_WORDS = (INTERFACE_WIDTH + 63) / 64; 1620 | localparam int unsigned IMAGE_WIDTH_PIXELS = 640; 1621 | localparam int unsigned MEGA = 1000 * 1000; // Unitless 1622 | localparam int unsigned MEBI = 1024 * 1024; // Unitless 1623 | localparam int unsigned SYSTEM_CLOCK_HZ = 200 * MEGA; 1624 | ``` 1625 | 1626 | ### Signal Widths 1627 | 1628 | ***Be careful about signal widths.*** 1629 | 1630 | #### Always be explicit about the widths of number literals. 1631 | 1632 | Examples: 1633 | 1634 | 👍 1635 | ```systemverilog {.good} 1636 | localparam logic [3:0] bar = 4'd4; 1637 | 1638 | assign foo = 8'd2; 1639 | ``` 1640 | 1641 | 👎 1642 | ```systemverilog {.bad} 1643 | localparam logic [3:0] bar = 4; 1644 | 1645 | assign foo = 2; 1646 | ``` 1647 | 1648 | Exceptions: 1649 | 1650 | * When using parameterized widths, it is acceptable to simply use `1'b1` (e.g. 1651 | when incrementing) rather than contrivances such as 1652 | `{{(Bus_width-1){1'b0}}, 1'b1}`. Alternately it could be written as `Bus_width'(1)`. 1653 | * It is acceptable to use the '0 construct to create an automatic correctly 1654 | sized zero. 1655 | * Literals assigned to integer variants (e.g. byte, shortint, int, integer, 1656 | and longint) do not need an explicit width. 1657 | 1658 | #### Port connections on module instances must always match widths correctly. 1659 | 1660 | It is recommended to use explicit widths, rather than relying on Verilog's 1661 | implicit zero-extension and truncation operations, whenever practical. 1662 | 1663 | Examples: 1664 | 1665 | 👍 1666 | ```systemverilog {.good} 1667 | my_module i_module ( 1668 | .thirty_two_bit_input({16'd0, sixteen_bit_word}) 1669 | ); 1670 | ``` 1671 | 1672 | 👎 1673 | ```systemverilog {.bad} 1674 | my_module i_module ( 1675 | // Incorrectly implicitly extends from 16 bit to 32 bit 1676 | .thirty_two_bit_input(sixteen_bit_word) 1677 | ); 1678 | ``` 1679 | 1680 | #### Do not use multi-bit signals in a boolean context. 1681 | 1682 | Rather than letting boolean operations and if expressions reduce a multi-bit 1683 | signal to a single bit, explicitly compare the multi-bit signal to 0. The 1684 | implicit conversion can hide subtle logic bugs. 1685 | 1686 | Examples; 1687 | 1688 | 👍 1689 | ```systemverilog {.good} 1690 | logic [3:0] a, b; 1691 | logic out; 1692 | 1693 | assign out = (a != '0) && (b == '0); 1694 | 1695 | always_comb begin 1696 | if (a != '0) 1697 | ... 1698 | else 1699 | ... 1700 | end 1701 | ``` 1702 | 1703 | 👎 1704 | ```systemverilog {.bad} 1705 | logic [3:0] a, b; 1706 | logic out; 1707 | 1708 | // Incorrect because it implicitly converts 4-bit signals to 1-bit before AND. 1709 | // Also, !b is different from ~b and can be hard to catch. 1710 | assign out = a && !b; 1711 | 1712 | // Incorrect use of a multi-bit signal in an if expression 1713 | always_comb begin 1714 | if (a) 1715 | ... 1716 | else 1717 | ... 1718 | end 1719 | ``` 1720 | 1721 | #### Bit Slicing 1722 | 1723 | Only use the bit slicing operator when the intent is to refer to a portion of a 1724 | bit vector. 1725 | 1726 | Examples: 1727 | 1728 | 👍 1729 | ```systemverilog {.good} 1730 | logic [7:0] a, b; 1731 | logic [6:0] c; 1732 | 1733 | assign a = 8'd7; // good 1734 | 1735 | assign a[7:1] = 7'd5; // good - it's partial assignment. 1736 | assign a = b; // good - the parser would warn on width mismatch. 1737 | ``` 1738 | 1739 | 👎 1740 | ```systemverilog {.bad} 1741 | logic [7:0] a, b; 1742 | 1743 | assign a[7:0] = 8'd7; // BAD - redundant and can mask linter warnings. 1744 | assign a = b[7:0]; // BAD - redundant and masks linter warnings. 1745 | ``` 1746 | 1747 | #### Handling Width Overflow 1748 | 1749 | Beware of shift operations, which can produce a result wider than the operand. 1750 | Bit-selection and concatenation may be clearer than shifting by a constant 1751 | amount. 1752 | 1753 | Addition and negation operations produce a result one bit wider than the 1754 | operands, due to carry. An allowable exception to the rule about matching widths 1755 | is to silently drop the carry on assignment. 1756 | 1757 | Example: 1758 | 1759 | ```systemverilog 1760 | logic [3:0] cnt_d, cnt_q; 1761 | assign cnt_d = cnt_q + 4'h1; 1762 | ``` 1763 | 1764 | Or you may explicitly express dropping the carry by using size casting. 1765 | 1766 | ```systemverilog 1767 | assign cnt_d = 4'(cnt_q + 4'h1); 1768 | ``` 1769 | 1770 | ### Blocking and Non-blocking Assignments 1771 | 1772 | ***Sequential logic must use non-blocking assignments. Combinational 1773 | blocks must use blocking assignments.*** 1774 | 1775 | Never mix assignment types within a block declaration. 1776 | 1777 | A sequential block (a block that latches state on a clock edge) must exclusively 1778 | use non-block assignments, as defined in the Sequential Logic section below. 1779 | 1780 | Purely combinational blocks must exclusively use blocking assignments. 1781 | 1782 | This is one of Cliff Cumming's [Golden Rules of 1783 | Verilog](http://www.ece.cmu.edu/~ece447/s13/lib/exe/fetch.php?media=synth-verilog-cummins.pdf). 1784 | 1785 | ### Delay Modeling 1786 | 1787 | ***Do not use `#delay` in synthesizable design modules.*** 1788 | 1789 | Synthesizable design modules must be designed around a zero-delay simulation 1790 | methodology. All forms of `#delay`, including `#0`, are not permitted. 1791 | 1792 | See Cliff Cumming's [Verilog Nonblocking Assignments With Delays, Myths & 1793 | Mysteries](http://www.sunburst-design.com/papers/CummingsSNUG2002Boston_NBAwithDelays.pdf) 1794 | for details. 1795 | 1796 | ### Sequential Logic (Latches) 1797 | 1798 | ***The use of latches is discouraged - use flip-flops when possible.*** 1799 | 1800 | Unless absolutely necessary, use flops/registers instead of latches. 1801 | 1802 | If you must use a latch, use `always_latch` over `always`, and use non-blocking 1803 | assignments (`<=`). Never use blocking assignments (`=`). 1804 | 1805 | ### Sequential Logic (Registers) 1806 | 1807 | ***Use the standard format for declaring sequential blocks.*** 1808 | 1809 | In a sequential always block, only use non-blocking assignments (`<=`). Never 1810 | use blocking assignments (`=`). 1811 | 1812 | Designs that mix blocking and non-blocking assignments for registers simulate 1813 | incorrectly because some simulators process some of the blocking assignments in 1814 | an always block as occurring in a separate simulation event as the non-blocking 1815 | assignment. This process makes some signals jump registers, potentially leading 1816 | to total protonic reversal. That's bad. 1817 | 1818 | Sequential statements for state assignments should only contain reset values and 1819 | a next-state to state assignment, use a separate combinational-only block to 1820 | generate that next-state value. 1821 | 1822 | A correctly implemented 8-bit register with an initial value of "0xAB" would be 1823 | implemented: 1824 | 1825 | 👍 1826 | ```systemverilog {.good} 1827 | logic foo_en; 1828 | logic [7:0] foo_q, foo_d; 1829 | 1830 | always_ff @(posedge clk or negedge rst_ni) begin 1831 | if (!rst_ni) begin 1832 | foo_q <= 8'hab; 1833 | end else if (foo_en) begin 1834 | foo_q <= foo_d; 1835 | end 1836 | end 1837 | ``` 1838 | 1839 | Do not allow multiple non-blocking assignments to the same bit. 1840 | 1841 | Example: 1842 | 1843 | 👎 1844 | ```systemverilog {.bad} 1845 | if (cond1) begin 1846 | abc <= 4'h1; 1847 | end 1848 | 1849 | if (cond2) begin 1850 | abc <= 4'h2; 1851 | end 1852 | ``` 1853 | 1854 | If both cond1 and cond2 are true, the Verilog standard says that the second 1855 | assignment will take effect, but this is a style violation. 1856 | 1857 | Even if `cond1` and `cond2` are mutually exclusive, make the second `if` into an 1858 | `else if`. 1859 | 1860 | Exception: It is fine to set default values first, then specific values. 1861 | However, it is preferred to do this work in a separate combinational block with 1862 | explicit blocking assignments. 1863 | 1864 | Example: 1865 | 1866 | ```systemverilog 1867 | always_ff @(posedge clk or negedge rst_ni) begin 1868 | if (!rst_ni) begin 1869 | state_q <= StIdle; 1870 | end else begin 1871 | state_q <= state_d; 1872 | end 1873 | end 1874 | 1875 | always_comb begin 1876 | state_d = state_q; // default assignment next state is present state 1877 | unique case (state_q) 1878 | StIdle: state_d = StInit; // Idle State move to Init 1879 | StInit: begin // Initialize calculation 1880 | if (conditional) begin 1881 | state_d = StIdle; 1882 | end else begin 1883 | state_d = StCalc; 1884 | end 1885 | end 1886 | StCalc: begin // Perform calculation 1887 | if (conditional) begin 1888 | state_d = StResult; 1889 | end 1890 | end 1891 | StResult: state_d = Idle; 1892 | default: ; 1893 | endcase 1894 | end 1895 | ``` 1896 | 1897 | Keep work in sequential blocks simple. If a sequential block becomes 1898 | sufficiently complicated, consider splitting the combinational logic into a 1899 | separate combinational (`always_comb`) block. Ideally, sequential blocks should 1900 | contain only a register instantiation, with perhaps a load enable or an 1901 | increment. 1902 | 1903 | ### Don't Cares (`X`'s) 1904 | 1905 | ***The use of `X` literals in RTL code is strongly discouraged. RTL must not 1906 | assert `X` to indicate "don't care" to synthesis in any case. In order to flag 1907 | and detect invalid conditions, rather than assign and propagate `X` values, 1908 | designs should fully define all signal values and make extensive use of SVAs to 1909 | indicate the invalid conditions.*** 1910 | 1911 | If not strictly controlled, the use of `X` assignments in RTL to flag invalid or 1912 | don't care conditions can lead to simulation/synthesis mismatches. 1913 | 1914 | Instead of assigning and propagating `X` in order to flag and detect invalid 1915 | conditions, it is encouraged to make **extensive use of SVAs**. The added 1916 | benefits of this design practice are that: 1917 | 1918 | - No special code style is required to properly propagate `X` conditions, 1919 | - The chance of accidentally introducing simulation/synthesis mismatches is 1920 | systematically reduced, 1921 | - Simulation fails quickly and less signal backtracking is needed to root-cause 1922 | bugs, 1923 | - In several cases, formal property verification (FPV) can be used to prove 1924 | whether these SVAs can always be fulfilled, 1925 | - In a security context, deterministic/defined behavior is desired, even for 1926 | illegal/invalid/unreachable input combinations (sometimes stated more tersely 1927 | as "for security-critical designs, there are no don't-cares"). 1928 | 1929 | The solution presented here has similarities with the approaches presented in 1930 | ["Being Assertive With Your X"](http://www.lcdm-eng.com/papers/snug04_assertiveX.pdf) 1931 | by Don Mills. 1932 | 1933 | Note that although don't cares can be used to indicate possible optimization 1934 | opportunities to the synthesis tool, it is debatable whether the gains in logic 1935 | reduction are significant enough to outweigh the possible simulation/synthesis 1936 | mismatch issues that the use of `X` literals may entail (especially with the 1937 | gate-counts available in today's technologies). 1938 | 1939 | 1940 | #### Catching errors where invalid values are consumed 1941 | 1942 | For an internally-generated signal that could be invalid (but not driven to `X`) 1943 | and is used to trigger some action (such as a register write-enable), it is 1944 | recommened to add an assert to check that when the enable is true, the signal is 1945 | valid. This triggers a simple to diagnose failure when an invalid value has been 1946 | accidentally used. 1947 | 1948 | ```systemverilog 1949 | 1950 | logic reg_addr; 1951 | logic reg_wr_en; 1952 | 1953 | // internal logic which generates reg_addr/reg_wr_en reg_en_addr will never 1954 | // be X but must be ignored if reg_wr_en == 0 1955 | assign reg_addr = ... 1956 | assign reg_wr_en = ... 1957 | 1958 | ... 1959 | 1960 | // trigger some specific action when a certain register is written 1961 | logic special_reg_en; 1962 | 1963 | assign special_reg_en = (reg_addr == SPECIAL_REG_ADDR) & reg_wr_en; 1964 | 1965 | // Aim to keep RHS of implication as broad as possible 1966 | `ASSERT(NoSpecialRegEnWithoutRegEn, special_reg_en |-> reg_wr_en); 1967 | ``` 1968 | 1969 | Where the value and its validity signal are generated by a DV environment which 1970 | will drive `X` on invalid signals an `` `ASSERT_KNOWN `` suffices. 1971 | 1972 | ```systemverilog 1973 | module mymod ( 1974 | input [7:0] external_addr_i, 1975 | input external_wr_en_i 1976 | ); 1977 | 1978 | logic special_action_en; 1979 | 1980 | assign special_action_en = 1981 | (external_addr_i == SPECIAL_ADDR) & external_wr_en_i; 1982 | 1983 | `ASSERT_KNOWN(special_action_en) 1984 | 1985 | endmodule 1986 | ``` 1987 | 1988 | #### Specific Guidance on Case Statements and Ternaries 1989 | 1990 | To comply with this style, RTL must place `` `ASSERT_KNOWN`` assertions on all 1991 | module outputs, with the exception of signals that may implicitly be `X` at the 1992 | beginning of the simulation, such as FIFO, SRAM or register file outputs. 1993 | 1994 | ```systemverilog 1995 | module mymod ( 1996 | input ina_i, 1997 | input inb_i, 1998 | output logic out_o 1999 | ); 2000 | assign out_o = ina_i ^ inb_i; 2001 | `ASSERT_KNOWN(OutKnown_A, out_o, clk_i, !rst_ni) 2002 | endmodule : mymod 2003 | ``` 2004 | 2005 | Further, it is encouraged to add assertions to the signals forming conditions of 2006 | case statements, ternaries or if/else statements. The assertion style is at the 2007 | designer's discretion, and can range from simple `` `ASSERT_KNOWN`` to fully 2008 | functional assertions, as shown in the following examples: 2009 | 2010 | ```systemverilog 2011 | typedef enum logic [1:0] {mode0, mode1, mode2} state_e; 2012 | state_e sel; 2013 | 2014 | // encouraged 2015 | `ASSERT_KNOWN(SelKnown_A, sel) 2016 | always_comb begin 2017 | out0 = '0; 2018 | out1 = '0; 2019 | unique case (sel) 2020 | mode1: out0 = foo; 2021 | mode2: out1 = bar; 2022 | default: ; 2023 | endcase 2024 | end 2025 | 2026 | // optional, but more explicit 2027 | // not always applicable 2028 | `ASSERT(MainFsmCase_A, sel inside {mode0, mode1, mode2}, clk_i, !rst_ni) 2029 | always_comb begin 2030 | out0 = '0; 2031 | out1 = '0; 2032 | unique case (sel) 2033 | mode1: out0 = foo; 2034 | mode2: out1 = bar; 2035 | default: ; 2036 | endcase 2037 | end 2038 | ``` 2039 | 2040 | In the context of ternary statements, the following are encouraged examples: 2041 | 2042 | ```systemverilog 2043 | // encouraged 2044 | `ASSERT_KNOWN(ModeKnown_A, mode_i, clk_i, !rst_ni) 2045 | `ASSERT_KNOWN(LenKnown_A, len_i, clk_i, !rst_ni) 2046 | // assign '0 for all other combinations 2047 | assign val = (mode_i == ENC) ? 8'h01 : 2048 | (mode_i == DEC && len_i == LEN128) ? 8'h36 : 2049 | (mode_i == DEC && len_i == LEN192) ? 8'h80 : 2050 | (mode_i == DEC && len_i == LEN256) ? 8'h40 : 8'h00; 2051 | 2052 | // optional, but more explicit 2053 | `ASSERT(ValSelValid_A, mode_i == ENC || mode_i == DEC && 2054 | len_i inside {LEN128, LEN192, LEN256}, clk_i, !rst_ni) 2055 | // using one of the valid outputs for other combinations (saves logic) 2056 | assign val = (mode_i == ENC) ? 8'h01 : 2057 | (mode_i == DEC && len_i == LEN128) ? 8'h36 : 2058 | (mode_i == DEC && len_i == LEN192) ? 8'h80 : 2059 | (mode_i == DEC && len_i == LEN256) ? 8'h40 : 8'h01; 2060 | ``` 2061 | 2062 | Note that there are cases where the input into a case or ternary could be `X` 2063 | but only under circumstances where it doesn't matter as the output will be 2064 | ignored as some valid signal that qualifies the input is not set. For example 2065 | the input may be fed directly from a memory or from a top-level input that a DV 2066 | environment drives to `X`. A plain `` `ASSERT_KNOWN `` will not work under these 2067 | circumstances and it is appropriate to use an assert with some qualifying valid 2068 | instead: 2069 | 2070 | ```systemverilog 2071 | `ASSERT(AddrKnownIfValid, addr_valid |-> !$isunknown(addr)) 2072 | always_comb begin 2073 | out = '0 2074 | unique case (addr[1:0]) 2075 | ConstAddr1: out = foo; 2076 | ConstAddr2: out = bar; 2077 | default: out = baz; 2078 | endcase 2079 | end 2080 | ``` 2081 | 2082 | The aim should be to make the qualifying valid signal as wide reaching as 2083 | possible rather than narrowing down the `X` check more than is required: 2084 | 2085 | 👎 2086 | ```systemverilog {.bad} 2087 | `ASSERT(AddrKnownIfValid, 2088 | addr_valid & internal_condition_1 & internal_condition_2 |-> 2089 | !$isunknown(addr)) 2090 | ``` 2091 | 2092 | #### Dynamic Array Indexing 2093 | 2094 | It should be noted that dynamic array indexing operations can implicitly lead to 2095 | `X`. This should be avoided if possible by either aligning indexed arrays to 2096 | powers of 2 or by adding guarding if statements around the indexing operation. 2097 | These solutions are illustrated in the following examples. 2098 | 2099 | 2100 | 👎 2101 | ```systemverilog {.bad} 2102 | logic selected; 2103 | logic [3:0] idx; 2104 | logic [11:0] foo; // problematic 2105 | 2106 | assign foo = {12'b1010_1111_0000}; 2107 | assign selected = foo[idx]; 2108 | ``` 2109 | 2110 | 👍 2111 | ```systemverilog {.good} 2112 | logic selected; 2113 | logic [3:0] idx; 2114 | logic [15:0] foo; // aligned to powers of two 2115 | 2116 | assign foo = {4'b0000, 12'b1010_1111_0000}; 2117 | assign selected = foo[idx]; 2118 | ``` 2119 | 2120 | 👍 2121 | ```systemverilog {.good} 2122 | logic selected; 2123 | logic [3:0] idx; 2124 | logic [11:0] foo; 2125 | 2126 | assign foo = {12'b1010_1111_0000}; 2127 | 2128 | // guarding if statement 2129 | assign selected = (idx < $bits(foo)) ? foo[idx] : 1'b0; 2130 | ``` 2131 | 2132 | ### Combinational Logic 2133 | 2134 | ***Avoid sensitivity lists, and use a consistent assignment type.*** 2135 | 2136 | Use `always_comb` for SystemVerilog combinational blocks. Use `always @*` if 2137 | only Verilog-2001 is supported. Never explicitly declare sensitivity lists for 2138 | combinational logic. 2139 | 2140 | Prefer assign statements wherever practical. 2141 | 2142 | Example: 2143 | 2144 | ```systemverilog 2145 | assign final_value = xyz ? value_a : value_b; 2146 | ``` 2147 | 2148 | Where a case statement is needed, enclose it in its own `always_comb` block. 2149 | 2150 | Synthesizable combinational logic blocks should only use blocking assignments. 2151 | 2152 | Do not use three-state logic (`Z` state) to accomplish on-chip logic such as 2153 | muxing. 2154 | 2155 | Do not infer a latch inside a function, as this may cause a 2156 | simulation/synthesis mismatch. 2157 | 2158 | ### Case Statements 2159 | 2160 | ***Avoid case-modifying pragmas. `unique case` is the best 2161 | practice. Always define a default case.*** 2162 | 2163 | Never use either the `full_case` or `parallel_case` pragmas. These pragmas can 2164 | easily cause simulation/synthesis mismatches. 2165 | 2166 | Here is an example of a style-compliant full case statement: 2167 | 2168 | ```systemverilog 2169 | always_comb begin 2170 | unique casez (select) 2171 | 3'b000: operand = accum0 >> 0; 2172 | 3'b001: operand = accum0 >> 1; 2173 | 3'b010: operand = accum1 >> 0; 2174 | 3'b011: operand = accum1 >> 1; 2175 | 3'b1??: operand = regfile[select[1:0]]; 2176 | default: operand = '0; // assign a default 2177 | endcase 2178 | end 2179 | ``` 2180 | 2181 | The `unique` prefix is recommended before all case statements, as it creates 2182 | simulation assertions that can catch certain mistakes. In some cases, `priority` 2183 | may be used instead of `unique`, though in such cases, cascaded ternary 2184 | structures should be the preferred way of representing priority encoders as 2185 | they are a more readable representation for priority encoders. 2186 | 2187 | Be sure to use `unique case` correctly. In particular, make sure that: 2188 | 2189 | - a `default:` statement is **always** included in order to avoid accidental 2190 | inference of latches, even if all cases are covered. In simulation, a case 2191 | expression that evaluates to `X` will not match any case and will behave as a 2192 | latch, leading to different behavior than synthesis if no default is specified. 2193 | 2194 | - if no default assignments are given before the case statement as shown in 2195 | the example above, any variables assigned in one case item must be assigned in 2196 | all case items, including the `default:`. Failing to do this can lead to a 2197 | simulation/synthesis mismatch as described in [Don Mills' paper][yalagp]. 2198 | 2199 | The following is a different example showing a style-compliant case statement 2200 | variant that is frequently used for describing the next-state logic of a finite 2201 | state machine. What is different from the previous example is that the default 2202 | assignments are put before the `unique case` block, thus making it possible to 2203 | omit common assignments in the individual cases further below. If it weren't for 2204 | the common default assignments before the case statement, all variables would 2205 | have to be assigned a value in all cases and in the `default:` in order to 2206 | prevent simulation/synthesis mismatches. 2207 | 2208 | ```systemverilog 2209 | always_comb begin 2210 | // common default assignments 2211 | state_d = state_q; 2212 | outa = 1'b0; 2213 | outb = 1'b0; 2214 | outc = 1'b0; 2215 | 2216 | unique case (state_q) 2217 | Idle: begin 2218 | state_d = Work; 2219 | outa = in0; 2220 | end 2221 | Work: begin 2222 | state_d = Wait; 2223 | outb = in1; 2224 | end 2225 | Wait: begin 2226 | state_d = Idle; 2227 | outc = in2; 2228 | end 2229 | // always include a default case 2230 | // empty default permissible due to defaults before case block 2231 | default: ; 2232 | endcase 2233 | end 2234 | ``` 2235 | 2236 | #### Wildcards in case items 2237 | 2238 | Use `case` if wildcard operator behavior is not needed. 2239 | Use `case inside` if wildcard operator behavior is needed. 2240 | Use `casez` if wildcard operator behavior is needed and Verilog-2001 compatibility is required. 2241 | 2242 | When expressing a wildcard in a case item, use the '?' character since it more 2243 | clearly expresses the intent. 2244 | 2245 | `casex` should not be used. `casex` implements a symmetric wildcard operator 2246 | such that an `X` in the case expression may match one or more case items. 2247 | `casez` only treats high-impedance states (`Z` or `?`) as a wildcard, and 2248 | performs exact matches for undriven `X` inputs. While this does not completely 2249 | fix the problems with symmetric wildcard matching, it is harder to accidentally 2250 | produce a `Z` input than an `X` input, so this form is preferred. 2251 | `case inside` does not treat either `X` or `Z` in the case expression as a 2252 | wildcard, so this form is preferred over `casez`. 2253 | 2254 | References: 2255 | 2256 | * Don Mills, [Yet Another Latch and Gotchas Paper][yalagp] 2257 | * Clifford Cummings, [full\_case parallel\_case, the Evil Twins of Verilog Synthesis][twinevils] 2258 | * Clifford Cummings, [SystemVerilog's priority & unique][priuniq] 2259 | * Sutherland, Mills, and Spear, [Gotcha Again: More Subtleties in the Verilog and SystemVerilog Standards That Every Engineer Should Know][gotagain] 2260 | 2261 | [yalagp]: http://www.lcdm-eng.com/papers/snug12_Paper_final.pdf 2262 | [twinevils]: http://www.sunburst-design.com/papers/CummingsSNUG1999Boston_FullParallelCase_rev1_1.pdf 2263 | [priuniq]: http://www.sunburst-design.com/papers/CummingsSNUG2005Israel_SystemVerilog_UniquePriority.pdf 2264 | [gotagain]: http://www.lcdm-eng.com/papers/snug07_Verilog%20Gotchas%20Part2.pdf 2265 | 2266 | ### Generate Constructs 2267 | 2268 | ***Always name your generated blocks.*** 2269 | 2270 | When using a generate construct, always explicitly name each block of generated 2271 | code. Name each possible outcome of the generating if statement, and name the 2272 | iterated block of a generating for statement. 2273 | 2274 | This ensures that generated hierarchical signal names are consistent across 2275 | different tools. 2276 | 2277 | Generate and all named code blocks should use `lower_snake_case`. A space should 2278 | be placed between `begin` and the code block name. 2279 | 2280 | Example of a conditional generate construct: 2281 | 2282 | 👍 2283 | ```systemverilog {.good} 2284 | if (TypeIsPosedge) begin : posedge_type 2285 | always_ff @(posedge clk) foo <= bar; 2286 | end else begin : negedge_type 2287 | always_ff @(negedge clk) foo <= bar; 2288 | end 2289 | ``` 2290 | 2291 | Example of a loop generate construct: 2292 | 2293 | 👍 2294 | ```systemverilog {.good} 2295 | for (genvar ii = 0; ii < NumberOfBuses; ii++) begin : my_buses 2296 | my_bus #(.index(ii)) i_my_bus (.foo(foo), .bar(bar[ii])); 2297 | end 2298 | ``` 2299 | 2300 | Do not wrap a generate construct with an additional `begin` block. 2301 | 2302 | Do not use generate regions {`generate`, `endgenerate`}. 2303 | 2304 | ### Signed Arithmetic 2305 | 2306 | ***Use the available signed arithmetic constructs wherever signed 2307 | arithmetic is used.*** 2308 | 2309 | When it's necessary to convert from unsigned to signed, use the `signed'` cast 2310 | operator (`$signed` in Verilog-2001). 2311 | 2312 | If any operand in a calculation is unsigned, Verilog implicitly casts all 2313 | operands to unsigned and generates a warning. There should not be any 2314 | signed-to-unsigned warnings from either the simulation or synthesis tools if all 2315 | unsigned variables are properly casted. 2316 | 2317 | Example of implicit signed-to-unsigned casting: 2318 | 2319 | ```systemverilog 2320 | logic signed [7:0] a; 2321 | logic incr; 2322 | logic signed [15:0] sum1, sum2, sum3; 2323 | initial begin 2324 | a = 8'sh80; // a = -128 2325 | incr = 1'b1; 2326 | sum1 = a + incr; // bad: sum1 = 16'h0081 ( 129) 2327 | sum2 = a + signed'({1'b0, incr}); // good: sum2 = 16'hFF81 (-127) 2328 | sum3 = a + 8'sh01; // good: sum3 = sum2 (more straightforward) 2329 | end 2330 | ``` 2331 | 2332 | In the above example, the fact that `incr` is unsigned causes `a` to be 2333 | evaluated as unsigned as well. The `sum1` evaluation is surprising and is 2334 | flagged by a warning that should not be ignored. 2335 | 2336 | ### Number Formatting 2337 | 2338 | ***Prefix printed binary numbers with `0b`. Prefix printed hexadecimal 2339 | numbers with `0x`. Do not use prefixes for decimal numbers.*** 2340 | 2341 | When formatting text representations of numbers for log files, make it clear 2342 | what data you are including. 2343 | 2344 | Make the base of a printed number clear. Only print decimal numbers without 2345 | modifiers. Use a `0x` prefix for hexadecimal and `0b` prefix for binary. 2346 | 2347 | Decode individual fields of large structures individually, instead of expecting 2348 | the user to manually decode raw values. 2349 | 2350 | 👍 2351 | ```systemverilog {.good} 2352 | $display("0x%0x", some_hex_value); 2353 | $display("0b%0b", some_binary_value); 2354 | $display("%0d", some_decimal_value); 2355 | ``` 2356 | 2357 | 👎 2358 | ```systemverilog {.bad} 2359 | $display("%0x", some_hex_value); 2360 | $display("%0b", some_binary_value); 2361 | $display("0d%0d", some_decimal_value); 2362 | ``` 2363 | 2364 | When assigning constant values, it is preferred to use underscore notation for 2365 | hex or binary bit strengths of length beyond 8 for better readability. Zero 2366 | prepending is not required unless it improves readability. Declare constants in 2367 | the format (binary, hex, decimal) they are typically displayed in. 2368 | 2369 | 2370 | 👍 2371 | ```systemverilog {.good} 2372 | logic [15:0] val0, val1, val2; 2373 | logic [39:0] addr0, addr1; 2374 | 2375 | always_comb begin 2376 | val0 = 16'h0; 2377 | if (condition1) begin 2378 | val1 = 16'b0010_0011_0000_1101; 2379 | val2 = 16'b0010_1100_0000_0000; 2380 | addr1 = 40'h00_1fc0_0000; 2381 | addr2 = 40'h00_efc0_0000; 2382 | end else begin 2383 | val0 = 16'hffff; 2384 | val1 = 16'b1010_0011_0110_1001; 2385 | val2 = 16'b1110_1100_1111_0110; 2386 | addr1 = 40'h40_8000_0000; 2387 | addr2 = 40'h41_c000_0000; 2388 | end 2389 | end 2390 | ``` 2391 | 2392 | ### Functions and Tasks 2393 | 2394 | The following section applies to synthesizable RTL only. See the [Coding Style 2395 | Guide for Design Verification](DVCodingStyle.md) for DV usage. 2396 | 2397 | ***In synthesizable RTL the use of functions is allowed, provided they are declared 2398 | `automatic`. Tasks should not be used.*** 2399 | 2400 | Functions must be declared in either a package or inside a module. A package is 2401 | appropriate where the function relates to other definitions in the package and 2402 | could be useful to multiple modules (even if it's currently only used by one). A 2403 | module is appropriate where the function specifically relates to the internals 2404 | of that module. 2405 | 2406 | Functions should aim to conceptually represent a reusable block of combinational 2407 | logic. 2408 | 2409 | Storage types must be explicitly declared for all arguments and the function 2410 | return value. All types must be 4-state data types, either `logic` or types 2411 | derived from `logic` (such as appropriate `struct`, `enum` or `typedef` types). 2412 | 2413 | Do not use `output`, `inout`, or `ref` on function arguments. All functions 2414 | should only consume inputs and produce one output. `input` is the default and is 2415 | not required on the function arguments. 2416 | 2417 | 2418 | 👎 2419 | ```systemverilog {.bad} 2420 | // - Doesn't have explicit storage type on `a` or `b` or return type 2421 | // - `b` being used as `output` argument 2422 | // - `input` not required on `a` 2423 | function automatic [2:0] foo(input [2:0] a, [2:0] b); 2424 | b = b + 1; 2425 | return a + b; 2426 | endfunction 2427 | ``` 2428 | 2429 | 👎 2430 | ```systemverilog {.bad} 2431 | // - Doesn't have explicit storage type on `a`, `b` or `c` 2432 | // - Uses `output` on `c` 2433 | // - `input` not required on `a` and `b` 2434 | function automatic logic [2:0] foo(input [2:0] a, input [2:0] b, output [2:0] c); 2435 | c = a - b; 2436 | return a + b; 2437 | endfunction 2438 | ``` 2439 | 2440 | 👎 2441 | ```systemverilog {.bad} 2442 | // - Uses 2-state data type `int` for `a` 2443 | function automatic logic [2:0] foo(int a, logic [2:0] b); 2444 | return a + b; 2445 | endfunction 2446 | ``` 2447 | 2448 | 👍 2449 | ```systemverilog {.good} 2450 | function automatic logic [2:0] foo(logic [2:0] a, logic [2:0] b); 2451 | return a ^ b; 2452 | endfunction 2453 | ``` 2454 | 2455 | 👍 2456 | ```systemverilog {.good} 2457 | typedef logic [2:0] bar_t; 2458 | 2459 | typedef struct packed { 2460 | logic [2:0] field; 2461 | } baz_t; 2462 | 2463 | function automatic logic [2:0] foo(bar_t a, baz_t b); 2464 | return a + b.field; 2465 | endfunction 2466 | ``` 2467 | 2468 | Data should be returned from a function using an explicit `return result` style. 2469 | Do not use a `function_name = result` style. 2470 | 2471 | 👎 2472 | ```systemverilog {.bad} 2473 | function automatic logic [2:0] foo(logic [2:0] a, logic [2:0] b); 2474 | if (a == 3'd2) begin 2475 | foo = b; 2476 | end else begin 2477 | foo = a ^ b; 2478 | end 2479 | endfunction 2480 | ``` 2481 | 2482 | 👍 2483 | ```systemverilog {.good} 2484 | function automatic logic [2:0] foo(logic [2:0] a, logic [2:0] b); 2485 | logic [2:0] result; 2486 | 2487 | if (a == 3'd2) begin 2488 | result = b; 2489 | end else begin 2490 | result = a ^ b; 2491 | end 2492 | 2493 | return result; 2494 | endfunction 2495 | ``` 2496 | 2497 | All local variables must be assigned in all code paths, either through an 2498 | initial assignment or through the use of `else` and `default:` for `if` and 2499 | `case` statements. 2500 | 2501 | 👍 2502 | ```systemverilog {.good} 2503 | function automatic logic [2:0] foo(logic [2:0] a, logic [2:0] b); 2504 | logic [2:0] local_var_1; 2505 | logic [2:0] local_var_2; 2506 | 2507 | local_var_1 = 3'd0; 2508 | 2509 | if (a == 0) begin 2510 | local_var_1 = 3'd2; 2511 | end 2512 | 2513 | unique case(b) 2514 | 3'd0: local_var_2 = 3'd1; 2515 | 3'd1: local_var_2 = 3'd3; 2516 | default: local_var_2 = 3'd0; 2517 | endcase 2518 | 2519 | return local_var_1 + local_var_2; 2520 | endfunction 2521 | ``` 2522 | 2523 | 👎 2524 | ```systemverilog {.bad} 2525 | function automatic logic [2:0] foo(logic [2:0] a, logic [2:0] b); 2526 | logic [2:0] local_var_1; 2527 | logic [2:0] local_var_2; 2528 | 2529 | if (a == 0) begin 2530 | local_var_1 = 3'd2; 2531 | end 2532 | 2533 | unique case(b) 2534 | 3'd0: local_var_2 = 3'd1; 2535 | 3'd1: local_var_2 = 3'd3; 2536 | endcase 2537 | 2538 | return local_var_1 + local_var_2; 2539 | endfunction 2540 | ``` 2541 | 2542 | Functions should not reference any non-local signals or variables outside their 2543 | scope. Avoiding non-local references improves readability and helps reduce 2544 | simulation/synthesis mismatches. Accessing non-local parameters and constants 2545 | is allowed. 2546 | 2547 | 👎 2548 | ```systemverilog {.bad} 2549 | // - Incorrect because `mem` is not local to get_mem() 2550 | // - Incorrect because `in_i` is not local to get_mem() 2551 | module mymod ( 2552 | input logic [7:0] in_i, 2553 | output logic [7:0] out_o 2554 | ); 2555 | 2556 | logic [7:0] mem[256]; 2557 | 2558 | function automatic logic [7:0] get_mem(); 2559 | return mem[in_i]; 2560 | endfunction 2561 | 2562 | assign out_o = get_mem(); 2563 | 2564 | endmodule 2565 | ``` 2566 | 2567 | 👍 2568 | ```systemverilog {.good} 2569 | // - Correct because `MagicValue` is a parameter 2570 | // - Correct because `my_pkg::OtherMagicValue` is a parameter 2571 | // - Correct because `in_i` passed as an argument 2572 | module mymod ( 2573 | input logic [7:0] in_i, 2574 | output logic [7:0] out_o 2575 | ); 2576 | 2577 | localparam [7:0] MagicValue = 1; 2578 | 2579 | function automatic logic is_magic(logic [7:0] v); 2580 | return (v == MagicValue) || (v == my_pkg::OtherMagicValue); 2581 | endfunction 2582 | 2583 | assign out_o = is_magic(in_i); 2584 | 2585 | endmodule 2586 | ``` 2587 | 2588 | ### Problematic Language Features and Constructs 2589 | 2590 | These language features are considered problematic and their use is discouraged 2591 | unless otherwise noted: 2592 | 2593 | - Interfaces. 2594 | - The `alias` statement. 2595 | 2596 | #### Floating begin-end blocks 2597 | 2598 | The use of generate blocks other than `for` loop, `if`, or `case` generate 2599 | constructs is not LRM compliant. While such usage might be accepted by some 2600 | tools, this guide prohibits such "bare" generate blocks. Note that the similar 2601 | "sequential block" construct is LRM compliant and allowed. 2602 | 2603 | 👎 2604 | ```systemverilog {.bad} 2605 | module foo ( 2606 | input bar, 2607 | output foo 2608 | ); 2609 | begin // illegal generate block 2610 | assign foo = bar; 2611 | end 2612 | endmodule 2613 | ``` 2614 | 2615 | #### Hierarchical references 2616 | 2617 | The use of hierarchical references in synthesizable RTL code is prohibited. 2618 | Certain synthesis tools indeed support hierarchical references, while some 2619 | tools error out and others may silently ignore them potentially leading to 2620 | simulation/synthesis mismatches. 2621 | 2622 | An exemption to this is the case where the hierarchical references are guarded 2623 | by macros to remove them for synthesis, e.g., as part of SystemVerilog 2624 | assertions (SVAs). 2625 | 2626 | 👎 2627 | ```systemverilog {.bad} 2628 | 2629 | module mymod_int ( 2630 | input in0_i, 2631 | input in1_i, 2632 | input in2_i, 2633 | output logic out_o 2634 | ); 2635 | 2636 | logic int; 2637 | assign int = in0_i & in1_i; 2638 | assign out_o = in2_i | int; 2639 | 2640 | endmodule 2641 | 2642 | module mymod ( 2643 | ... 2644 | ); 2645 | 2646 | mymod_int u_mymod_int ( 2647 | .in0_i, 2648 | .in1_i, 2649 | .in2_i, 2650 | .out_o 2651 | ); 2652 | 2653 | // Hierarchical references are prohibited in synthesizable RTL code. 2654 | assign int_o = u_mymod_int.int; 2655 | 2656 | endmodule 2657 | ``` 2658 | 2659 | ## Design Conventions 2660 | 2661 | ### Summary 2662 | 2663 | The key ideas in this section include: 2664 | 2665 | * Declare all signals and use `logic`: `logic foo;` 2666 | * Packed arrays are little-endian: `logic [7:0] byte;` 2667 | * Unpacked arrays are big-endian: `byte_t arr[0:N-1];` 2668 | * Prefer to register module outputs. 2669 | * Declare FSMs consistently. 2670 | 2671 | ### Declare all signals 2672 | 2673 | ***Do not rely on inferred nets.*** 2674 | 2675 | All signals **must** be explicitly declared before use. All declared signals 2676 | must specify a data type. A correct design contains no inferred nets. 2677 | 2678 | ### Use `logic` for synthesis 2679 | 2680 | ***Use `logic` for synthesis. `wire` is allowed when necessary.*** 2681 | 2682 | All signals in synthesizable RTL must be implemented in terms of 4-state data 2683 | types. This means that all signals must ultimately be constructed of nets with 2684 | the storage type of `logic`. While SystemVerilog does provide other data 2685 | primitives with 4-state storage (ie. `integer`), those primitives are prone to 2686 | misunderstandings and misuse. 2687 | 2688 | For example: 2689 | 2690 | 👍 2691 | ```systemverilog {.good} 2692 | logic signed [31:0] x_velocity; // say what you mean: a signed 32-bit integer. 2693 | typedef logic [7:0] byte_t; 2694 | ``` 2695 | 2696 | 👎 2697 | ```systemverilog {.bad} 2698 | bit signed [63:0] stars_in_the_sky; // 2-state logic doesn't belong in RTL 2699 | int grains_of_sand; // Or wait, did I mean integer? Easy to confuse! 2700 | ``` 2701 | 2702 | It is permissible to use wire as a short-hand to both declare a net and perform 2703 | continuous assignment. Take care not to confuse continuous assignment with 2704 | initialization. For example: 2705 | 2706 | 👍 2707 | ```systemverilog {.good} 2708 | wire [7:0] sum = a + b; // Continuous assignment 2709 | ``` 2710 | 2711 | 👎 2712 | ```systemverilog {.bad} 2713 | logic [7:0] sum = a + b; // Initialization (not synthesizable) 2714 | ``` 2715 | 2716 | `sum` is initialized to sum of initial values of a and b. 2717 | 2718 | 👍 2719 | ```systemverilog {.good} 2720 | logic [7:0] acc = '0; // Initialization (synthesizable on some FPGA tools) 2721 | ``` 2722 | 2723 | There are exceptions for places where `logic` is inappropriate. For example, 2724 | nets that connect to bidirectional (`inout`) ports must be declared with `wire`. 2725 | These exceptions should be justified with a short comment. 2726 | 2727 | It is permissible for DV (Design Verification) to make use of 2-state 2728 | logic, but all interfaces between 4-state and 2-state signals must assert 2729 | a check for `X` on the 4-state net before resolving to a 2-state variable. 2730 | 2731 | ### Logical vs. Bitwise 2732 | 2733 | ***Prefer logical constructs for logical comparisons, bit-wise for data.*** 2734 | 2735 | Logical operators (`!`, `||`, `&&`, `==`, `!=`) should be used for all 2736 | constructs that are evaluating logic (true or false) values, such as 2737 | if clauses and ternary assignments. Prefer bit-wise operators (`~`, `|`, 2738 | `&`, `^`) for all data constructs, even if scalar. Exceptions can be made 2739 | where it is clear that the evaluated expression is to be used in a logical 2740 | context. 2741 | 2742 | :+1: 2743 | ```systemverilog {.good} 2744 | always_ff @(posedge clk_i or negedge rst_ni) begin 2745 | if (!rst_ni) begin 2746 | reg_q <= '0; 2747 | end else begin 2748 | reg_q <= reg_d; 2749 | end 2750 | end 2751 | 2752 | always_comb begin 2753 | if (bool_a || (bool_b && !bool_c) begin 2754 | x = 1'b1; 2755 | end else begin 2756 | x = 1'b0; 2757 | end 2758 | 2759 | assign z = ((bool_a != bool_b) || bool_c) ? a : b; 2760 | assign y = (a & ~b) | c; 2761 | ``` 2762 | 2763 | :-1: 2764 | ```systemverilog {.bad} 2765 | always_ff @(posedge clk_i or negedge rst_ni) begin 2766 | if (~rst_ni) begin 2767 | reg_q <= '0; 2768 | end else begin 2769 | reg_q <= reg_d; 2770 | end 2771 | end 2772 | 2773 | always_comb begin 2774 | if (bool_a | (bool_b & ~bool_c) begin 2775 | x = 1'b1; 2776 | end else begin 2777 | x = 1'b0; 2778 | end 2779 | 2780 | assign z = ((bool_a ^ bool_b) | bool_c) ? a : b; 2781 | assign y = (a && !b) || c; 2782 | ``` 2783 | 2784 | :+1: 2785 | ```systemverilog 2786 | // allowed logical assignment for boolean test 2787 | assign request_valid = !fifo_empty && data_available; 2788 | 2789 | always_comb begin 2790 | if (request_valid) begin 2791 | output_valid = 1'b1; 2792 | end else begin 2793 | output_valid = 1'b0; 2794 | end 2795 | end 2796 | ``` 2797 | 2798 | 2799 | ### Packed Ordering 2800 | 2801 | ***Bit vectors and packed arrays must be little-endian.*** 2802 | 2803 | When declaring bit vectors and packed arrays, the index of the most-significant 2804 | bound (left of the colon) must be greater than or equal to the least-significant 2805 | bound (right of the colon). 2806 | 2807 | This style of bit vector declaration keeps packed variables little-endian. 2808 | 2809 | For example: 2810 | 2811 | ```systemverilog 2812 | typedef logic [7:0] u8_t; 2813 | logic [31:0] u32_word; 2814 | u8_t [1:0] u16_word; 2815 | u8_t byte3, byte2, byte1, byte0; 2816 | assign u16_word = {byte1, byte0}; 2817 | assign u32_word = {byte3, byte2, u16_word}; 2818 | ``` 2819 | 2820 | ### Unpacked Ordering 2821 | 2822 | ***Unpacked arrays must be big-endian.*** 2823 | 2824 | Declare unpacked arrays in big-endian fashion (for instance, `[n:m]` where `n <= 2825 | m`). Never declare an unpacked array in little-endian order, such as 2826 | `[size-1:0]`. 2827 | 2828 | Declare zero-based unpacked arrays using the shorter notation `[size]`. It is 2829 | understood that `[size]` is equivalent to the big-endian declaration 2830 | `[0:size-1]`. 2831 | 2832 | ```systemverilog 2833 | logic [15:0] word_array[3] = '{word0, word1, word2}; 2834 | ``` 2835 | 2836 | ### Finite State Machines 2837 | 2838 | ***State machines use an enum to define states, and be implemented with 2839 | two process blocks: a combinational block and a clocked block.*** 2840 | 2841 | Every state machine description has three parts: 2842 | 2843 | 1. An enum that declares and describes the states. 2844 | 1. A combinational process block that decodes state to produce next state and 2845 | other combinational outputs. 2846 | 1. A clocked process block that updates state from next state. 2847 | 2848 | *Enumerating States* 2849 | 2850 | The enum statement for the state machine should list each state in the state 2851 | machine. Comments describing the states should be deferred to case statement in 2852 | the combinational process block, below. 2853 | 2854 | States should be named in `UpperCamelCase`, like other 2855 | [enumeration constants](#enumerations). 2856 | 2857 | Barring special circumstances, the initial idle state of the state 2858 | machines will be named `Idle` or `StIdle`. (Alternate names are acceptable 2859 | if they improve clarity.) 2860 | 2861 | Ideally, each module should only contain one state machine. If your module needs 2862 | more than one state machine, you will need to add a unique prefix (or suffix) to 2863 | the states of each state machine, to distinguish which state is associated with 2864 | which state machine. For example, a module with a "reader" machine and a 2865 | "writer" machine might have a `StRdIdle` state and a `StWrIdle` state. 2866 | 2867 | *Combinational Decode of State* 2868 | 2869 | The combinational process block should contain: 2870 | 2871 | - A case statement that decodes state to produce next state and combinational 2872 | outputs. For clarity, only cases where the output value deviates from the 2873 | default should be coded. 2874 | - Before the case statement should be a block of code that defines default 2875 | values for every combinational output, including "next state." 2876 | - The default value for the "next state" variable should be the current state. 2877 | The case statement that decodes state will then only assign to "next state" 2878 | when transitioning between states. 2879 | - Within the case statement, each state alternative should be preceded with a 2880 | comment that describes the function of that state within the state machine. 2881 | 2882 | *The State Register* 2883 | 2884 | No logic except for reset should be performed in this process. The state 2885 | variable should latch the value of the "next state" variable. 2886 | 2887 | *Other Guidelines* 2888 | 2889 | When possible, try to choose state names that differ near the beginning of their 2890 | name, to make them more readable when viewing waveform traces. 2891 | 2892 | *Example* 2893 | 2894 | 👍 2895 | ```systemverilog {.good} 2896 | // Define the states 2897 | typedef enum { 2898 | StIdle, StFrameStart, StDynInstrRead, StBandCorr, StAccStoreWrite, StBandEnd 2899 | } alcor_state_e; 2900 | 2901 | alcor_state_e alcor_state_d, alcor_state_q; 2902 | 2903 | // Combinational decode of the state 2904 | always_comb begin 2905 | alcor_state_d = alcor_state_q; 2906 | foo = 1'b0; 2907 | bar = 1'b0; 2908 | bum = 1'b0; 2909 | unique case (alcor_state_q) 2910 | // StIdle: waiting for frame_start 2911 | StIdle: 2912 | if (frame_start) begin 2913 | foo = 1'b1; 2914 | alcor_state_d = StFrameStart; 2915 | end 2916 | // StFrameStart: Reset accumulators 2917 | StFrameStart: begin 2918 | // ... etc ... 2919 | end 2920 | // may be empty or used to catch parasitic states 2921 | default: alcor_state_d = StIdle; 2922 | endcase 2923 | end 2924 | 2925 | // Register the state 2926 | always_ff @(posedge clk or negedge rst_n) begin 2927 | if (!rst_n) begin 2928 | alcor_state_q <= StIdle; 2929 | end else begin 2930 | alcor_state_q <= alcor_state_d; 2931 | end 2932 | end 2933 | ``` 2934 | 2935 | ### Active-Low Signals 2936 | 2937 | ***The `_n` suffix indicates an active-low signal.*** 2938 | 2939 | If active-low signals are used, they must have the `_n` suffix in their 2940 | name. Otherwise, all signals are assumed to be active-high. 2941 | 2942 | ### Differential Pairs 2943 | 2944 | ***Use the `_p` and `_n` suffixes to indicate a differential pair.*** 2945 | 2946 | For example, `in_p` and `in_n` comprise a differential pair set. 2947 | 2948 | ### Delays 2949 | 2950 | ***Signals delayed by a single clock cycle should end in a `_q` suffix.*** 2951 | 2952 | If one signal is only a delayed version of another signal, the `_q` suffix 2953 | should be used to indicate this relationship. 2954 | 2955 | If another signal is then delayed by another clock cycle, the next signal should 2956 | be identifed with the `_q2` suffix, and then `_q3` and so on. 2957 | 2958 | Example: 2959 | 2960 | ```systemverilog 2961 | always_ff @(posedge clk) begin 2962 | data_valid_q <= data_valid_d; 2963 | data_valid_q2 <= data_valid_q; 2964 | data_valid_q3 <= data_valid_q2; 2965 | end 2966 | ``` 2967 | 2968 | ### Wildcard import of packages 2969 | 2970 | The wildcard import syntax, e.g. `import ip_pkg::*;` is only allowed where the 2971 | package is part of the same IP as the module that uses that package. Wildcard 2972 | import statement must be placed in the module header or in the module body. 2973 | 2974 | 👍 2975 | ```systemverilog {.good} 2976 | // mod_a_pkg.sv and mod_a.sv are in the same IP. 2977 | // Packages can be imported in the module declaration if access to 2978 | // unqualified types is needed in the port list. 2979 | 2980 | // mod_a_pkg.sv 2981 | package mod_a_pkg; 2982 | 2983 | typedef struct packed { 2984 | ... 2985 | } a_req_t; 2986 | endpackage 2987 | 2988 | // mod_a.sv 2989 | module mod_a 2990 | import mod_a_pkg::*; 2991 | ( 2992 | ... 2993 | a_req_t a_req, 2994 | ... 2995 | ); 2996 | 2997 | endmodule 2998 | ``` 2999 | 3000 | 👍 3001 | ```systemverilog {.good} 3002 | // mod_a 3003 | module mod_a (); 3004 | 3005 | // mod_a_pkg.sv and mod_a.sv are in the same IP. 3006 | import mod_a_pkg::*; 3007 | 3008 | ... 3009 | 3010 | a_req_t a_req; 3011 | 3012 | endmodule 3013 | ``` 3014 | 3015 | Other than the cases above, wildcard imports are not allowed. For instance, 3016 | the example below may create a name collision in the module following `mod_a` 3017 | in the source list. 3018 | 3019 | 👎 3020 | ```systemverilog {.bad} 3021 | // mod_a.sv 3022 | import mod_a_pkg::*; // not allowed: imported to $root scope. 3023 | 3024 | module mod_a (); 3025 | 3026 | endmodule 3027 | ``` 3028 | 3029 | Other bad examples: 3030 | 3031 | 👎 3032 | ```systemverilog {.bad} 3033 | // wildcard import for other packages outside of the IP 3034 | module mod_a import mod_b_pkg::*; (); 3035 | ``` 3036 | 3037 | 👎 3038 | ```systemverilog {.bad} 3039 | module mod_a (); 3040 | 3041 | // not allowed: wildcard import of a package from a different IP 3042 | import mod_b_pkg::*; 3043 | 3044 | endmodule 3045 | ``` 3046 | 3047 | ### Assertion Macros 3048 | 3049 | It is encouraged to use SystemVerilog assertions (SVAs) throughout the design to 3050 | check functional correctness and flag invalid conditions. In order to increase 3051 | productivity and keep the assertions short and concise, the following assertion 3052 | macros can be used: 3053 | 3054 | ```systemverilog 3055 | // immediate assertion, to be placed within a process. 3056 | `ASSERT_I(, ) 3057 | // immediate assertion wrapped within an initial block. can be used for things 3058 | // like parameter checking. 3059 | `ASSERT_INIT(, ) 3060 | // concurrent assertion to be used for functional assertions. 3061 | `ASSERT(, , , ) 3062 | // concurrent assertion that checks that a signal has a known value after reset 3063 | // (i.e. that the signal is not `X`). 3064 | `ASSERT_KNOWN(, , , ) 3065 | ``` 3066 | 3067 | An implementation of these macros (including other useful variations thereof) 3068 | can be found here: 3069 | https://github.com/lowRISC/opentitan/blob/master/hw/ip/prim/rtl/prim_assert.sv 3070 | 3071 | 3072 | #### A Note on Security Critical Applications 3073 | 3074 | For security critical applications, the names of the assertion macros involved 3075 | in guarding case statements and ternaries shall be postfixed with `_SEC`. This 3076 | enables security-specific post-processing of these statements at a later stage 3077 | in the design process. In terms of functionality these macros should be 3078 | identical to the original assertions, i.e., 3079 | 3080 | ```systemverilog 3081 | `define ASSERT_SEC `ASSERT 3082 | `define ASSERT_I_SEC `ASSERT_I 3083 | `define ASSERT_KNOWN_SEC `ASSERT_KNOWN 3084 | ``` 3085 | 3086 | More security assertion and coding style guidance will be given in a separate 3087 | document, soon. 3088 | 3089 | ## Appendix - Condensed Style Guide 3090 | 3091 | This is a short summary of the Comportable style guide. Refer to the main text 3092 | body for explanations examples, and exceptions. 3093 | 3094 | ### Basic Style Elements 3095 | 3096 | * Use SystemVerilog-2012 conventions, files named as module.sv, one file 3097 | per module 3098 | * Only ASCII, **100** chars per line, **no** tabs, **two** spaces per 3099 | indent for all paired keywords. 3100 | * C++ style comments `//` 3101 | * For multiple items on a line, **one** space must separate the comma 3102 | and the next character 3103 | * Include **whitespace** around keywords and binary operators 3104 | * **No** space between case item and colon, function/task/macro call 3105 | and open parenthesis 3106 | * Line wraps should indent by **four** spaces 3107 | * `begin` must be on the same line as the preceding keyword and end 3108 | the line 3109 | * `end` must start a new line 3110 | 3111 | ### Construct Naming 3112 | 3113 | * Use **lower\_snake\_case** for instance names, signals, declarations, 3114 | variables, types 3115 | * Use **UpperCamelCase** for tunable parameters, enumerated value names 3116 | * Use **ALL\_CAPS** for constants and define macros 3117 | * Main clock signal is named `clk`. All clock signals must start with `clk_` 3118 | * Reset signals are **active-low** and **asynchronous**, default name is 3119 | `rst_n` 3120 | * Signal names should be descriptive and be consistent throughout the 3121 | hierarchy 3122 | 3123 | ### Suffixes for signals and types 3124 | 3125 | * Add `_i` to module inputs, `_o` to module outputs or `_io` for 3126 | bi-directional module signals 3127 | * The input (next state) of a registered signal should have `_d` and 3128 | the output `_q` as suffix 3129 | * Pipelined versions of signals should be named `_q2`, `_q3`, etc. to 3130 | reflect their latency 3131 | * Active low signals should use `_n`. When using differential signals use 3132 | `_p` for active high 3133 | * Enumerated types should be suffixed with `_e` 3134 | * Multiple suffixes will not be separated with `_`. `n` should come first 3135 | `i`, `o`, or `io` last 3136 | 3137 | ### Language features 3138 | 3139 | * Use **full port declaration style** for modules, any clock and reset 3140 | declared first 3141 | * Use **named parameters** for instantiation, all declared ports must 3142 | be present, no `.*` 3143 | * Top-level parameters is preferred over `` `define`` globals 3144 | * Use **symbolically named constants** instead of raw numbers 3145 | * Local constants should be declared `localparam`, globals in a separate 3146 | **.svh** file. 3147 | * `logic` is preferred over `reg` and `wire`, declare all signals 3148 | explicitly 3149 | * `always_comb`, `always_ff` and `always_latch` are preferred over `always` 3150 | * Interfaces are discouraged 3151 | * Sequential logic must use **non-blocking** assignments 3152 | * Combinational blocks must use **blocking** assignments 3153 | * Use of latches is discouraged, use flip-flops when possible 3154 | * The use of `X` assignments in RTL is strongly discouraged, make use of SVAs 3155 | to check invalid behavior instead. 3156 | * Prefer `assign` statements wherever practical. 3157 | * Use `unique case` and always define a `default` case 3158 | * Use available signed arithmetic constructs wherever signed arithmetic 3159 | is used 3160 | * When printing use `0b` and `0x` as a prefix for binary and hex. Use 3161 | `_` for clarity 3162 | * Use logical constructs (i.e `||`) for logical comparison, bit-wise 3163 | (i.e `|`) for data comparison 3164 | * Bit vectors and packed arrays must be little-endian, unpacked arrays 3165 | must be big-endian 3166 | * FSMs: **no logic** except for reset should be performed in the process 3167 | for the state register 3168 | * A combinational process should first define **default value** of all 3169 | outputs in the process 3170 | * Default value for next state variable should be the current state 3171 | --------------------------------------------------------------------------------