Documente Academic
Documente Profesional
Documente Cultură
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.
Scope Of Course
Introduction to SystemVerilog for verification Hands-on lab assignments Students will not be SystemVerilog experts at the end of this class. Class is an introduction only. Advanced classes go into more details.
Next Classes: Functional Coverage/Temporal language/Checkers How to write a SV Test How to write an SV BFM
Length: 2 days
Intel Confidential
Typographic Conventions
Regular Text Courier Bold Course Content Code examples, command line keyboard input Screen output Placeholders for data user should input
Intel Confidential
What is SystemVerilog
SystemVerilog is an IEEE extension to the Verilog language. SystemVerilog adds testbench features such as classes, constraints, and temporal expressions to Verilog.
Intel Confidential
AVC Wiki
http://wwwfmec.fm.intel.com/twiki/bin/view/Chipset/SystemVerilog
http://carmel.fm.intel.com/sites/CPDCDTG/DATE/FEDAO/SystemVerilog%20Deployment%20Doc %20Lib/Forms/AllItems.aspx
Additional Information
www.accellera.org
Intel Confidential
Using SystemVerilog
To setup your environment to use SystemVerilog, type the following at the unix prompt:
Intel Confidential
Hello World
module helloWorld(); initial begin: hello $display("Hello World"); end: hello endmodule: helloWorld
Intel Confidential
Compiling SystemVerilog
To compile your program, type the following:
% vlog hello.sv
Note: If you do not name your file ending in .sv, you must use the sv option to vlog. To run your program, use the following command:
% vsim -c -do "run -all;q -f" helloWorld
Intel Confidential
10
Intel Confidential
11
Intel Confidential
12
Intel Confidential
14
Signed/Unsigned
byte, shortint, int, integer and longint defaults to signed
Use unsigned to represent unsigned integer value
Example: int unsigned ui;
bit, reg and logic defaults to unsigned To create vectors, use the following syntax:
logic [1:0] L; // Creates 2 bit logic // vector
Intel Confidential
15
Strings
string dynamic allocated array of bytes SV provides methods for working with strings Str1 == Str2 Str1 != Str2 <, <=, >, >= {Str1, Str2, 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, atohex, atoct, atobin atoreal itoa hextoa octtoa bintoa realtoa
Intel Confidential
17
Literal Values
Integer Literal Same as verilog
value unsized decimal value sizebase value sized integer in a specific radix Ex: 4b0101; 4hC; 32hDEAD_BEEF; 2b1Z
Real Literal
value.value Ex: 2.4 Base Exponent ( E/e)
Logic Value
0, 1, [z|Z], [x|X]
18
Intel Confidential
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
Operators
Logic Operators
& + | ~ % ^ / ~& * ~| ~^ << >>
Arithmetic Operators
** <<< >>>
Assignment Operators
= += -= *= /= %= &= |= ^= <<= >>= <<<= >>>=
Intel Confidential
20
Operators
Auto-increment (++) Auto-decrement(--)
Example: a = 1; a++; a now contains 2.
Comparison Operators
== != === !== =?= !?= > < <= >= Example: a = 1'bZ; b = 1'bZ; if (a != b) $display(Z != Z); if (a === b) $display(Z === Z);
Intel Confidential
21
Concatenation
The { } operator is used for concatenation. Example:
s = {Hello, , World}; v = {32b1, 32b10}; // v = 64b vector
Sizes of assignment have to match. If LHS is smaller then assignment gets truncated.
Intel Confidential
22
Lab 3: Operators
Write a SystemVerilog module to calculate the following, and print the result as an integer to the screen:
(1101001 XOR 11111001) 5 Ignore remainder.
Intel Confidential
23
SystemVerilog additions
Verilog includes: if-(else-(if)), case, forever, repeat, while, for, ?: (ternary) SystemVerilog:
Enhances for Adds do..while, foreach
Intel Confidential
25
if
Verilog if expressions Then branch taken for any nonzero known value of expr (no x or z), equivalent to expr != 0 Chain if statements:
if (expr) begin end else if (expr) begin end else begin end
Intel Confidential
26
?:
Operator, but conditional
expr ? then_val : else_val
Some call this the ternary operator, in the same vein as unary and binary, with 3 operands. Ex: var_m = (x == 1) ? a : b;
Intel Confidential
27
case
4-value exact matching, runtime evaluation, no fallthrough, bit length of all expressions padded to same length
case (expr) item: begin statement end item2, item3, item4: begin statement end default: statement endcase
Intel Confidential
28
casez, 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 (8bx100z011 ^ reg_a) 8b1x1001?1: $display(x); 8b01z10zx1: $display(y); 8b11z01011: $display(z); endcase
Intel Confidential
29
forever
Continuous execution, without end, of body statement(s) Used with timing controls Usually last statement in some block initial : clock_drive begin clk = 1b0; forever #10 clk = ~clk; end : clock_drive
Intel Confidential
30
repeat
Repeat a block x times, no conditional test
repeat (expr) statement
31
while
Executes statement as long as expr evaluates to true
Intel Confidential
for
C inspired for loop
for (initial_assignment; condition; step_assignment) statement
Equivalent to
begin initial_assignment; while (condition) begin statement; step_assignment; end end
Intel Confidential
33
Enhanced for
SystemVerilog adds:
Loop variable declaration Multiple statements in init and step blocks (comma separated) ++ and -- operators (Mentioned in operator section)
for (int i; i < arr.size(); j+=2, i++) begin arr[i] += 200; arrb[i]--; end
Intel Confidential
34
do..while
do statement while (expr); Whats the difference?
x = 0; 1) while (x) begin $display(%d, x); x--; end 2) do begin $display(%d, x); x--; end while (x);
Intel Confidential
35
Intel Confidential
36
Enumeration
Syntax: enum [enum_base_type] { enum_name_declaration {,enum_name_declaration} } enum_base_type: default is int Enumeration is a useful way of defining abstract variables.
NOTE:
Define an enumeration with enum enum {red, green, yellow} traf_lite1, traf_lite2; Values can be cast to integer types and auto-incremented enum { a=5, b, c} vars; // b=6, c=7
Default assigned values start at zero 0 1 2 enum {red, green, yellow} lite;
A sized constant can be used to set size of the type enum bit [3:0] { bronze=4h3, silver, gold} medal; // All medal members are 4-bits Define a new type typedef enum {NO, YES} bool; // bool is NOT a SystemVerilog type bool myvar; // but it just became one
myvar will now be checked for valid values in all assignments, arguments and relational operators
8-39 SV for Verification Using Questa: Functional Coverage Copyright 2005 Mentor Graphics Corporation
Enumeration example
Modelsim now allows viewing of enum types in waveforms similar to VHDL enum types. To use enumerated types in numerical expressions the language provides the following functions: prev(), next(), first(), last(), num() and name().
Example
typedef enum {red, green, blue, yellow, white, black} Colors; Colors col_ps; Colors col_ns; always @(col_ps) col_ns = col_ps.next(); always @(posedge clk) col_ps <= col_ns;
Intel Confidential
40
Casting
Casting
A data type can be changed by using a cast () operation. Syntax: <type>(<value/expression>) Examples:
int(2.0 * 3.0)// real to int casting 7(x-2)//number of bits to change size. signed(m)//changes m to signed inteltype(2+3)//casting to a user defined type [inteltype].
Intel Confidential
42
Arrays
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 [3:0] m; m = 4b1100;
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.
Ex: logic m [5:0]; // each element is only 1-bit deep Ex: logic [3:0] m [5:0]
Intel Confidential
44
For more control, consider the dimensions of the array and use { } to match those dimensions exactly.
int k [1:3][1:4] = '{'{1,2,3,4},'{5,6,7,8},'{9,10,11,12}};
// 3 groups of 4
// 2 groups of 3
Dynamic Arrays
Syntax: data_type array_name[] ;
Examples:
bit [3:0] nibble[ ]; integer mem[ ]; int data[ ]; data = new[256]; int addr = new[100]; addr = new[200](addr);
// 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
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]; addr.delete();
Cannot delete selected elements
Intel Confidential
48
SV has a built-in list mechanism which is ideal for queues, stacks, etc. A list is basically a variable size array of any SV data type. int q1[$]; int n, item; q1 = { n, q1 }; q1 = { q1, n }; item = q1[0]; item = q1[$]; n = q1.size; q1 = q1[1:$]; q1 = q1[0:$-1];
// $ 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)
Queue Methods
size() insert() Returns the number of items in the queue. If the queue is empty, it returns 0. Inserts the given item at the specified index position. Q.insert (i, e) => delete() Q = {Q[0:i-1], e, Q[i,$]} Prototype: function int size(); Prototype: function void insert (int index, queue_type item); Prototype: function void delete (int index); Prototype: function queue_type pop_front(); Prototype: function queue_type pop_back(); Prototype: function void push_front (queue_type item); Prototype: function void push_back (queue_type item);
Deletes the item at the specified index position. Q.delete (i) => Q = {Q[0:i-1], Q[i+1,$]}
pop_front()
Removes and returns the first element of the queue. e = Q.pop_front () => e = Q[0]; Q = Q[1,$]
pop_back()
Removes and returns the last element of the queue. e = Q.pop_back () => e = Q[$]; Q = Q[0,$-1]
push_front()
Inserts the given element at the front of the queue. Q.push_front (e) => Q = {e, Q}
push_back()
Inserts the given element at the end of the queue. Q.push_back (e) => Q = {Q, e}
Queue Example
module queues (); int q [$]; // declare the q initial begin: store_disp Push elements into the queue q.push_back(1); q.push_back(0); Display its contents $display("Size of queue = %0d", q.size()); Delete the element of queue at index 1 q.delete(1); Push to front of the queue q.push_front (0); Display all the contents in the queue for (int i = 0; i < q.size(); i++) $display("q[%0d] = %0d", i, q[i]); end: store_disp
//
// // // //
endmodule: queues
Intel Confidential
51
Lab 6: Queues
Write a SystemVerilog program with specification as defined in lab6.sv The output will look as follows: # Loading work.lab6 # run all # Size of queue = 3 # q[0] = 0 # q[1] = 1 # q[2] = 3 # q -f
Intel Confidential
52
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]; In other words value_type array_name [key_type]; It implements a lookup table of the elements of its declared type. Data type used as an index serves as lookup key and imposes an order. Associative array do not have their storage allocated until it is used.
Intel Confidential
53
Index Types
String Index Types
Ex: int a [string]; a[joe] = 21;
Intel Confidential
54
Use
Returns number of entries Index for delete optional. When specified used to delete given index else whole array. 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. It returns 0 if the array is empty, and 1 otherwise. finds the entry whose index is greater/smaller than the given index.
Intel Confidential
55
2.
3. 4.
Display the size of the hash using $display statement Check if name Jane exists in the associative array and if it does
Intel Confidential
57
Procedural Blocks
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. Level-sensitive signal detection If the signal is already true, execution continues without stopping
Intel Confidential
59
Initial Block
An initial block starts at time 0, executes exactly once during a simulation, and then does not execute again. If there are multiple initial blocks, each block starts to execute concurrently at time 0. Each block finishes execution independently of other blocks. Multiple behavioral statements must be grouped, typically using begin and end.
Example
module stimulus; reg a,b; initial begin #5 a = 1b1; #25 b = 1b0; end endmodule
Intel Confidential
60
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. This statement is used to model a block of activity that is repeated continuously.
Intel Confidential
Example
module clock_gen; bit clock; initial begin clock = 1b0; forever #10 clock = ~clock; end always @(posedge clk) begin <statements>; end endmodule
61
Final Blocks
The final block is like an initial block, defining a procedural block of statements, 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.
Example final begin $display("Number of cycles executed %d",$time/period); $display("Final PC = %h",PC); end
Intel Confidential
62
Intel Confidential
63
Types of Assignment
Blocking Nonblocking
Blocking Assignment
The simulator completes a blocking assignment (=) in one pass [execution and assignment]. 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.
Intel Confidential
Example
initial begin a = 30; #10; a = 5; c = #10 a; b = 2; end // at time 0 a = 30 //at time 10 a = 5, b = x, c = x // at time 20 a = 5, b = x, c = 5 // at time 20 a = 5, b = 2, c = 5
65
Nonblocking Assignment
The simulator completes a nonblocking assignment (<=) in two passes.
Right-hand side of the assignment is sampled immediately. Assignment to the lefthand side is postponed until other evaluations in a given simulation time step are complete.
Example
initial begin a = 30; #10; a <= 5; c <= #10 a; b <= 2; end // at time 0 a = 30 //at time 10 a = 5, b = 2, c = x // at time 20 a = 5, b = 2, c = 30
66
Intel Confidential
Tasks
SystemVerilog makes a number of extensions to basic Verilog syntax.
Implied beginend
task automatic my_task( input int local_a, int local_b); if (local_a == local_b) Arguments can be ANY begin SV type, even structs, etc. my_task(local_a-1,local_b+1); return; // end this copy of task end global_a = local_a; return keyword is supported and global_b = 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
70
Functions
automatic functions allocate memory dynamically at call time (full recursion). Default port direction is input (also supports output) ANSI style portlists Implied beginend
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.
End
Copyright 2005 Mentor Graphics Corporation
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
Intel Confidential
73
Intel Confidential
74
Example
task read (int j =0, int k,int data = 1); endtask // task can be called using // following default arguments read (, 5); // equivalent: read (0, 5, 1) read (2, 5); // equivalent: read (2, 5, 1) read (); // error since k has no default // value
Intel Confidential
75
Lab 9a
Create a SystemVerilog module as described below:
1. 2. 3.
4. 5.
Define a queue 'q' of string type. Define a named initial block "store_info" Store the following values into the queue 1. index =0, str = "Intel Chandler" 2. index =1, str = "Intel Folsom" Display the size of the queue. Define a function named "change_str" which does the following: 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. 3. returns the value of 1 indicating success.
Intel Confidential
76
Lab 9b
6.
7.
q[%0d] = %s" Notes: "change_str" and show" are called from named initial block "store_info".
# # # # # #
Takes queue and return value from "change_str" as inputs The default inital value [task input argument: ret_value] shall be set to 0. When the return value from "change_str" function is 1, prints the elements stored in the queue using the following format:
Output:
Loading work.lab9 run all Size of storage q = 2 q[0] = Intel Chandler q[1] = Intel Ireland q -f
Intel Confidential
77
Hierarchy
Who comes first
Modules
The basic hardware unit in Verilog. Hierarchy of design Ports represent communication
Inout Inputs Module Outputs
Intel Confidential
79
Ports
Connections
Direction input, output, inout Type wire, bit, logic, user-defined, etc.
Examples:
input bit[3:0] x, y, z; input bit w[3:0]; output logic q; inout logic s; input int x; output reg r;
Intel Confidential
80
Module syntax
module x (port_list); module_body endmodule : x Instantiation x x1 (port_binding_list);
Example
module cpu (inout logic[63:0] data, output logic[63:0] addr, output logic w_or_rb ); initial begin : place_holder $display(A NOTHING CPU); end : place_holder endmodule : cpu // Error prone cpu cpu_inst1(addr, data, w_or_rb); // Better cpu cpu_inst2(.addr(addr), .data(data), .w_or_rb(w_or_rb) ); // Newer cpu cpu_inst3( .* );
Intel Confidential
81
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]^ 8hAE; 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
adr
MEM
interface
IO Abstraction
source
reg a; a = 0;
sink
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.a = 0;
interface intf
sink
if ( intf.a == 1)
reg a;
source
intf.wrt_a(0);
interface intf
sink
if (intf.rd_a() == 1)
reg a;
Enhanced interface with methods source/sink only call methods source/sink dont see low-level details like variables/structure, etc. Easy to swap interface abstractions without any effect on source/sink
Copyright 2005 Mentor Graphics Corporation
Interface Characteristics
Interfaces bring abstraction-level enhancements to ports, not just internals. An interface may contain any legal SystemVerilog code except module definitions and/or instances. This includes tasks, functions, initial/always blocks, parameters, etc. Bus timing, pipelining, etc. may be captured in an interface rather than the connecting modules. Interfaces are defined once and used widely, so it simplifies design. e.g. Changing a bus spec (add a new signal?) means editing the interface only. Interfaces are synthesizable.
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
modport
Different users of interface need different views
Master/Slave
Example
interface i2; wire a, b, c, d; modport master (input a, b, output c, d); modport slave (output a, b, input c, d); endinterface : i2 module m (i2.master i); endmodule: m module s (i2.slave i); endmodule: s module top(); i2 i(); m u1(.i(i.master)); s u2(.i(i.slave)); endmodule: top
Intel Confidential
88
Lab 10
Create modules moda and modb. moda has an input named a, and an output named b modb has an input named b, and an output named a Use an interface to connect
Intel Confidential
89
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
clocking bus @(posedge clock1); default input #10ns output #2ns; input data, ready, enable=top.mem1.enable; output negedge ack; input #1 addr; endclocking
Intel Confidential
91
Program Blocks
A program block is similar to a module. It is used for testbench code.
program helloWorld(); initial begin: hello $display("Hello World"); end initial begin: there $display(Hello There); end endprogram: helloWorld
Intel Confidential
92
Program Blocks
Programs can be instantiated inside modules, but not the other way around. Program blocks may contain one or more initial blocks, but may not contain always, UDPs, modules, interfaces, or other programs. Programs may be explicitly exited using the $exit task. When all program blocks complete the simulation ends.
Intel Confidential
93
Day Two
Classes
SystemVerilog and Object Oriented Programming Testbench Only
Objects/Classes have:
Data Operations/Methods
Example: A class might be Automobile. Instances of the Automobile class might be Joes car, Bobs car, Sallys truck, etc.
96
Classes
Inheritance: (is-a relationship)
Allows users to extend existing classes, making minor modifications. Extending the Automobile class example, users might create subclasses for sedan, truck, van, etc. The van class might also have a minivan subclass. Etc. In these cases, the subclass IS-A superclass. i.e. a sedan is a Automobile. When using inheritance, the sub-class inherits all the parents public/protected data properties and methods. It is allowed to override them, or use them as-is.
Composition is used for the case where one object HAS-A instance of another class. For example, an Automobile class might have 4 instances of a wheel class. In this case, a wheel is not an Automobile, so inheritance should not be used.
Intel Confidential
97
Classes
Polymorphism:
Most common definition of polymorphism is the ability of the language to process objects differently depending on their data type or class. SystemVerilog can only process objects differently depending on their class.
Intel Confidential
98
Class Format
class classname [extends superclass]; property declarations; constructor; methods; endclass: myPacket
Intel Confidential
99
Example Class
class myPacket extends BasePacket; // inheritance byte data[$]; bit [3:0] command; function new(); command = IDLE; data = {1,2,3,4}; endfunction: new virtual task myTask(input byte a, output byte b); #10; b = a + 5; endtask: myTask; virtual function integer myFunc(int b); return(b 3); endfunction: myFunc endclass: myPacket
Intel Confidential
100
Intel Confidential
101
Constructors
Example constructor
function new(); command = IDLE; data = {1,2,3,4}; endfunction: new // Creating an instance invokes the constructor: myInstance = new;
102
this
The special variable this is a predefined object handle for the current object instance. It is optional, since the current instance is assumed if no variable is specified.
class myPacket extends BasePacket; int x, y, z; virtual function integer myFunc(); x = y + z; // Equivalent: this.x = this.y + this.z; myOtherMethod(); // Equivalent to: this.myOtherMethod(); endfunction: myFunc endclass: myPacket
Intel Confidential
103
Static Properties
Static properties/data members are static to all instances of the class. This means that all instances share the same value of this variable. If one instance changes the value, it changes the value for all instances.
class StaticExample; static int staticProperty = 0; virtual function void showStaticProperty(); $display(Current value: %d,staticProperty); endfunction: showStaticProperty virtual function void setStaticProperty(int val); staticProperty = val; endfunction: setStaticProperty endclass: StaticExample
Intel Confidential
104
Static Methods
Static methods do not require an instance of the class to operate on. Static methods may only modify static properties. To invoke a static method, use Classname::methodName
class StaticExample; static int staticProperty = 0; static function void staticMethod(); endfunction: staticMethod endclass: StaticExample StaticExample::staticMethod();
Intel Confidential
105
Polymorphism
Instances of subclasses may be assigned to variables declared of the superclass type. This is useful for cases where the general algorithm is the same for all the subclasses, but only a few details need to change. If the subclass overrides a method specified in the superclass, the method defined in the class of the object instance is called.
class BaseClass; virtual function in myFunc(int b); return(b + 10); endfunction myFunc endclass: BaseClass class myFirstClass extends BaseClass; virtual function int myFunc(int b); return(b 3); endfunction: myFunc endclass: myFirstClass class mySecondClass extends BaseClass; virtual function int myFunc(int b); return(b + 3); endfunction: myFunc endclass: mySecondClass BaseClass bc; // Returns an instance myFirstClass bc = getFirstClassInstance(); $display(What do I print? %d ,bc.myFunc(6)); // Returns an instance mySecondClass bc = getSecondClassInstance(); $display(What do I print? %d ,bc.myFunc(6));
106
Intel Confidential
To make data members visible only to the class, or any subclasses, use the protected keyword.
class myPacket extends BasePacket; protected int x;
Intel Confidential
107
Intel Confidential
108
Abstract Classes
The virtual keyword may be used on a class to make the class abstract. An abstract class may not be instantiated. Users must subclass the abstract class to create instances of the class.
virtual class BasePacket;
Intel Confidential
109
110
Methods:
// Sets data to value passed and // length to the size of queue passed. setData(byte d[$]);
// Returns formatted representation of // xaction. Format should be: // Len=X, Data=0xXXXXXXXX string toString();
Hint: $sformat(str,"Len=%d,
Xaction x;
DATA=0x%h",length,data);
Intel Confidential
111
Add a task to the class that waits for the number of time steps specified in iws: Override the toString() method, add printing the iws value. Be sure to use super.toString, and not reimplement the toString of the parent class:
// Len=X, Data=0xXXXXXXXX, IWS=X
s = new; s.iws = 10; $display(current time = %t,$time); s.stall(); $display(current time = %t,$time); x = s; x.setData({5,6,7,8}); $display(%s,x.toString());
Intel Confidential
112
Virtual Interfaces
Classes cannot have modules or interfaces, need a specialized mechanism Virtual interfaces provide a mechanism for separating test programs/BFM models from the actual signals. 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. Syntax: virtual <interface name> <variable name>;
Intel Confidential
113
114
Random Constraints
How to decide how random to be
Intel Confidential
116
Simplest randomness
$urandom system tasks $urandom() is SV, thread stable, deterministic $urandom returns unsigned 32-bit integers Procedural call can be inserted wherever needed
Intel Confidential
117
118
Intel Confidential
119
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; } c_eq_10 {c == 10;} b_in_range { b >= 2 && b <= 8; } all_gt_0 {a > 0; b > 0; c > 0;}
120
Constraints
Restrict range of possible values Can use state variables to restrict range of random variables Example:
int x[7] = {3,5,6,27,10,42,1}; int z = hff, w = 10; constraint c_within_set_of_x { c inside x; } constraint b_between_w_z { b <= z && b >= w; }
Intel Confidential
121
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.randomize() begin end -solvefaildebug
Intel Confidential
y; } z; } x; } == 0 ) // Solver error
Constraint operators
Any Verilog boolean expression
i.e. x < y+b-c*10>>20
Other constraint operations set membership implication iterative constraint variable ordering functions
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
Loop/array constraints
Constrain every element of an array in some fashion, including reference to other elements of array
constraint foreach A[i] } constraint foreach (k < } c1 { ( A[i] ) inside {2, 4, 6, 8, 10}; c2 { ( A[k] ) A.size-1) -> A[k+1] > A[k];
Intel Confidential
125
Arguments to .randomize()
Normal form of .randomize()
No arguments, 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 with {}
Specify inline constraints that are added to constraint set to solve
z > buzz; };
Intel Confidential
127
Distribution Constraints
Operators: := :/ dist Example: constraint twsConstraint { tws dist { [0:2] :/ 10, [3:9] :/ 1, [10:50] :/ 9 }; } constraint distConstraint { cmd dist { mem_write := 10, mem_read := 5, lrw := 1, lrrww := 1, io_read := 1, io_write := 1, idle := 1 }; }
Intel Confidential
128
module test_rand; typedef enum {SM, MED, LRG} trans_len; class transaction { rand bit [19:0] addr; rand trans_len len; rand bit [3:0] byte_len; rand bit wr_or_rd_b; constraint c1 { wr_or_rd_b -> len != LRG; } constraint c2 { (len == SM) -> (byte_len <= 4); } constraint c3 { (len == MED) -> (byte_len > 4 && byte_len <= 8);} constraint c4 { (len == LRG) -> (byte_len > 8); } // Mem above 16-bit is write-only IO devices constraint c5 { (!wr_or_rd_b) -> (addr[19:16] != 0); } virtual function string toString() return sformat(%5H: %s %d bytes, addr, (wr_or_rd_b ? WR : RD), byte_len); endfunction : toString endclass : transaction <CONTINUED>
Intel Confidential
129
Intel Confidential
130
Intel Confidential
131
Packages
A mechanism for sharing parameters, data, types, tasks, functions, classes, sequences, and properties among modules, interfaces and programs
Intel Confidential
132
import p::c if ( ! c )
133
Package Example
keyword
package endpackage
Example: package p; class Data; int a; int b; endclass typedef enum {FALSE, TRUE} BOOL; endpackage : p
module top; import p::*; BOOL b = TRUE; endmodule OR module top; p::BOOL b = p::TRUE; endmodule
Intel Confidential
134
Intel Confidential
135
System Tasks
Display
$display printf-ish, with \n implied
$display (format_string, arguments);
$write printf-ish ($display w/out newline) $sformat print formatted string (ala sprintf) $monitor Implicit task to call $display any time arguments change, only one $monitor active
Intel Confidential
137
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
Simulation Control
$finish end simulation (quit simulator), final blocks $stop halt simulation $exit quit execution of program block (SV-only)
Example
initial #10000 $finish(); initial @(posedge all_bfms_done) $finish();
Intel Confidential
139
File I/O
integer char int integer integer integer fd c code code code code = = = = = = $fopen(string filename, string mode) $fgetc(int fd); $ungetc(char c, int fd); $fgets(string str, int fd); $fscanf(int fd, FORMAT, args); $sscanf(string str, FORMAT, args);
Example
string buf_s; in_fd = $fopen(input_file, r); out_fd = $fopen(output_file, w); chars_read = $fgets(buf_s, in_fd); if (chars_read == 0) begin $display(End of file); $finish(); end if (2==$sscanf(buf_s, "%x %x", hexStartAddr, hexEndAddr) ) begin $display(Address Range: %8x -> %8x, hexStartAddr, hexEndAddr); 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
Named blocks
Blocks can be provided names. By providing blocks with names provides the following advantages:
Declaration of local variables. Named blocks are part of the design hierarchy. Local variables declared can be accessed through hierarchical referencing. Example
always @(CK or D) begin : latch_counter int count; if (CK) count = count + 1; begin O = D ; end end : latch_counter
Intel Confidential
143
Threads
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, 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; #5 a = 2; #5 a = 3; end
145
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. A return statement in the context of fork..join is illegal.
Example
fork begin $display( "First Block\n" ); # 20ns; end begin $display( "Second Block\n" ); @eventA; end join
Intel Confidential
146
Dynamic Processes
Inspired by the need for software verification environments to dynamically start and stop threads, SystemVerilog defines 2 new special cases of forkjoin with associated keywords join_any & join_none
join_any join_none
fork other blocks continue as dynamic threads join_any // any block finished
NOTE Child processes spawned by a forkjoin_none do not start to execute until the parent process hits a blocking statement
Copyright 2005 Mentor Graphics Corporation
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(); task2(); join_any fork task3(); task4(); join_none wait fork; end
Q 6.1
The disable fork statement terminates all active child processes of the process where it is called. Termination is recursive, in other words it terminates child processes, grandchild processes, etc.
task run_tests; fork simul_test1; simul_test2; join endtask task test_with_timeout; fork run_tests(); timeout( 1000 ); join_any disable fork; endtask
// 2 child tasks spawned in parallel, first to finish triggers join_any // Kills the slower task (including any grandchild processes and so on)
Intel Confidential
150
Intel Confidential
151
Intel Confidential
Example
bit success; wait_order (a, b, c) success = 1; else success = 0; // event must occur in the // following order // ->a ->b ->c if not it fails.
153
Intel Confidential
154
Intel Confidential
155
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
Semaphore Methods
Semaphore provides following built-in methods:
Method
new() put() get() try_get()
Use
Create a semaphore with specified number of keys. Return one or more keys back. Obtain one or more keys. Try to get one or more keys without blocking.
Intel Confidential
158
Semaphore example
module semaphore_test (); semaphore spr = new(2); initial begin:init1 #1 spr.get(1); $display("initial1 takes 1 key at %0t", $time); #6 spr.put(1); $display("initial1 returns 1 key at %0t",$time); #1 spr.get(1); $display("initial1 takes 1 key at %0t", $time); 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.get(2); $display(" inital2 takes 2 keys at %0t",$time); #5 spr.put(1); $display(" inital2 returns 1 key at %0t",$time); end endmodule: semaphore_test
159
Mailboxes
Mailbox is a communication mechanism that allows messages to be exchanged between different processes.
Process 1
Process 2
Intel Confidential
160
Mailbox Types
Mailboxes can be classified as:
Unbounded mailboxes
No restrictions placed on size of mailbox. put() will never block. Ex: mailbox m = new ();
Bounded mailboxes
Number of entries is determined when the mailbox is created. Bound value should be positive. put() will be blocked if the mailbox is full. Ex: mailbox m = new (5); // mailbox of depth = 5
Intel Confidential
161
Mailbox Methods
Messages are placed in strict FIFO order. This does not guarantee order of arrival but that the arrival order shall be preserved. Mailboxes provides following built-in methods:
Method
new() put() get() try_get()/ try_peek() try_put() Create a new mailbox. Place a message in a mailbox. Retrieve a message from mailbox. Try to retrieve a message from the mailbox without blocking. Try to place a message in mailbox without blocking. Useful only for bounded mailboxes. Copies a message from mailbox without actually removing it.
Intel Confidential
Use
peek()
162
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 = 3b111; $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
Intel Confidential
165
Modifiers on if and case/casex/casez selection expressions unique - no more than one branch may be true for each evaluation, simulator errors if this happens priority - order of evaluation is important Both modifiers require that if no fall-through else/default statement is available, and no branch is true, an error is generated
Intel Confidential
166
Lab 5: CRC}
Intel Confidential
167
Intel Confidential
168
Intel Confidential
169
std::randomize() {BACKUP}
Procedural invocation of constraint solver Any variables can be the random variables with block for constraints Normal .randomize() cannot include variables outside scope of class
Intel Confidential
170
Intel Confidential
171
Intel Confidential
172