Intro To SystemVerilog

SystemVerilog for Verification

Day One

Welcome
Welcome to the “Intro to SystemVerilog for Verification” class Requirements
Some HDL programming experience Some Unix experience Familiarity with some Unix editor Unix account in Folsom, Chandler, Dupont, or Penang.

Assumes use of Modelsim.
Intel Confidential

3

Class is an introduction only. Next Classes: Functional Coverage/Temporal language/Checkers How to write a SV Test How to write an SV BFM Length: 2 days Intel Confidential 4 .Scope Of Course Introduction to SystemVerilog for verification Hands-on lab assignments Students will not be SystemVerilog experts at the end of this class. Advanced classes go into more details.

command line keyboard input Screen output Placeholders for data user should input Intel Confidential Courier Regular Italic 5 .Typographic Conventions Regular Text Courier Bold Course Content Code examples.

constraints. Intel Confidential 6 . SystemVerilog adds testbench features such as classes. and temporal expressions to Verilog.What is SystemVerilog SystemVerilog is an IEEE extension to the Verilog language.

com/twiki/bin/view/Chipset/SystemVerilog Comprehensive information on SV: http://carmel.org/sv/SystemVerilog_3.1a.accellera.pdf AVC Wiki http://wwwfmec.Getting More Information SystemVerilog LRM http://www.intel.org Intel Confidential 7 .fm.aspx Additional Information www.eda.fm.com/sites/CPDCDTG/DATE/FEDAO/SystemVerilog%20Deployment%20Doc %20Lib/Forms/AllItems.intel.

type the following at the unix prompt: % source <local site specific setup script> Next.Using SystemVerilog To setup your environment to use SystemVerilog. cd svtraining % vlib work % vmap work work Intel Confidential 8 . and create a work library: % mkdir svtraining. create a training directory.

end: hello endmodule: helloWorld Intel Confidential 9 . initial begin: hello $display("Hello World").Hello World module helloWorld().

use the following command: % vsim -c -do "run -all.sv Note: If you do not name your file ending in .q -f" helloWorld Intel Confidential 10 . To run your program.sv.Compiling SystemVerilog To compile your program. type the following: % vlog hello. you must use the –sv option to vlog.

SystemVerilog supports two types of comments /* Block comments that can span * multiple lines */ // And single line comments $display(“hello”). // This is a comment Intel Confidential 11 .Commenting Your Code Like C++.

Lab 1: Hello World Create a module that prints “Hello World” using the $display command. Intel Confidential 12 .

Basic Data Types .

z) user-def 4-state user-defined size 4-state. user-defined vector size 4-state (1. 32 bit signed 4-state. 64 bit signed 2-state. 32 bit signed 2-state. 64 bit unsigned Intel Confidential 14 .x.Integer Data Type shortint int longint byte bit logic reg integer time 2-state (1. 16 bit signed 2-state.0. 8 bit signed 2-state. 0).

Signed/Unsigned byte. int. use the following syntax: logic [1:0] L. bit. reg and logic defaults to unsigned To create vectors. integer and longint defaults to signed Use unsigned to represent unsigned integer value Example: int unsigned ui. // Creates 2 bit logic // vector Intel Confidential 15 . shortint.

Strings string – dynamic allocated array of bytes SV provides methods for working with strings Str1 == Str2 Str1 != Str2 <. >. Str2. >= {Str1. <=. … Strn} Str1[index] Equality Inequality Comparison Concatenation indexing – return 0 if out of range Intel Confidential 16 .

String Methods len putc getc toupper tolower compare icompare substr atoi. atoct. atobin atoreal itoa hextoa octtoa bintoa realtoa Intel Confidential 17 . atohex.

Literal Values Integer Literal – Same as verilog value – unsized decimal value size’base value – sized integer in a specific radix Ex: 4’b0101.value Ex: 2. [z|Z]. 4’hC.4 Base Exponent ( E/e) Logic Value 0. 32’hDEAD_BEEF. [x|X] 18 Intel Confidential . 1. 2’b1Z Real Literal value.

str. i. string int i. Use of the following data types: 1. Hint: Output: # The integer i is 0x00000014 # The unsigned integer ui is 0xdeadbeef # The logic L is 1Z # string str1 is "Hello World" # string str2 is "Cruel World“ Intel Confidential 19 . l) $display(“Logic value in upper case %s”. logic 3.toupper()). “%b”. $display(“%d %h”. $sformat(str. h.Lab 2: Data Types Write a top level module that displays the following output. string str. h). int both signed and unsigned 2.

Operators Logic Operators & + | ~ % ^ / ~& * ~| ~^ << >> Arithmetic Operators ** <<< >>> Assignment Operators = += -= *= /= %= &= |= ^= <<= >>= <<<= >>>= Example: a += 3. Intel Confidential 20 . Equivalent to: a = a + 3.

if (a === b) $display(“Z === Z”). if (a != b) $display(“Z != Z”). Comparison Operators == != === !== =?= !?= > < <= >= Example: a = 1'bZ.Operators Auto-increment (++) Auto-decrement(--) Example: a = 1. Intel Confidential 21 . a++. a now contains 2. b = 1'bZ.

Concatenation The { } operator is used for concatenation. 32’b10}. “World”}. Sizes of assignment have to match. If LHS is smaller then assignment gets truncated. b. // v = 64b vector Can also be used on left hand side: {a. v = {32’b1. Intel Confidential 22 . c} = 3’b111. Example: s = {“Hello”. “ “.

and print the result as an integer to the screen: (1101001 XOR 11111001) ÷ 5 Ignore remainder. Intel Confidential 23 .Lab 3: Operators Write a SystemVerilog module to calculate the following.

Flow Control Constructs How to go with the flow .

forever.. foreach Intel Confidential 25 .SystemVerilog additions Verilog includes: if-(else-(if)). case. ?: (ternary) SystemVerilog: Enhances for Adds do. repeat.while. for. while.

equivalent to expr != ‘0’ Chain ‘if’ statements: if (expr) begin … end else if (expr) begin … end else begin … end Intel Confidential 26 .if Verilog ‘if’ expressions Then branch taken for any nonzero known value of expr (no ‘x’ or ‘z’).

Ex: var_m = (x == 1) ? a : b. with 3 operands.?: Operator. but conditional expr ? then_val : else_val Some call this the “ternary” operator. in the same vein as “unary” and “binary”. Intel Confidential 27 .

runtime evaluation.case 4-value exact matching. bit length of all expressions padded to same length case (expr) item: begin statement end item2. no fallthrough. item3. item4: begin statement end default: statement endcase Intel Confidential 28 .

casex Handle wild cards with either casez or casex casez: ‘z’ bit in either item or expression will be treated as a match for that bit casex: ‘z’ or ‘x’ bits will both match casex (8’bx100z011 ^ reg_a) 8’b1x1001?1: $display(“x”). 8’b01z10zx1: $display(“y”). 8’b11z01011: $display(“z”). endcase Intel Confidential 29 .casez.

forever
Continuous execution, without end, of body statement(s) Used with timing controls Usually last statement in some block initial : clock_drive begin clk = 1’b0; forever #10 clk = ~clk; end : clock_drive
Intel Confidential

30

repeat
Repeat a block ‘x’ times, no conditional test
repeat (expr) statement

What happens with expr = ‘x’ or ‘z’? Example
x = 0; repeat (16) begin $display(“%d”, x++); end
Intel Confidential

31

while
Executes statement as long as expr evaluates to true

while (expr) statement
Example:

while (reg_i) begin something_happens(); reg_i = reg_i – 1; end
32

Intel Confidential

step_assignment) statement Equivalent to begin initial_assignment. step_assignment. end end Intel Confidential 33 .for ‘C’ inspired for loop for (initial_assignment. while (condition) begin statement. condition.

j+=2.size().operators (Mentioned in operator section) for (int i. end Intel Confidential 34 .Enhanced for SystemVerilog adds: Loop variable declaration Multiple statements in init and step blocks (comma separated) ++ and -. i++) begin arr[i] += 200. arrb[i]--. i < arr.

while do statement while (expr).do. x). Intel Confidential 35 .. x--. end while (x). 1) while (x) begin $display(“%d”. x--. end 2) do begin $display(“%d”. What’s the difference? x = 0. x).

Lab 4: Flow control Write a SystemVerilog module to display the first 20 Fibonacci numbers. Fn = Fn-1 + Fn-2 Hint: F1 = F2 = 1 Intel Confidential 36 .

User Defined Types and Enumerated Types .

inch foot = 12.User Defined Types SystemVerilog supports a new keyword: typedef Syntax: typedef <base_data_type> <type_identifier> // inch becomes a new type // these are 2 new variables of type ‘inch’ typedef int inch . yard = 36. 8-38 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation .

NOTE: Define an enumeration with “ enum ” enum {red. A sized constant can be used to set size of the type enum bit [3:0] { bronze=4’h3. // All medal members are 4-bits Define a new type typedef enum {NO. c} vars. YES} bool. green. gold} medal. yellow} traf_lite1. arguments and relational operators 8-39 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation . // bool is NOT a SystemVerilog type bool myvar.Enumeration Syntax: enum [enum_base_type] { enum_name_declaration {. c=7 Default assigned values start at zero 0 1 2 enum {red. traf_lite2. b. green. Values can be cast to integer types and auto-incremented enum { a=5. silver. // b=6. yellow} lite. // but it just became one “myvar” will now be checked for valid values in all assignments.enum_name_declaration} } enum_base_type: default is int Enumeration is a useful way of defining abstract variables.

always @(posedge clk) col_ps <= col_ns. Colors col_ns. num() and name(). next(). To use enumerated types in numerical expressions the language provides the following functions: prev(). always @(col_ps) col_ns = col_ps. green. Colors col_ps.Enumeration example Modelsim now allows viewing of enum types in waveforms similar to VHDL enum types. white. Example typedef enum {red.next(). yellow. black} Colors. blue. last(). first(). Intel Confidential 40 .

Casting .

0)// real to int casting 7’(x-2)//number of bits to change size.0 * 3. Syntax: <type>’(<value/expression>) Examples: int’(2.Casting A data type can be changed by using a cast (’) operation. signed(m)//changes m to signed inteltype’(2+3)//casting to a user defined type [inteltype]. Intel Confidential 42 .

Arrays .

m = 4’b1100. In unpacked arrays [range is on the right side of the identifier] each individual element is considered by itself without any relation to other elements. // each element is only 1-bit deep Ex: logic [3:0] m [5:0] Arrays can have packed and unpacked dimensions. Ex: logic [3:0] m.Packed/Unpacked Arrays In packed arrays [range is on the left side of the identifier] all elements are glued together and can be overwritten by zero/sign extension of a single literal. Ex: logic m [5:0]. Intel Confidential 44 .

1.'{9.8}.Array Literals and Default To help in assigning literal values to arrays SV introduces the default keyword: int k [1:1000] = '{default: 5}.7. // All elements “5” For more control.2}.2.'{3{4}}}. int k [1:3][1:4] = '{'{1.'{5.12}}.3. consider the dimensions of the array and use { } to match those dimensions exactly.10.6.4}. // 3 groups of 4 int m [1:2][1:3] = '{'{0.11. // 2 groups of 3 8-45 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation .

not synthesizable Dynamic declaration of one index of an unpacked array Declares a dynamic array array_name of type data_type data_type array_name[] = new[ array_size ] [(array)] . int data[ ]. Allocates a new array array_name of type data_type and size array_size Optionally assigns values of array to array_name If no value is assigned then element has default value of data_type Examples: bit [3:0] nibble[ ]. // Dynamic array of 4-bit vectors // Dynamic array of integers // Declare a dynamic array // Create a 256-element array // Create a 100-element array // Create a 200-element array // preserving previous values in lower 100 addresses Copyright © 2005 Mentor Graphics Corporation 8-46 • SV for Verification Using Questa: Functional Coverage . addr = new[200](addr). data = new[256]. 1st new array in SV. int addr = new[100].Dynamic Arrays Syntax: data_type array_name[] . integer mem[ ].

addr.delete(). Cannot delete selected elements 8-47 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation .Dynamic Arrays – Methods function int size() Returns the current size of the array int addr[ ] = new[256]. int j = addr.size(). // j = 256 function void delete() Empties array contents and zero-sizes it int addr[ ] = new[256].

size()). data1. $display("Size of array = %d". data1. data2. data1. bit data1 [].size()).delete().size()). data2 = new[256](data1).Dynamic Array Example module dyn_arry (). end endmodule Intel Confidential 48 . $display("Size of array = %d". initial begin // create a 128 element array data1 = new [128]. $display("Size of array = %d".

q1 }. q1 = ‘{ q1. n }. i < q1. q1 = q1[1:$]. int q1[$]. q1 = ‘{ n. stacks. q1 = q1[0:$-1]. item. int n. item = q1[$]. i++) begin … end q1 = { }.Queues and Lists 3rd new array in SV. n = q1. etc. item = q1[0]. A list is basically a variable size array of any SV data type.size. not synthesizable SV has a built-in list mechanism which is ideal for queues.size. // clear the q1 list Copyright © 2005 Mentor Graphics Corporation 8-49 • SV for Verification Using Questa: Functional Coverage . // $ represents the ‘upper’ array boundary // uses concatenate syntax to write n to the left end of q1 // uses concatenate syntax to write n to the right end of q1 // read leftmost ( first ) item from list // read rightmost ( last ) item from list // determine number of items on q1 // delete leftmost ( first ) item of q1 // delete rightmost ( last ) item of q1 // step through a list using integers (NO POINTERS) for (int i=0.

Prototype: function queue_type pop_back(). Prototype: function queue_type pop_front(). Q = Q[1. Prototype: function void push_back (queue_type item). Q. e} 8-50 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation . Prototype: function void insert (int index.pop_front () => e = Q[0]. Q} push_back() Inserts the given element at the end of the queue. e = Q. Q[i. e) => delete() Q = ‘{Q[0:i-1].$]} Prototype: function int size().$-1] push_front() Inserts the given element at the front of the queue. Q. e = Q. Q = Q[0. e. Prototype: function void push_front (queue_type item). Q[i+1.$] pop_back() Removes and returns the last element of the queue. Q. If the queue is empty. Prototype: function void delete (int index).push_front (e) => Q = ‘{e.insert (i.$]} pop_front() Removes and returns the first element of the queue.delete (i) => Q = ‘{Q[0:i-1]. Inserts the given item at the specified index position.pop_back () => e = Q[$]. Q. Deletes the item at the specified index position. it returns 0.Queue Methods size() insert() Returns the number of items in the queue.push_back (e) => Q = ‘{Q. queue_type item).

// declare the q initial begin: store_disp Push elements into the queue q. i < q.push_back(0). Display all the contents in the queue for (int i = 0. q. q[i]). Display its contents $display("Size of queue = %0d". q.size()). i++) $display("q[%0d] = %0d". i. int q [$]. Delete the element of queue at index 1 q. Push to front of the queue q.size().Queue Example module queues (). end: store_disp // // // // // endmodule: queues Intel Confidential 51 .push_back(1).push_front (0).delete(1).

sv The output will look as follows: # Loading work.Lab 6: Queues Write a SystemVerilog program with specification as defined in lab6.lab6 # run –all # Size of queue = 3 # q[0] = 0 # q[1] = 1 # q[2] = 3 # q -f Intel Confidential 52 .

Data type used as an index serves as lookup key and imposes an order. Intel Confidential 53 . In other words value_type array_name [key_type]. Associative array do not have their storage allocated until it is used. It implements a lookup table of the elements of its declared type.Associative Arrays Associative arrays are used when the size of the array is not known or the data is sparse. Syntax: data_type array_name [index_type].

Integer Index Types Ex: bit [1:0] a [int].Index Types String Index Types Ex: int a [string]. a[“joe”] = 21. Intel Confidential 54 . a[5] = 2’b11.

When specified used to delete given index else whole array. exists (<index>) first (<index>). and 1 otherwise. Returns 1 if element exists at index else 0 assigns to the given index variable the value of the first/last (smallest/largest) index in the associative array.Associative Array Methods Function num() delete(<index>) Use Returns number of entries Index for delete optional. prev (<index>) Intel Confidential 55 . finds the entry whose index is greater/smaller than the given index. last (<index>) next (<index>). It returns 0 if the array is empty.

db ["joe"] = 21.Example module asoc_arry ().first(s)) do begin $display("Name = %s -. end while (db. // Display the size of the associative array $display("Size of hash = %0d". // Define an associative array initial begin: test string s. db[s]). db.Associative array methods . s.Age = %0d". // store values at indexes of associative array db ["jill"] = 19.exists("jill")) // check if index exists and change value begin db["jill"] = 25.next(s)). end // print the contents of associative array if (db.num()). if (db. int db [string]. end: test endmodule: asoc_arry Intel Confidential 56 .

Age 2. 4. 5. Define an associate array named 'assoc' assoc has the following attributes: INDEX . Print the contents of the associative array. Intel Confidential 57 . Display the size of the hash using $display statement Check if name Jane exists in the associative array and if it does change her age to 40.Lab 7: Associative Arrays 1. Make the following entries into assoc NAME AGE ---------------John 25 James 30 Jane 24 3.Name of person VALUE .

Procedural Blocks .

execution continues without stopping Intel Confidential 59 . Level-sensitive signal detection If the signal is already true.Triggering sensitivity @(<signal>) waits for an edge on <signal> before executing the next statement Edge-sensitive signal detection @(posedge clk) – waits for a rising edge clock @(negedge rstb) – waits for a falling edge on rs wait(<signal>) waits for a condition to become true before executing the next statement.

each block starts to execute concurrently at time 0. Example module stimulus. executes exactly once during a simulation.Initial Block An initial block starts at time 0. typically using begin and end.b. initial begin #5 a = 1’b1. Each block finishes execution independently of other blocks. Multiple behavioral statements must be grouped. If there are multiple initial blocks. end endmodule Intel Confidential 60 . #25 b = 1’b0. and then does not execute again. reg a.

end endmodule 61 . end always @(posedge clk) begin <statements>.Always Block The always block statement starts evaluating sensitivity list at time 0 and executes statements in the always block continuously in a looping fashion. Intel Confidential Example module clock_gen. This statement is used to model a block of activity that is repeated continuously. bit clock. forever #10 clock = ~clock. initial begin clock = 1’b0.

except that it occurs at the end of simulation time and executes without delays. A final block is typically used to display statistical information about the simulation.$time/period). end Intel Confidential 62 .Final Blocks The final block is like an initial block. $display("Final PC = %h". Example final begin $display("Number of cycles executed %d".PC). defining a procedural block of statements.

Define an initial block such that it generates a clock clk time period = 10ns NOTE: Need to initialize clock even though the bit data type is automatically done. Define a final block to print the size of 'q' at the end of simulation Hint: Use final blocks Output: # Size of q = 4 Intel Confidential 63 . Increment 'counter' when always block is triggered 4.Lab 8: Procedural Blocks Create a SystemVerilog module: 1. Create an always blocks that stores the value of signal 'clk' into queue 'q' at positive edge of the clock. 3. 2. When counter reaches 4 call $finish system call Hint: Use if statement 5.

Types of Assignment Blocking Nonblocking .

a = 5. end // at time 0 a = 30 //at time 10 a = 5. c = 5 // at time 20 a = 5. Execution flow is blocked until a given blocking assignment is complete. If there is a time delay on a statement then the next statement will not be executed until this delay is over. b = x. b = 2. c = x // at time 20 a = 5. c = 5 65 . #10.Blocking Assignment The simulator completes a blocking assignment (=) in one pass [execution and assignment]. b = x. c = #10 a. b = 2. Intel Confidential Example initial begin a = 30.

Right-hand side of the assignment is sampled immediately. c <= #10 a. a <= 5. b = 2. Assignment to the lefthand side is postponed until other evaluations in a given simulation time step are complete. end // at time 0 a = 30 //at time 10 a = 5.Nonblocking Assignment The simulator completes a nonblocking assignment (<=) in two passes. b = 2. b <= 2. Example initial begin a = 30. #10. c = 30 66 Intel Confidential . c = x // at time 20 a = 5.

Tasks and Functions .

automatic tasks allocate memory dynamically at call time.local_b+1). return. Default port direction is input ANSI style portlists Implied begin…end task automatic my_task( input int local_a.Tasks SystemVerilog makes a number of extensions to basic Verilog syntax. int local_b). terminates task at that point endtask Full recursion is supported (automatic variables/arguments stored on stack) • Can do concurrent calls • Can do recursive calls 8-68 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation . etc. even structs. my_task(local_a-1. return keyword is supported and global_b = local_b. // end ‘this’ copy of task end global_a = local_a. if (local_a == local_b) Arguments can be ANY begin SV type.

reentry(). $display("Value of counter = %0d".Task usage examples [1] Example of a static task module task_reentry(). task reentry(). reentry(). counter++. int counter = 0. endtask initial begin reentry(). counter++. counter++. counter++. counter++. counter++. reentry(). counter++. $display("Value of counter = %0d". int counter = 0. counter). counter). reentry(). counter++. counter++. end endmodule: task_reentry Example of an automatic task module task_reentry(). endtask initial begin reentry(). end endmodule: task_reentry What will be the value of counter for each call to reentry()? Intel Confidential What will be the value of counter for each call to reentry()? 69 . task automatic reentry(). reentry(). counter++. reentry().

Task usage examples [2]
module task_function (); int i, j, z; initial begin i = 5; j = 3; end initial begin #10; tsk (i, z, j); $display("Z = %0d, J = %0d", z, j); // prints Z = 50, J = 4 end task tsk (input int t1, output int t2, inout int t3); t2 = 10 * t1; t3++; endtask: tsk endmodule
Intel Confidential

70

Functions
automatic functions allocate memory dynamically at call time (full recursion). Default port direction is input (also supports output) ANSI style portlists Implied begin…end

function automatic int factorial (int n); if (n==0) return(1); // factorial 0 is 1 else return(factorial(n-1)*n); endfunction

Arguments and return type can be ANY SV type, even complex structs, etc.

return(value) is supported and terminates function at that point

function void inverta(); a = !a endfunction reg a;
Return type of void means no return value! Recommended style (instead of writing a task) to guarantee a task executes with 0 delay.

initial inverta(); // function called like a task
8-71 • SV for Verification Using Questa: Functional Coverage

End
Copyright © 2005 Mentor Graphics Corporation

Function usage examples
Example 1
function void show_packet(); $display("=================="); $display("Packet Type = %s", context_name); $display("Address = %h", addr); $display("Data = %h", data); $display("==================="); endfunction

Example 2
typedef enum {FALSE, TRUE} bool; bool cache_range; function bool is_cache_range (); if (addr > 0 & addr < 10) begin cache_range = TRUE; $display("addr in cache range = %d", addr); return TRUE; end else begin cache_range = FALSE; return FALSE; end endfunction

Intel Confidential

72

Task cannot be called from functions. output and inout. By default arguments are passed by value. Functions Function can enable other functions only. output or inout types. [Pass by reference not supported in Modelsim 6. Functions should execute in zero simulation time. Functions have only one return value but SystemVerilog also allows functions to have input.Summary Tasks Tasks can enable other tasks and functions Tasks may execute in non-zero simulation time. Both tasks and functions support passing arguments by reference. Tasks may have zero or more arguments of type input.1] Intel Confidential 73 .Task and Functions Usage .

Task and function argument passing Passing by value is the default mechanism for passing arguments. <function body>. Copies arguments passed into subroutine area. each copy retains a local copy of argument. When defined as automatic. endfunction // a local copy of ‘m’ is // created when ‘val’ is // called. Changes to arguments in subroutine are not visible outside. Example function int val (byte m [3:0]). Intel Confidential 74 .

// equivalent: read (0. 1) read (). // equivalent: read (2.int data = 1). 5. 5). endtask // task can be called using // following default arguments read (. Example task read (int j =0.Default argument values – Tasks/Functions SV allows a subroutine declaration to specify default value for each argument. When subroutine is called. 1) read (2. arguments with default values can be omitted from the call and corresponding default values are used. BKM: Default arguments should be optional arguments and should be the final set of arguments. 5). int k. 5. // error since k has no default // value Intel Confidential 75 .

returns the value of 1 indicating success. index =0. 2. index =1. Define a function named "change_str" which does the following: 1. 5. Define a named initial block "store_info" Store the following values into the queue 1. Takes queue and index value as input 2. changes the value of str stored in queue at index 1 to "Intel Ireland" from "Intel Folsom“. Define a queue 'q' of string type. str = "Intel Chandler" 2. 3.Lab 9a Create a SystemVerilog module as described below: 1. Intel Confidential 76 . 4. str = "Intel Folsom" Display the size of the queue. 3.

Define a task named “show" which does the following: 1. 7. When the return value from "change_str" function is 1. prints the elements stored in the queue using the following format: Output: Loading work.Lab 9b 6. 2. 3.lab9 run –all Size of storage q = 2 q[0] = Intel Chandler q[1] = Intel Ireland q -f Intel Confidential 77 . # # # # # # Takes queue and return value from "change_str" as inputs The default inital value [task input argument: ret_value] shall be set to 0. q[%0d] = %s" Notes: "change_str" and “show" are called from named initial block "store_info".

Hierarchy Who comes first .

Hierarchy of design Ports represent communication Inout Inputs Module Outputs Intel Confidential 79 .Modules The basic hardware unit in Verilog.

inout Type – wire. etc. y. output reg r. input bit w[3:0]. logic.Ports Connections Direction – input. inout logic s. user-defined. bit. output logic q. output. Intel Confidential 80 . z. input int x. Examples: input bit[3:0] x.

// Better cpu cpu_inst2(. output logic[63:0] addr.data(data).* ). . data. initial begin : place_holder $display(“A NOTHING CPU”).Module syntax module x (port_list). Intel Confidential 81 . Example module cpu (inout logic[63:0] data. end : place_holder endmodule : cpu // Error prone cpu cpu_inst1(addr. // Newer cpu cpu_inst3( . output logic w_or_rb ). .w_or_rb(w_or_rb) ). module_body endmodule : x Instantiation x x1 (port_binding_list). w_or_rb).addr(addr).

Parameters
Generic parameters (ala VHDL generics) Elaboration time constants Separate “ports” on a module Example
module xyz #(parameter int width = 8) (input x[width-1:0], output y)); assign y[width-1:0] = x[width-1:0]^ 8’hAE; endmodule xyz #(.width(14)) xyz1 (.x(inp), .y(outp));

Intel Confidential

82

Multiple drivers
Most nets have only one driver Nets with multiple drivers need to have a resolution function In SystemVerilog there is a wire type that includes a resolution function Example
wire x; dut dut1(.outp(x)); dut dut2(.outp(x));
Intel Confidential

83

Interfaces
Great coding efficiency can be achieved by modeling the blocks of a system at different levels of abstraction, behavioral, rtl, gate, etc. In Verilog, the I/O between these blocks has always remained at the lowest “wire” level. High-performance system-level simulation requires the abstraction of inter-block communication.
module mmu(d, a, rw_, en); output [15:0] a; output rw_, en; inout [7:0] d; ... endmodule module mem(d, a, rw_, en); input [15:0] a; input rw_, en; inout [7:0] d; ... Traditional endmodule Verilog module system; wire [7:0] data; wire [15:0] addr; wire ena, rw_; mmu U1 (data, addr, rw_, ena); mem U2 (data, addr, rw_, ena); endmodule interface interf; logic [7:0] data; logic [15:0] addr; logic ena, rw_; endinterface module mmu(interf io); io.addr <= ad; ... endmodule module mem(interf io); adr = io.addr; ... endmodule SystemVerilog module system; interf i1; mmu U1 (i1); mem U2 (i1); endmodule
Copyright © 2005 Mentor Graphics Corporation

data

MMU

ad

addr rw_ ena

adr

MEM

interface

At it’s simplest an interface is like a module for ports/wires

8-84 • SV for Verification Using Questa: Functional Coverage

• Easy to swap interface abstractions without any effect on source/sink Copyright © 2005 Mentor Graphics Corporation 8-85 • SV for Verification Using Questa: Functional Coverage .a = 0.rd_a() == 1) a reg a.IO Abstraction source reg a. interface intf sink if ( intf. Enhanced interface with methods • source/sink only call methods • source/sink don’t see low-level “details” like variables/structure. etc. task rd_a(). a = 0.a == 1) … a reg a. sink a a a if ( a == 1) … Traditional Verilog approach • Simple netlist-level IO • source/sink can be abstracted but IO must stay at low level • IO operations are cumbersome Simple “bundle” interface • All accesses are through interface • Simplifies source/sink declarations source intf. interface intf sink if (intf. source intf. task wrt_a().wrt_a(0).

Changing a bus spec (add a new signal?) means editing the interface only. This includes tasks. pipelining. etc. so it simplifies design. 8-86 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation . • Interfaces are synthesizable. may be captured in an interface rather than the connecting modules. • Interfaces are defined once and used widely. e.g. • Bus timing. initial/always blocks. etc. • An interface may contain any legal SystemVerilog code except module definitions and/or instances. not just internals.Interface Characteristics • Interfaces bring abstraction-level enhancements to ports. parameters. functions.

Interface in hierarchy Interfaces appear as normal module instantiations in design hierarchy. At the moment. interfaces cannot be instantiated in VHDL blocks. Interface instances interface name: bfm_interface Instantiated twice: bi1. bi2 Intel Confidential 87 .

c. endinterface : i2 module m (i2.slave i). input c. … endmodule: m module s (i2. b.i(i. b. d). … endmodule: s module top().modport Different users of interface need different views Master/Slave Example interface i2. m u1(. d.slave)).master i).i(i. endmodule: top Intel Confidential Restrict access to internal interface signals Protect implementation signals from corruption 88 . b. d). i2 i(). output c. modport master (input a. s u2(. wire a.master)). modport slave (output a.

and an output named a Use an interface to connect Intel Confidential 89 . moda has an input named a. and an output named b modb has an input named b.Lab 10 Create modules moda and modb.

Clocking blocks Synchronous blocks can have race conditions when all trying to evaluate blocks in same time step Clocking blocks capture timing and synchronization requirements Intel Confidential 90 .

item list. ready. input data. endclocking Intel Confidential 91 . enable=top.enable.Clocking block syntax clocking block_name clocking_event. output negedge ack. default input #10ns output #2ns. endclocking : block_name clocking bus @(posedge clock1).mem1. input #1 addr.

Program Blocks A program block is similar to a module. end endprogram: helloWorld Intel Confidential 92 . end initial begin: there $display(“Hello There”). It is used for testbench code. program helloWorld(). initial begin: hello $display("Hello World").

but may not contain always. or other programs. Programs may be explicitly exited using the $exit task. but not the other way around. modules. Program blocks may contain one or more initial blocks. When all program blocks complete the simulation ends.Program Blocks Programs can be instantiated inside modules. Intel Confidential 93 . interfaces. UDPs.

Day Two .

Classes SystemVerilog and Object Oriented Programming Testbench Only .

etc. direction. Instances of the “Automobile” class might be “Joe’s car”. Intel Confidential 96 . “Bob’s car”. etc. etc. increaseSpeed. Color. stop.Object Oriented Primer A Class is a description of some group of things that have something in common. speed. Encapsulation: Encapsulate implementation details internal to the object/class. turn. “Sally’s truck”. Objects/Classes have: Data Operations/Methods Example: A class might be “Automobile”. Start. Objects are individual instances of “classes”.

a “sedan” is a “Automobile”. When using inheritance. an “Automobile” class might have 4 instances of a “wheel” class. Extending the “Automobile” class example. “truck”. etc. or use them as-is. In this case. In these cases. For example. the sub-class “inherits” all the parents public/protected data properties and methods. users might create subclasses for “sedan”. “van”. i.Classes Inheritance: (is-a relationship) Allows users to extend existing classes. making minor modifications. so inheritance should not be used. the subclass IS-A superclass. Composition: (has-a relationship) Composition is used for the case where one object HAS-A instance of another class. It is allowed to override them. Intel Confidential 97 . Etc. The “van” class might also have a “minivan” subclass.e. a wheel is not an “Automobile”.

Intel Confidential 98 . SystemVerilog can only process objects differently depending on their class.Classes Polymorphism: Most common definition of polymorphism is the ability of the language to process objects differently depending on their data type or class.

property declarations. methods. constructor. endclass: myPacket Intel Confidential 99 .Class Format class classname [extends superclass].

function new().4}. data = ‘{1. b = a + 5. endtask: myTask. virtual function integer myFunc(int b). output byte b). command = IDLE. endfunction: new virtual task myTask(input byte a. endfunction: myFunc endclass: myPacket Intel Confidential 100 . return(b – 3). #10.Example Class class myPacket extends BasePacket.3. // inheritance byte data[$]. bit [3:0] command.2.

c. c. Intel Confidential 101 .task1().function1(). c = new.property1 = 10. c. c.” operator.Referencing Properties and Methods Instance data properties and methods may be referenced/called using the “.property2 = 11.

Constructors may take arguments. super. endfunction: new // Creating an instance invokes the constructor: myInstance = new.4}. bit[12:0] addr = 0). … endfunction: new Only one constructor per class allowed.new().2. command = IDLE. … endfunction: new When extending a class constructor.new(). function new().3. call super.Constructors Example constructor function new(). function new(int a = 0. data = {1. Intel Confidential 102 .

int x. y.this The special variable this is a predefined object handle for the current object instance. since the current instance is assumed if no variable is specified.x = this. myOtherMethod(). … virtual function integer myFunc(). // Equivalent: this. It is optional.myOtherMethod().y + this. x = y + z.z. // Equivalent to: this. endfunction: myFunc endclass: myPacket Intel Confidential 103 . z. class myPacket extends BasePacket.

Static Properties Static properties/data members are “static” to all instances of the class. endfunction: setStaticProperty endclass: StaticExample Intel Confidential 104 . If one instance changes the value. $display(“Current value: %d”. it changes the value for all instances.staticProperty). class StaticExample. staticProperty = val. virtual function void showStaticProperty(). static int staticProperty = 0. This means that all instances share the same value of this variable. endfunction: showStaticProperty virtual function void setStaticProperty(int val).

To invoke a static method. Intel Confidential 105 . … endfunction: staticMethod endclass: StaticExample StaticExample::staticMethod(). use Classname::methodName class StaticExample. Static methods may only modify static properties. static int staticProperty = 0.Static Methods Static methods do not require an instance of the class to operate on. static function void staticMethod().

$display(“What do I print? %d” . class BaseClass. endfunction: myFunc endclass: mySecondClass BaseClass bc. but only a few details need to change.myFunc(6)). the method defined in the class of the object instance is called.bc. $display(“What do I print? %d” . virtual function int myFunc(int b). virtual function in myFunc(int b).myFunc(6)).Polymorphism Instances of subclasses may be assigned to variables declared of the superclass type. endfunction myFunc endclass: BaseClass class myFirstClass extends BaseClass. endfunction: myFunc endclass: myFirstClass class mySecondClass extends BaseClass. // Returns an instance mySecondClass bc = getSecondClassInstance(). If the subclass overrides a method specified in the superclass. 106 Intel Confidential .bc. virtual function int myFunc(int b). return(b + 10). // Returns an instance myFirstClass bc = getFirstClassInstance(). return(b + 3). This is useful for cases where the general algorithm is the same for all the subclasses. return(b – 3).

Data Hiding and Encapsulation To make data members visible only to the class. To make data members visible only to the class. or any subclasses. protected int x. class myPacket extends BasePacket. local int x. use the protected keyword. Intel Confidential 107 . use the local keyword. class myPacket extends BasePacket.

class myPacket extends BasePacket. function new(int id). size = id * 4096. // Single assignment in // constructor OK … Intel Confidential 108 . // Assignment of constant value in // declaration makes it constant // to all instances. and may be different per class instance. const int size. const constants are different from ` define constants because the initial value may be determined at runtime.Constant Class Properties The const keyword may be used to make class properties unchangeable.

An abstract class may not be instantiated. virtual class BasePacket. … Intel Confidential 109 . Users must subclass the abstract class to create instances of the class.Abstract Classes The virtual keyword may be used on a class to make the class “abstract”.

To do this. C1 c1Instance. Example: typedef class C2. // Forward declaration of C2 class C1.Typedef Class and Forward References Sometimes it is necessary to use a class before it has been defined. C2 c2Instance. … endclass: C1 class C2. … endclass: C2 Intel Confidential 110 . then later define the class. you can use a typedef forward reference.

setData(‘{1.5. setData(byte d[$]). x. Hint: $sformat(str. x = new.7. // Length in bytes Methods: // Sets data to value passed and // length to the size of queue passed.Lab 11a: Classes Create an “Xaction” class. Using your new class. Data=0xXXXXXXXX string toString().6.data). $display(“%s”.2."Len=%d. Format should be: // Len=X. DATA=0x%h".3.length. run the following test code. // Returns formatted representation of // xaction. The Xaction class should have the following Properties: byte int data[$].4.toString()). // Queue of bytes length. Xaction x. Intel Confidential 111 .x.8}).

Intel Confidential 112 . x = s. add printing the iws value. s = new.8}). SubXaction s. $display(“current time = %t”. $display(“%s”. s.Lab 11b: Classes Modify lab10a and create a subclass of the Xaction class that has the following property added: int iws.iws = 10.6. Be sure to use super. $display(“current time = %t”. s. and not reimplement the toString of the parent class: // Len=X. // Initiator wait states // Wait IWS time steps stall().setData(’{5.x.$time).toString. IWS=X Execute the following testcode.7.toString()).stall(). x. Data=0xXXXXXXXX. Add a task to the class that waits for the number of time steps specified in iws: Override the toString() method.$time). Xaction x.

Intel Confidential 113 . Virtual interfaces let BFM models manipulate virtual set of signals instead of actual RTL signals. Virtual interface is a variable that represents an interface instance. need a specialized mechanism Virtual interfaces provide a mechanism for separating test programs/BFM models from the actual signals. Syntax: virtual <interface name> <variable name>.Virtual Interfaces Classes cannot have modules or interfaces.

logic [7:0] addr. bit grant. bit req. @(posedge bus. $time).req. $display("Req = %b @ %0t". // dut instance dut dut1 (infc_b. clk). bus. endfunction task req_bus(). logic [7:0] data. class BFM. xaction = new.Virtual Interfaces Example // interface // definition interface Bus (input logic clk). endinterface: Bus // testbench // interface instance Bus infc_b (clk). virtual Bus bus. bus. Xaction xaction. endtask: req_bus endclass: BFM Intel Confidential 114 .req <= 1'b1. // need to initialize virtual interface // in constructor bus = b. function new (virtual Bus b). // class instance BFM mybfm = new (infc_b).clk).

Random Constraints How to decide how random to be .

Random data sources Random exercise of stimulus allows easy cases to be done easily Ability to “tune” random stimulus usually gives more coverage with less work (be careful) Save the impossible cases until the Design Under Test (DUT) is healthier Works hand-in-hand with functional coverage Intel Confidential 116 .

thread stable.Simplest randomness $urandom system tasks $urandom() is SV. deterministic $urandom returns unsigned 32-bit integers Procedural call can be inserted wherever needed Intel Confidential 117 .

rand int a. end : random_loop Intel Confidential 118 . except for some explicit randomization Select new random value each time “.More sophisticated mechanisms Random variables (rand modifier – classes only) Must be properties of a class. c. b.randomize(). endclass : x x x_inst = new. initial begin : random_loop forever @(posedge clk) x_inst.randomize()” is called Example: class x.

every value of the variable will be reached before any value is duplicated Caution… special solver ordering for randc Intel Confidential 119 .What’s ‘randc’ for? Exhaustive permutations of a variable ‘c’ is for “cyclic”.

b > 0. } c_eq_10 {c == 10.} b_in_range { b >= 2 && b <= 8. c > 0.} How many permutations are now possible? Intel Confidential 120 .Constraints Set of Boolean algebraic expressions Relationships between random variables and: Other random variables Non-random state variables Example: constraint constraint constraint constraint a_le_b { a <= b. } all_gt_0 {a > 0.

10.42.27. } constraint b_between_w_z { b <= z && b >= w.Constraints Restrict range of possible values Can use state variables to restrict range of random variables Example: int x[7] = ’{3. constraint c_within_set_of_x { c inside x. w = 10.6.1}. int z = ’hff.5. } Intel Confidential 121 .

} z.randomize() begin … end -solvefaildebug Intel Confidential y.Conflicting constraints What happens when you impose constraints that conflict in some way? Example: constraint x_gt_y { x > constraint y_gt_z { y > constraint z_gt_x { z > … if ( x_inst. } x. } == 0 ) // Solver error Modelsim cmdline setting 122 .

e.Constraint operators Any Verilog boolean expression i. x < y+b-c*10>>20 Other constraint operations set membership implication iterative constraint variable ordering functions within -> or if…else… foreach solve … before … func_x() Intel Confidential 123 .

Implication constraint Uses one boolean to decide if another constraint must hold (trans_size == SMALL) -> (length < 10) (trans_size == MED) -> (length >= 10 && length <= 100) (trans_size == LARGE) -> (length > 100) Advanced note: a -> b is equivalent to !a || b Intel Confidential 124 .

10}.size-1) -> A[k+1] > A[k]. 6. 8. including reference to other elements of array constraint foreach A[i] } constraint foreach (k < } c1 { ( A[i] ) inside {2. Intel Confidential 125 . 4. c2 { ( A[k] ) A.Loop/array constraints Constrain every element of an array in some fashion.

randomize() No arguments.Arguments to . randomize class members according to declaration modifiers Optional arguments Specify the variables which are random Can make ‘rand’ override declaration type for this call Declares entire set of random variables for this run of Constraint Solver ‘null’ argument forces checking constraints only Cannot change ‘randc’ to ‘rand’ Intel Confidential 126 .randomize() Normal form of .

}. Intel Confidential 127 .randomize() with { x < 100.. z > buzz.randomize with {} Specify inline constraints that are added to constraint set to solve trans.

Distribution Constraints Operators: := :/ dist Example: constraint twsConstraint { tws dist { [0:2] :/ 10. } Intel Confidential 128 . [10:50] :/ 9 }. mem_read := 5. io_read := 1. io_write := 1. lrrww := 1. idle := 1 }. lrw := 1. [3:9] :/ 1. } constraint distConstraint { cmd dist { mem_write := 10.

} constraint c2 { (len == SM) -> (byte_len <= 4). addr. endfunction : toString endclass : transaction <CONTINUED> Intel Confidential 129 . byte_len). constraint c1 { wr_or_rd_b -> len != LRG. LRG} trans_len. } virtual function string toString() return sformat(“%5H: %s %d bytes”. rand bit wr_or_rd_b.Putting it all together module test_rand. class transaction { rand bit [19:0] addr.} constraint c4 { (len == LRG) -> (byte_len > 8). } constraint c3 { (len == MED) -> (byte_len > 4 && byte_len <= 8). typedef enum {SM. (wr_or_rd_b ? “WR” : “RD”). rand trans_len len. MED. } // Mem above 16-bit is write-only IO devices constraint c5 { (!wr_or_rd_b) -> (addr[19:16] != 0). rand bit [3:0] byte_len.

repeat (20) begin : rand_gen if (trans. intial begin : test_body int counter = 0. $finish.randomize() == 0) begin $display(“ERROR: Random constraints conflict”). trans. end $display(“%d: %s”.toString()).Putting it all together (cont) transaction trans = new(). counter++. end : rand_gen end : test_body endmodule : test_rand Intel Confidential 130 .

printing the Xaction after each randomize() call. Write a loop that calls randomize() 40 times. with the following enumerated values: SMALL. LARGE 10%.Lab 12: Random Constraints Modify the Xaction class created in lab11 and make all properties rand. Add a distribution constraint that make the size: SMALL 70%. MEDIUM 20%. 3. 1. 2. Add a constraint that sets the length based on the size property: SMALL : (length <= 10) MEDIUM : (length >10) && (length <=20) LARGE : (length > 20) && (length < 100) (Note: Add a constraint saying the length must be > 0) 4. LARGE. MEDIUM. Add a rand property named size. Intel Confidential 131 .

sequences. interfaces and programs Intel Confidential 132 . types. tasks. and properties among modules. functions. data.Packages A mechanism for sharing parameters. classes.

import p::c if ( ! c ) … 133 . FALSE. endpackage u = p::c. BOOL c = TRUE. TRUE} BOOL.c. typedef enum {FALSE. y = FALSE.Package Search Order Rules package p. BOOL. y = p::TRUE A qualified package identifier is visible in any scope All declarations inside package p become potentially directly visible in the importing scope: . TRUE The importing identifiers become directly visible in the importing scope: -c Intel Confidential import p::*.

endclass typedef enum {FALSE. class Data. int b. endmodule Intel Confidential 134 . int a. endmodule OR module top. TRUE} BOOL.Package Example keyword package … endpackage Example: package p. BOOL b = TRUE. import p::*. p::BOOL b = p::TRUE. endpackage : p module top.

Lab 13: Packages Create two packages which contains an int C and C is initialized with two different values. Write a top level module that print out both C value Intel Confidential 135 .

System Tasks .

only one $monitor active Intel Confidential 137 . $write – printf-ish ($display w/out newline) $sformat – print formatted string (ala sprintf) $monitor – Implicit task to call $display any time arguments change. with “\n” implied $display (format_string. arguments).Display $display – printf-ish.

Time $time – Returns 64-bit time normalized to unit timescale. most common for error messages $realtime – floating point scaled to timescale $stime – least significant 32-bits of time Intel Confidential 138 .

initial @(posedge all_bfms_done) $finish(). final blocks $stop – halt simulation $exit – quit execution of program block (SV-only) Example initial #10000 $finish().Simulation Control $finish – end simulation (quit simulator). Intel Confidential 139 .

Example string buf_s.File I/O integer char int integer integer integer fd c code code code code = = = = = = $fopen(string filename. out_fd = $fopen(“output_file”. chars_read = $fgets(buf_s. string mode) $fgetc(int fd). $fscanf(int fd. $ungetc(char c. “w”). in_fd). $finish(). “r”). int fd). in_fd = $fopen(“input_file”. $sscanf(string str. hexStartAddr. args). $fgets(string str. int fd). hexEndAddr) ) begin $display(“Address Range: %8x -> %8x”. FORMAT. FORMAT. hexStartAddr. if (chars_read == 0) begin $display(“End of file”). args). "%x %x". hexEndAddr). end if (2==$sscanf(buf_s. end Intel Confidential 140 .

File I/O $fclose $fdisplay $fdisplayb $fdisplayh $fdisplayo $fgetc $fflush $fgets $fmonitor $fmonitorb $fmonitorh $fmonitoro $readmemb $swrite $swriteo $sformat $fscanf $fread $fseek $fopen $fstrobe $fstrobeb $fstrobeh $fstrobeo $ungetc $ferror $rewind $fwrite $fwriteb $fwriteh $fwriteo $readmemh $swriteb $swriteh $sdf_annotate $sscanf $ftell Intel Confidential 141 .

Random functions $random $dist_chi_square $dist_exponential $dist_poisson $dist_uniform $dist_erlang $dist_normal $dist_t Intel Confidential 142 .

Local variables declared can be accessed through hierarchical referencing. By providing blocks with names provides the following advantages: Declaration of local variables. Named blocks are part of the design hierarchy. end end : latch_counter … Intel Confidential 143 . Example … always @(CK or D) begin : latch_counter int count.Named blocks Blocks can be provided names. begin O = D . if (CK) count = count + 1.

Threads .

end 145 . #5 a = 3. then begins the next You always know the order in which it actually executes the statements The simulator exits the block after finishing the last statement Intel Confidential Example begin #5 a = 1.Sequential Blocks There is the difference between a sequential and a concurrent block: Simulator executes statements in a sequential block in sequence It finishes the current statement. #5 a = 2.

join is illegal. Example fork begin $display( "First Block\n" ). @eventA.Concurrent Blocks The simulator executes statements in a concurrent block in parallel It starts executing all statements simultaneously You can not know the order in which it actually executes statements scheduled for the same simulation time The simulator exits the block after finishing the latest statement. end begin $display( "Second Block\n" ). A return statement in the context of fork. end join Intel Confidential 146 .. # 20ns.

end NOTE Child processes spawned by a fork…join_none do not start to execute until the parent process hits a blocking statement Copyright © 2005 Mentor Graphics Corporation 8-147 • SV for Verification Using Questa: Functional Coverage .Dynamic Processes Inspired by the need for software verification environments to dynamically start and stop threads. SystemVerilog defines 2 new special cases of fork…join with associated keywords join_any & join_none join_any join_none fork … other blocks continue … as dynamic threads … join_any // any block finished begin fork … join_none // no waiting at all @(sig1).

task4(). Q 6.1 The wait fork statement is used to ensure that all child processes (spawned by the process where it is called) have completed execution. begin fork task1().Process Control – Wait Fork With Dynamic processes SystemVerilog needed to provide more global detection that spawned processes have completed. join_none wait fork. join_any fork task3(). end // continue when either task completes // continue regardless // block until tasks 1-4 complete 8-148 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation . task2().

fork run_tests().1 The disable fork statement terminates all active child processes of the process where it is called. timeout( 1000 ). endtask // 2 child tasks spawned in parallel. simul_test2. join_any disable fork. task run_tests. in other words it terminates child processes. etc. first to finish triggers join_any // Kills the slower task (including any grandchild processes and so on) 8-149 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation . Termination is recursive. join endtask task test_with_timeout. grandchild processes.Process Control – Disable Fork Q 6. fork simul_test1.

initial begin clk = 1'b0. always @(posedge clk) -> a. module event_testing (). forever #10 clk = !clk . end endmodule Intel Confidential 150 . b. bit clk. always @(negedge clk) -> b. event a. These events are such that trigger state cannot be observed but only their effect.Events Trigger Types [1] Triggering an event Named events are triggered using -> operator. Triggering an event unblocks all processes currently waiting on the event. Event can be visualized in wave window.

counter++. end Intel Confidential 151 . $time). Example always @(posedge clk) begin if (counter == 2) ->> a. The statement executes without blocking and it creates a nonblocking assign update event in the time in which the event occurs.Events Trigger Types [2] Nonblocking event trigger They are triggered using ->> operator. end initial begin forever @(a) $display("event a triggered @ %0t. The effect of this event is felt during the nonblocking assignment region of a simulation cycle.

bit clk. end endmodule 152 Intel Confidential . always @(a or b) -> c. always @(negedge clk) -> b. forever #10 clk = !clk .Waiting for an event @ is used to wait for an event. initial begin clk = 1'b0. b. The @ operator blocks the calling process until the given event is triggered. c. always @(posedge clk) -> a. Example module event_testing (). event a.

b. wait_order (a. If any events are triggered out of order then it causes a fail of the operation. Intel Confidential Example bit success.Event Sequencing: wait_order() wait_order construct suspends the calling process until all specified events are triggered in the given order [left to right]. // event must occur in the // following order // ->a ->b ->c if not it fails. c) success = 1. else success = 0. 153 .

a = b. both merge into one event variable. // also triggers a Intel Confidential 154 . Example event a.Event Variables [1] Merging Events When one event variable is assigned to another. Executing -> on either one of the events affects processes waiting on either event variable. b. -> a. // also triggers b -> b.

Event Variables [2] Reclaiming Events When an event variable is assigned the special null value. the association between the event variable and the underlying synchronization queue is broken. Intel Confidential 155 . Example event E1 = null.

if ( E1 ) // same as if ( E1 != null ) E1 = E2. if ( E1 == E2 ) $display( "E1 and E2 are the same event" ). E2. Example event E1. Equality (==) with another event or with null. Inequality (!=) with another event or with null.Event Variables [3] Event Comparison Event variables can be compared against other event variables or the special value null. Intel Confidential 156 .

Semaphores Can be described as counters used to control access to shared resources by multiple processes [threads]. Printer1 Printer1 [1] [0] Printer2 [1] 3 keys 2 keys Printer3 [1] Print manager Intel Confidential 157 .

Return one or more keys back. Obtain one or more keys. Try to get one or more keys without blocking.Semaphore Methods Semaphore provides following built-in methods: Method new() put() get() try_get() Use Create a semaphore with specified number of keys. Intel Confidential 158 .

get(1). $time). $display("initial1 returns 1 key at %0t". #5 spr. $display(" inital2 takes 2 keys at %0t". $display(" inital2 returns 1 key at %0t".$time). semaphore spr = new(2).$time).put(1). end endmodule: semaphore_test 159 .get(1). #1 spr. $display("initial1 takes 1 key at %0t".Semaphore example module semaphore_test ().get(2). initial begin:init1 #1 spr.put(1). end Output: # initial1 takes 1 key at 1 # initial1 returns 1 key at 7 # inital2 takes 2 keys at 7 # inital2 returns 1 key at 12 # initial1 takes 1 key at 12 # q -f Intel Confidential initial begin:init2 #5 spr. #6 spr. $time). $display("initial1 takes 1 key at %0t".$time).

Process 1 Process 2 Intel Confidential 160 .Mailboxes Mailbox is a communication mechanism that allows messages to be exchanged between different processes.

put() will never block.Mailbox Types Mailboxes can be classified as: Unbounded mailboxes No restrictions placed on size of mailbox. Bounded mailboxes Number of entries is determined when the mailbox is created. put() will be blocked if the mailbox is full. Bound value should be positive. // mailbox of depth = 5 Intel Confidential 161 . Ex: mailbox m = new (). Ex: mailbox m = new (5).

Try to place a message in mailbox without blocking. This does not guarantee order of arrival but that the arrival order shall be preserved. Try to retrieve a message from the mailbox without blocking. Place a message in a mailbox. Copies a message from mailbox without actually removing it.Mailbox Methods Messages are placed in strict FIFO order. Intel Confidential Use peek() 162 . Mailboxes provides following built-in methods: Method new() put() get() try_get()/ try_peek() try_put() Create a new mailbox. Useful only for bounded mailboxes. Retrieve a message from mailbox.

Mailbox example
module mailbox_ex (); class Xaction; rand bit [2:0] addr; endclass typedef mailbox #(Xaction) mbx; mbx mb = new (); initial begin: t Xaction xaction; int mb_size; for (int i=0; i<5; i++) begin xaction = new; xaction.addr = 3’b111; $display("BEFORE:: Addr = %h", xaction.addr); mb.put(xaction); end 163 mb_size = mb.num(); for (int i=0; i<mb_size; i++) begin: dis_l Xaction d_x; mb.get(d_x); $display("Addr = %h", d_x.addr); end: dis_l end: t endmodule: mailbox_ex

Intel Confidential

BACKUP

Intel Confidential

164

foreach (Not in ModelSim 6.1) {BACKUP}
Implicit loop variable(s), multiple dimensions, any array type
int arr_x[]; typedef int arr_joe[7:0][3:8] arr_joe arr_y[$]; int arr_z[0:3*width][8*num-1:0]; initial begin arr_x = foreach foreach foreach end

new[10]; (arr_x[i]) statement (arr_y[m,n,p]) statement (arr_z[i,j]) statement

Intel Confidential

165

order of evaluation is important Both modifiers require that if no fall-through else/default statement is available.no more than one branch may be true for each evaluation. an error is generated Intel Confidential 166 . simulator errors if this happens ‘priority’ . and no branch is true.‘unique’ and ‘priority’ modifiers {BACKUP} Modifiers on if and case/casex/casez selection expressions ‘unique’ .

Lab 5: CRC} Intel Confidential 167 .

Intel Confidential 168 . The operators << (left shift) and ^ (xor) will be needed. Process the bitstream given in the lab file and report the CRC.Lab 5: CRC (cont) {BACKUP} Implement the CRC algorithm shown in the previous foil.

just using state variables (!global_reset_state && cmd) -> (cmd_type != IDLE) Can even test obj pointers for null (a != null && a.x) Intel Confidential 169 . but remove the constraint from consideration of the constraint solver Use the same implication operator.Constraint Guards {BACKUP} Guards prevent the application of constraints. similar to implication.x > 10) -> (y < 100 && y > a.

randomize() cannot include variables outside scope of class Intel Confidential 170 .std::randomize() {BACKUP} Procedural invocation of constraint solver Any variables can be the random variables “with” block for constraints Normal .

Disabling rand/constraints {BACKUP} rand_mode – method to toggle the “rand” attribute off on a class variable constraint_mode – method to toggle the application of a named constraint Intel Confidential 171 .

Random Stability {BACKUP} SV has thread random stability Intel Confidential 172 .

Sign up to vote on this title
UsefulNot useful