IntroToSV_orgi
-
Upload
suneel-kumar -
Category
Documents
-
view
61 -
download
3
Transcript of IntroToSV_orgi
Intro To SystemVerilog
SystemVerilog for Verification
Day One
3Intel Confidential
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.
4Intel Confidential
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
5Intel Confidential
Typographic Conventions
Regular Text
Courier Bold
Courier Regular
Italic
Course Content
Code examples, command line keyboard input
Screen output
Placeholders for data user should input
6Intel 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.
7Intel Confidential
Getting More Information
� SystemVerilog LRMhttp://www.eda.org/sv/SystemVerilog_3.1a.pdf
� AVC Wikihttp://www-
fmec.fm.intel.com/twiki/bin/view/Chipset/SystemVerilog
� Comprehensive information on SV:http://carmel.fm.intel.com/sites/CPD-CDTG/DATE/FEDAO/SystemVerilog%20Deployment%20Doc%20Lib/Forms/AllItems.aspx
� Additional Informationwww.accellera.org
8Intel Confidential
Using SystemVerilog
To setup your environment to use SystemVerilog, type the following at the unix prompt:
% source <local site specific setup script>
Next, create a training directory, and create a work library:
% mkdir svtraining; cd svtraining% vlib work% vmap work work
9Intel Confidential
Hello World
module helloWorld();
initial
begin: hello
$display("Hello World");
end: hello
endmodule: helloWorld
10Intel 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
11Intel Confidential
Commenting Your Code
Like C++, SystemVerilog supports two types of comments
/* Block comments that can span
* multiple lines
*/
// And single line comments
$display(“hello”); // This is a comment
12Intel Confidential
Lab 1: Hello World
Create a module that prints “Hello World” using the $display command.
Basic Data Types
14Intel Confidential
Integer Data Type
4-state, 64 bit unsignedtime4-state, 32 bit signedinteger4-state user-defined sizereg4-state (1,0,x,z) user-deflogic2-state, user-defined vector sizebit2-state, 8 bit signedbyte2-state, 64 bit signedlongint2-state, 32 bit signedint2-state (1, 0), 16 bit signedshortint
15Intel Confidential
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
16Intel Confidential
Strings
� string – dynamic allocated array of bytes� SV provides methods for working with strings
indexing – return 0 if out of range
Str1[index]
Concatenation{Str1, Str2, … Strn}
Comparison<, <=, >, >=
InequalityStr1 != Str2
EqualityStr1 == Str2
17Intel Confidential
String Methods
� len
� putc
� getc
� toupper
� tolower
� compare
� icompare
� substr
� atoi, atohex, atoct, atobin
� atoreal
� itoa
� hextoa
� octtoa
� bintoa
� realtoa
18Intel Confidential
Literal Values
� Integer Literal – Same as verilog� value – unsized decimal value� size’base value – sized integer in a specific radix
� Ex: 4’b0101; 4’hC; 32’hDEAD_BEEF; 2’b1Z
� Real Literal� value.value
� Ex: 2.4� Base Exponent ( E/e)
� Logic Value� 0, 1, [z|Z], [x|X]
19Intel Confidential
Lab 2: Data TypesWrite a top level module that displays the following output.Use of the following data types:1. int both signed and unsigned2. logic3. string
Hint:int i, h; $display(“%d %h”, i, h);
string str; $sformat(str, “%b”, l)$display(“Logic value in upper case %s”,str.toupper());
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“
20Intel Confidential
Operators
Logic Operators& | ~ ^ ~& ~| ~^ << >>
Arithmetic Operators+ - % / * ** <<< >>>
Assignment Operators= += -= *= /= %= &= |= ^= <<= >>= <<<= >>>=
Example:a += 3;Equivalent to:a = a + 3;
21Intel Confidential
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”);
22Intel Confidential
Concatenation
The { } operator is used for concatenation. Example:s = {“Hello”, “ “, “World”};v = {32’b1, 32’b10}; // v = 64b vector
Can also be used on left hand side:{a, b, c} = 3’b111;
Sizes of assignment have to match. If LHS is smaller then assignment gets
truncated.
23Intel Confidential
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.
Flow Control Constructs
How to go with the flow
25Intel Confidential
SystemVerilog additions
� Verilog includes: if-(else-(if)), case, forever, repeat, while, for, ?: (ternary)
� SystemVerilog:� Enhances for� Adds do..while, foreach
26Intel Confidential
if
Verilog ‘if’ expressionsThen 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
elsebegin…end
27Intel Confidential
?:
Operator, but conditionalexpr ? 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;
28Intel Confidential
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
enddefault: statement
endcase
29Intel Confidential
casez, casex
Handle wild cards with either casez or casexcasez: ‘z’ bit in either item or expression will be treated
as a match for that bitcasex: ‘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
30Intel Confidential
forever
Continuous execution, without end, of body statement(s)
Used with timing controls Usually last statement in some block
initial : clock_drivebegin
clk = 1’b0;forever #10 clk = ~clk;
end : clock_drive
31Intel Confidential
repeat
Repeat a block ‘x’ times, no conditional testrepeat (expr) statement
What happens with expr = ‘x’ or ‘z’?
Examplex = 0;repeat (16) begin
$display(“%d”, x++);end
32Intel Confidential
while
Executes statement as long as expr evaluates to truewhile (expr) statement
Example:while (reg_i) begin
something_happens();
reg_i = reg_i – 1;
end
33Intel Confidential
for
‘C’ inspired for loopfor (initial_assignment; condition; step_assignment)
statement
Equivalent tobegin
initial_assignment;while (condition) begin
statement;step_assignment;
endend
34Intel Confidential
Enhanced for
SystemVerilog adds: Loop variable declarationMultiple statements in init and step blocks (comma
separated)++ and -- operators (Mentioned in operator section)
for (int i; i < arr.size(); j+=2, i++) beginarr[i] += 200;arrb[i]--;
end
35Intel Confidential
do..while
do statement while (expr);
What’s the difference?x = 0;
1) while (x) begin $display(“%d”, x); x--;
end2) do
begin $display(“%d”, x); x--; end
while (x);
36Intel Confidential
Lab 4: Flow control
Write a SystemVerilog module to display the first 20 Fibonacci numbers.
Fn = Fn-1 + Fn-2
� Hint: F1 = F2 = 1
User Defined Types andEnumerated Types
8-38 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
User Defined Types
SystemVerilog supports a new keyword: typedef
Syntax: typedef <base_data_type> <type_identifier>
typedef int inch ; // inch becomes a new type
inch foot = 12, yard = 36; // these are 2 new variables of type ‘inch’
8-39 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Enumeration
Enumeration is a useful way of defining abstract variables.
Define an enumeration with “ enum ”enum {red, green, yellow} traf_lite1, traf_lite2;
Values can be cast to integer types and auto-incrementedenum { a=5, b, c} vars; // b=6, c=7
A sized constant can be used to set size of the typeenum bit [3:0] { bronze=4’h3, silver, gold} medal; // All medal members are 4-bits
NOTE:
Default assigned values start at zero
0 1 2enum {red, green, yellow} lite;
Syntax:enum [enum_base_type] { enum_name_declaration {,enum_name_declaration} }
enum_base_type: default is int
Define a new typetypedef enum {NO, YES} bool; // bool is NOT a SystemVerilog typebool myvar; // but it just became one �
“myvar” will now be checked for valid values in all assignments, arguments and relational operators
40Intel Confidential
Enumeration example
Modelsim now allows viewing of enum types inwaveforms similar to VHDL enumtypes.
To use enumerated types in numerical expressionsthe language provides the following functions:prev(), next(), first(), last(), num() and name().
Exampletypedef 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;
Casting
42Intel Confidential
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].
Arrays
44Intel Confidential
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 = 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. � Ex: logic m [5:0];
// each element is only 1-bit deep
� Arrays can have packed and unpacked dimensions.� Ex: logic [3:0] m [5:0]
8-45 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Array Literals and Default
To help in assigning literal values to arrays SV introduces the default keyword:
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
int m [1:2][1:3] = '{'{0,1,2},'{3{4}}}; // 2 groups of 3
int k [1:1000] = '{default: 5}; // All elements “5”
8-46 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Dynamic Arrays
Dynamic declaration of one index of an unpacked array
Syntax:data_type array_name[] ;
Declares a dynamic array array_name of type data_type
data_type array_name[] = new[ array_size ] [(array)] ;Allocates a new array array_name of type data_type and size array_sizeOptionally assigns values of array to array_nameIf no value is assigned then element has default value of data_type
Examples:bit [3:0] nibble[ ]; // Dynamic array of 4-bit vectorsinteger mem[ ]; // Dynamic array of integers
int data[ ]; // Declare a dynamic arraydata = new[256]; // Create a 256-element arrayint addr = new[100]; // Create a 100-element arrayaddr = new[200](addr); // Create a 200-element array
// preserving previous values in lower 100 addresses
1st new array in SV, not synthesizable
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];addr.delete();
Cannot delete selected elements
48Intel Confidential
Dynamic Array Examplemodule dyn_arry ();
bit data1 [];initial
begin
// create a 128 element array
data1 = new [128];
$display("Size of array = %d",
data1.size());
data2 = new[256](data1);
$display("Size of array = %d",
data2.size());
data1.delete();
$display("Size of array = %d",
data1.size());
end
endmodule
8-49 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Queues and Lists
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[$]; // $ represents the ‘upper’ array boundaryint n, item;
q1 = ‘{ n, q1 }; // uses concatenate syntax to write n to the left end of q1q1 = ‘{ q1, n }; // uses concatenate syntax to write n to the right end of q1
item = q1[0]; // read leftmost ( first ) item from listitem = q1[$]; // read rightmost ( last ) item from list
n = q1.size; // determine number of items on q1
q1 = q1[1:$]; // delete leftmost ( first ) item of q1q1 = q1[0:$-1]; // delete rightmost ( last ) item of q1
for (int i=0; i < q1.size; i++) // step through a list using integers (NO POINTERS)begin … end
q1 = { }; // clear the q1 list
3rd new array in SV, not synthesizable
8-50 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Queue Methods
size() Returns the number of items in the queue. Prototype:If the queue is empty, it returns 0. function int size();
insert() Inserts the given item at the specified index position. Prototype:function void insert (int index, queue_type item);
Q.insert (i, e) => Q = ‘{Q[0:i-1], e, Q[i,$]}
delete() Deletes the item at the specified index position. Prototype: function void delete (int index);
Q.delete (i) => Q = ‘{Q[0:i-1], Q[i+1,$]}
pop_front() Removes and returns the first element of the queue. Prototype: function queue_type pop_front();
e = Q.pop_front () => e = Q[0]; Q = Q[1,$]
pop_back() Removes and returns the last element of the queue. Prototype: function queue_type pop_back();
e = Q.pop_back () => e = Q[$]; Q = Q[0,$-1]
push_front() Inserts the given element at the front of the queue. Prototype: function void push_front (queue_type item);
Q.push_front (e) => Q = ‘{e, Q}
push_back() Inserts the given element at the end of the queue. Prototype: function void push_back (queue_type item);
Q.push_back (e) => Q = ‘{Q, e}
51Intel Confidential
Queue Examplemodule queues ();
int q [$]; // declare the q
initialbegin: store_disp
// Push elements into the queueq.push_back(1);q.push_back(0);
// Display its contents$display("Size of queue = %0d", q.size());
// Delete the element of queue at index 1q.delete(1);
// Push to front of the queueq.push_front (0);
// Display all the contents in the queuefor (int i = 0; i < q.size(); i++)
$display("q[%0d] = %0d", i, q[i]);
end: store_disp
endmodule: queues
52Intel Confidential
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
53Intel Confidential
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 wordsvalue_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.
54Intel Confidential
Index Types
� String Index Types� Ex: int a [string];a[“joe”] = 21;
� Integer Index Types� Ex: bit [1:0] a [int];a[5] = 2’b11;
55Intel Confidential
Associative Array Methods
finds the entry whose index is greater/smaller than the given index.
next (<index>), prev (<index>)
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.
first (<index>), last (<index>)
Returns 1 if element exists at index else 0
exists (<index>)
Index for delete optional. When specified used to delete given index else whole array.
delete(<index>)
Returns number of entriesnum()
UseFunction
56Intel Confidential
Associative array methods - Examplemodule asoc_arry ();
int db [string]; // Define an associative arrayinitial begin: test
string s;db ["joe"] = 21; // store values at indexes of associative arraydb ["jill"] = 19;
// Display the size of the associative array $display("Size of hash = %0d", db.num());if (db.exists("jill")) // check if index exists and change valuebegin
db["jill"] = 25;end
// print the contents of associative arrayif (db.first(s))do begin
$display("Name = %s -- Age = %0d", s, db[s]); endwhile (db.next(s));
end: testendmodule: asoc_arry
57Intel Confidential
Lab 7: Associative Arrays
1. Define an associate array named 'assoc' assoc has the following attributes:INDEX - Name of personVALUE - Age
2. Make the following entries into assocNAME AGE----------------John 25James 30Jane 24
3. Display the size of the hash using $display statement4. Check if name Jane exists in the associative array and if it does
change her age to 40.5. Print the contents of the associative array.
Procedural Blocks
59Intel Confidential
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
60Intel Confidential
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.
Examplemodule stimulus;
reg a,b;
initial
begin
#5 a = 1’b1;
#25 b = 1’b0;
end
endmodule
61Intel Confidential
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.
Examplemodule clock_gen;
bit clock;
initial begin
clock = 1’b0;
forever #10 clock = ~clock;end
always @(posedge clk)
begin
<statements>;
end
endmodule
62Intel Confidential
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.
Examplefinal
begin
$display("Number of cycles
executed %d",$time/period);
$display("Final PC = %h",PC);
end
63Intel Confidential
Lab 8: Procedural Blocks
Create a SystemVerilog module:1. Define an initial block such that it generates a clock clk time
period = 10nsNOTE: Need to initialize clock even though the bit data type is automatically done.
2. Create an always blocks that stores the value of signal 'clk' into queue 'q' at positive edge of the clock.
3. Increment 'counter' when always block is triggered4. When counter reaches 4 call $finish system call
Hint: Use if statement 5. Define a final block to print the size of 'q' at the end of simulation
Hint: Use final blocks
� Output:# Size of q = 4
Types of Assignment
BlockingNonblocking
65Intel Confidential
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.
Exampleinitial
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
66Intel Confidential
Nonblocking Assignment
� The simulator completes a non-blocking assignment (<=) in two passes.� Right-hand side of the
assignment is sampled immediately.
� Assignment to the left-hand side is postponed until other evaluations in a given simulation time step are complete.
Exampleinitial
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
Tasks and Functions
8-68 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Tasks
return keyword is supported and terminates task at that point
ANSI style portlists
task automatic my_task( input int local_a,int local_b);
if (local_a == local_b)begin
my_task(local_a-1,local_b+1); return; // end ‘this’ copy of task
endglobal_a = local_a;global_b = local_b;
endtask
automatic tasks allocate memorydynamically at call time.
Implied begin…end
Default port direction is input
SystemVerilog makes a number of extensions to basic Verilog syntax.
Arguments can be ANYSV type, even structs, etc.
Full recursion is supported (automatic variables/arguments stored on stack)• Can do concurrent calls• Can do recursive calls
69Intel Confidential
Task usage examples [1]Example of an automatic taskmodule task_reentry();
task automatic reentry();
int counter = 0;
counter++;counter++;
counter++;
counter++;
counter++;$display("Value of counter = %0d",
counter);
endtask
initial
begin
reentry();
reentry();reentry();
reentry();
end
endmodule: task_reentry
What will be the value of counter for each call to reentry()?
Example of a static taskmodule task_reentry();
task reentry();
int counter = 0;
counter++;counter++;
counter++;
counter++;
counter++;$display("Value of counter = %0d",
counter);
endtask
initial
begin
reentry();
reentry();reentry();
reentry();
end
endmodule: task_reentry
What will be the value of counter for each call to reentry()?
70Intel Confidential
Task usage examples [2]
module task_function ();int i, j, z;
initialbegin
i = 5;j = 3;
endinitialbegin
#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: tskendmodule
8-71 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Functions
function automatic int factorial (int n);if (n==0) return(1); // factorial 0 is 1else return(factorial(n-1)*n);
endfunction
return(value) is supported and terminates function at that point
ANSI style portlists
automatic functions allocate memorydynamically at call time (full recursion).
Implied begin…end
Default port direction is input (also supports output)
Arguments and return type can be ANY SV type, even complex structs, etc.
function void inverta();a = !a
endfunction
reg a;
initialinverta(); // function called like a task
Return type of voidmeans no return value!
EndEnd
Recommended style (instead of writing a task)to guarantee a task executes with 0 delay.
72Intel Confidential
Function usage examples
Example 2typedef enum {FALSE, TRUE} bool;
bool cache_range;
function bool is_cache_range ();
if (addr > 0 & addr < 10)
begincache_range = TRUE;
$display("addr in cache range = %d", addr);
return TRUE;
endelse begin
cache_range = FALSE;
return FALSE;end
endfunction
Example 1function void show_packet();
$display("==================");$display("Packet Type = %s",
context_name);$display("Address = %h", addr);$display("Data = %h", data);
$display("===================");endfunction
73Intel Confidential
Task and Functions Usage - Summary
� Tasks� Tasks can enable other tasks and functions� Tasks may execute in non-zero simulation time.� Tasks may have zero or more arguments of type input, output
and inout.� Functions
� Function can enable other functions only. Task cannot be called from functions.
� Functions should execute in zero simulation time.� Functions have only one return value but SystemVerilog also
allows functions to have input, output or inout types.� Both tasks and functions support passing arguments by
reference. By default arguments are passed by value. [Pass by reference not supported in Modelsim 6.1]
74Intel Confidential
Task and function argument passing
� Passing by value is the default mechanism for passing arguments.
� Copies arguments passed into subroutine area.
� Changes to arguments in subroutine are not visible outside.
� When defined as automatic, each copy retains a local copy of argument.
Examplefunction int val
(byte m [3:0]);
<function body>;
endfunction
// a local copy of ‘m’ is
// created when ‘val’ is
// called.
75Intel Confidential
Default argument values – Tasks/Functions
� SV allows a subroutine declaration to specify default value for each argument.
� When subroutine is called, 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.
Exampletask 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
76Intel Confidential
Lab 9a
� Create a SystemVerilog module as described below:
1. Define a queue 'q' of string type.2. Define a named initial block "store_info"3. Store the following values into the queue
1. index =0, str = "Intel Chandler"2. index =1, str = "Intel Folsom"
4. Display the size of the queue.5. Define a function named "change_str" which does the following:
1. Takes queue and index value as input2. 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.
77Intel Confidential
Lab 9b6. Define a task named “show" which does the following:
1. Takes queue and return value from "change_str" as inputs2. The default inital value [task input argument: ret_value] shall be
set to 0.3. When the return value from "change_str" function is 1, prints the
elements stored in the queue using the following format:q[%0d] = %s"
7. Notes: "change_str" and “show" are called from named initial block "store_info".
� Output:# Loading work.lab9# run –all# Size of storage q = 2# q[0] = Intel Chandler# q[1] = Intel Ireland# q -f
Hierarchy
Who comes first
79Intel Confidential
Modules
The basic hardware unit in Verilog.Hierarchy of design Ports represent communication
ModuleInputs
Outputs
Inout
80Intel Confidential
Ports
ConnectionsDirection – input, output, inoutType – 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;
81Intel Confidential
Module syntax
module x (port_list);module_body
endmodule : x
Instantiationx x1 (port_binding_list);
Examplemodule 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_holderendmodule : cpu
// Error pronecpu cpu_inst1(addr, data, w_or_rb);// Bettercpu cpu_inst2(.addr(addr),
.data(data),
.w_or_rb(w_or_rb));
// Newercpu cpu_inst3( .* );
82Intel Confidential
Parameters
Generic parameters (ala VHDL generics)Elaboration time constantsSeparate “ports” on a moduleExamplemodule xyz
#(parameter int width = 8)(input x[width-1:0], output y));assign y[width-1:0] = x[width-1:0]^ 8’hAE;
endmodulexyz #(.width(14)) xyz1 (.x(inp), .y(outp));
83Intel Confidential
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 functionExamplewire x;dut dut1(.outp(x));dut dut2(.outp(x));
8-84 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
InterfacesGreat 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.
MMU MEM
data
addr
rw_
ena
interface
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;. . .
endmodule
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
Traditional Verilog
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
module system;interf i1;mmu U1 (i1);mem U2 (i1);
endmodule
SystemVerilogAt it’s simplest an interface islike a modulefor ports/wires
ad adr
8-85 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
IO Abstraction
intf.a = 0; if ( intf.a == 1)…
a reg a;
source sinkinterface intf
intf.wrt_a(0); if (intf.rd_a() == 1)a reg a;
source sinkinterface intf
task wrt_a();task rd_a();
a = 0;
if ( a == 1)…
aa a
source sink
reg a; 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
Enhanced interface with methods• source/sink only call methods• source/sink don’t see low-level
“details” like variables/structure, etc.• Easy to swap interface abstractions
without any effect on source/sink
8-86 • SV for Verification Using Questa: Functional Coverage 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.
87Intel Confidential
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
88Intel Confidential
modport
� Different users of interface need different views� Master/Slave
� Restrict access to internal interface signals� Protect
implementation signals from corruption
Exampleinterface 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
89Intel Confidential
Lab 10
Create modules moda and modb. moda has an input named a, and an output
named bmodb has an input named b, and an output
named aUse an interface to connect
90Intel Confidential
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
91Intel Confidential
Clocking block syntax
clocking block_name clocking_event;item list;
endclocking : block_name
clocking bus @(posedge clock1);default input #10ns output #2ns;input data, ready,
enable=top.mem1.enable;output negedge ack;input #1 addr;
endclocking
92Intel Confidential
Program Blocks
A program block is similar to a module. It is used for testbench code.
program helloWorld();initialbegin: hello
$display("Hello World");end
initialbegin: there
$display(“Hello There”);end
endprogram: helloWorld
93Intel Confidential
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.
Day Two
Classes
SystemVerilog and Object Oriented Programming
Testbench Only
96Intel Confidential
Object Oriented Primer
A Class is a description of some group of things that have something in common.
Objects are individual instances of “classes”.� Example: A class might be “Automobile”. Instances of the
“Automobile” class might be “Joe’s car”, “Bob’s car”, “Sally’s truck”, etc.
Objects/Classes have: � Data
� Color, speed, direction, etc.� Operations/Methods
� Start, stop, increaseSpeed, turn, etc.Encapsulation:
� Encapsulate implementation details internal to the object/class.
97Intel Confidential
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: (has-a relationship)� 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.
98Intel Confidential
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.
99Intel Confidential
Class Format
class classname [extends superclass];
property declarations;
constructor;
methods;
endclass: myPacket
100Intel Confidential
Example Classclass 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: myFuncendclass: myPacket
101Intel Confidential
Referencing Properties and Methods
Instance data properties and methods may be referenced/called using the “.” operator.
c = new;c.property1 = 10;c.property2 = 11;c.task1();c.function1();
102Intel Confidential
Constructors
Example constructorfunction new();
command = IDLE;data = {1,2,3,4};
endfunction: new
// Creating an instance invokes the constructor:myInstance = new;
Constructors may take arguments.function new(int a = 0, bit[12:0] addr = 0);
…endfunction: new
When extending a class constructor, call super.new().function new();
super.new();…
endfunction: new
Only one constructor per class allowed.
103Intel Confidential
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: myFuncendclass: myPacket
104Intel Confidential
Static PropertiesStatic 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: setStaticPropertyendclass: StaticExample
105Intel Confidential
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: staticMethodendclass: StaticExample
StaticExample::staticMethod();
106Intel Confidential
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: BaseClassclass myFirstClass extends BaseClass;
virtual function int myFunc(int b);return(b – 3);
endfunction: myFuncendclass: myFirstClassclass mySecondClass extends BaseClass;
virtual function int myFunc(int b);return(b + 3);
endfunction: myFuncendclass: mySecondClass
BaseClass bc;
// Returns an instance myFirstClassbc = getFirstClassInstance();$display(“What do I print? %d”
,bc.myFunc(6));
// Returns an instance mySecondClassbc = getSecondClassInstance();$display(“What do I print? %d”
,bc.myFunc(6));
107Intel Confidential
Data Hiding and Encapsulation
To make data members visible only to the class, use the local keyword.
class myPacket extends BasePacket;local int x;
To make data members visible only to the class, or any subclasses, use the protected keyword.
class myPacket extends BasePacket;protected int x;
108Intel Confidential
Constant Class Properties
The const keyword may be used to make class properties unchangeable. const constants are different from d̀efine constants because the initial value may be
determined at runtime, and may be different per class instance.class myPacket extends BasePacket;
const int size; // Assignment of constant value in // declaration makes it constant // to all instances.
function new(int id);size = id * 4096; // Single assignment in
// constructor OK
…
109Intel Confidential
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;
…
110Intel Confidential
Typedef Class and Forward References
Sometimes it is necessary to use a class before it has been defined. To do this, you can use a typedefforward reference, then later define the class. Example:
typedef class C2; // Forward declaration of C2class C1;
C2 c2Instance;…
endclass: C1class C2;
C1 c1Instance;…
endclass: C2
111Intel Confidential
Lab 11a: ClassesCreate an “Xaction” class. The Xaction class should have the followingProperties:
byte data[$]; // Queue of bytesint length; // Length in bytes
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=0xXXXXXXXXstring toString();
Hint: $sformat(str,"Len=%d, DATA=0x%h",length,data);
Using your new class, run the following test code.Xaction x;
x = new;x.setData(‘{1,2,3,4,5,6,7,8});$display(“%s”,x.toString());
112Intel Confidential
Lab 11b: ClassesModify lab10a and create a subclass of the Xaction class that has the following
property added:int iws; // Initiator wait states
Add a task to the class that waits for the number of time steps specified in iws:// Wait IWS time stepsstall();
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
Execute the following testcode.Xaction x;SubXaction s;
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());
113Intel Confidential
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>;
114Intel Confidential
Virtual Interfaces Exampleclass BFM;
virtual Bus bus;
Xaction xaction;
function new (virtual Bus b);
// need to initialize virtual interface// in constructor
bus = b;
xaction = new;
endfunction
task req_bus();
@(posedge bus.clk);
bus.req <= 1'b1;
$display("Req = %b @ %0t", bus.req, $time);
endtask: req_bus
endclass: BFM
// interface
// definitioninterface Bus (input logic clk);
bit req;
bit grant;
logic [7:0] addr;
logic [7:0] data;
endinterface: Bus
// testbench
// interface instance
Bus infc_b (clk);
// dut instance dut dut1 (infc_b, clk);
// class instance BFM mybfm =
new (infc_b);
Random Constraints
How to decide how random to be
116Intel Confidential
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
117Intel Confidential
Simplest randomness
$urandom system tasks$urandom() is SV, thread stable, deterministic $urandom returns unsigned 32-bit integersProcedural call can be inserted wherever
needed
118Intel Confidential
More sophisticated mechanisms
Random variables (rand modifier – classes only)Must be properties of a class, except for some explicit randomizationSelect new random value each time “.randomize()” is called
Example:class x;
rand int a, b, c;endclass : xx x_inst = new;initialbegin : random_loop
forever @(posedge clk) x_inst.randomize();end : random_loop
119Intel Confidential
What’s ‘randc’ for?
Exhaustive permutations of a variable‘c’ is for “cyclic”, every value of the variable will
be reached before any value is duplicatedCaution… special solver ordering for randc
120Intel Confidential
Constraints
Set of Boolean algebraic expressionsRelationships between random variables and:
Other random variablesNon-random state variables
Example:constraint a_le_b { a <= b; }constraint c_eq_10 {c == 10;}constraint b_in_range { b >= 2 && b <= 8; }constraint all_gt_0 {a > 0; b > 0; c > 0;}
How many permutations are now possible?
121Intel Confidential
Constraints
Restrict range of possible valuesCan use state variables to restrict range of
random variablesExample: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; }
122Intel Confidential
Conflicting constraintsWhat happens when you impose constraints
that conflict in some way?Example:
constraint x_gt_y { x > y; }
constraint y_gt_z { y > z; }constraint z_gt_x { z > x; }
…
if ( x_inst.randomize() == 0 ) // Solver errorbegin
…end
Modelsim cmdline setting-solvefaildebug
123Intel Confidential
Constraint operators
Any Verilog boolean expressioni.e. x < y+b-c*10>>20
Other constraint operationsset membership within
implication -> or if…else…iterative constraint foreach
variable ordering solve … before …functions func_x()
124Intel Confidential
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
125Intel Confidential
Loop/array constraints
Constrain every element of an array in some fashion, including reference to other elements of array
constraint c1 { foreach ( A[i] )
A[i] inside {2, 4, 6, 8, 10}; }
constraint c2 { foreach ( A[k] )
(k < A.size-1) -> A[k+1] > A[k];
}
126Intel Confidential
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’
127Intel Confidential
.randomize with {}
� Specify inline constraints that are added to constraint set to solve
trans.randomize() with { x < 100; z > buzz; };
128Intel Confidential
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
};}
129Intel Confidential
Putting it all togethermodule 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 devicesconstraint 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>
130Intel Confidential
Putting it all together (cont)transaction trans = new();intialbegin : test_bodyint counter = 0;repeat (20) begin : rand_genif (trans.randomize() == 0) begin$display(“ERROR: Random constraints
conflict”);$finish;
end$display(“%d: %s”, counter++, trans.toString());end : rand_gen
end : test_body
endmodule : test_rand
131Intel Confidential
Lab 12: Random Constraints
Modify the Xaction class created in lab11 and make all properties rand.
1. Add a rand property named size, with the following enumerated values: SMALL, MEDIUM, LARGE.
2. Add a distribution constraint that make the size: SMALL 70%, MEDIUM 20%, LARGE 10%.
3. 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. Write a loop that calls randomize() 40 times, printing the Xaction after each randomize() call.
132Intel Confidential
Packages
� A mechanism for sharing parameters, data, types, tasks, functions, classes, sequences, and properties among modules, interfaces and programs
133Intel Confidential
Package Search Order Rules
The importing identifiers become directly visible in the importing scope:- c
import p::c
if ( ! c ) …
All declarations inside package p become potentially directly visible in the importing scope:- c, BOOL, FALSE, TRUE
import p::*;
y = FALSE;
A qualified package identifier is visible in any scope
u = p::c, y = p::TRUE
package p;
typedef enum {FALSE, TRUE} BOOL;
BOOL c = TRUE;
endpackage
134Intel Confidential
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
ORmodule top;
p::BOOL b = p::TRUE;
endmodule
135Intel Confidential
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
System Tasks
137Intel Confidential
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
138Intel Confidential
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
139Intel Confidential
Simulation Control
$finish – end simulation (quit simulator), final blocks$stop – halt simulation$exit – quit execution of program block (SV-only)
Exampleinitial
#10000 $finish();
initial
@(posedge all_bfms_done) $finish();
140Intel Confidential
File I/O
integer fd = $fopen(string filename, string mode)char c = $fgetc(int fd);int code = $ungetc(char c, int fd);integer code = $fgets(string str, int fd);integer code = $fscanf(int fd, FORMAT, args);integer code = $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();
endif (2==$sscanf(buf_s, "%x %x", hexStartAddr, hexEndAddr) )
begin$display(“Address Range: %8x -> %8x”, hexStartAddr, hexEndAddr);
end
141Intel Confidential
File I/O
$fclose $fopen$fdisplay $fstrobe$fdisplayb $fstrobeb$fdisplayh $fstrobeh$fdisplayo $fstrobeo$fgetc $ungetc$fflush $ferror$fgets $rewind$fmonitor $fwrite$fmonitorb $fwriteb$fmonitorh $fwriteh$fmonitoro $fwriteo$readmemb $readmemh$swrite $swriteb$swriteo $swriteh$sformat $sdf_annotate$fscanf $sscanf$fread $ftell$fseek
142Intel Confidential
Random functions
$random
$dist_chi_square $dist_erlang
$dist_exponential $dist_normal
$dist_poisson $dist_t
$dist_uniform
143Intel Confidential
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
…
Threads
145Intel Confidential
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
Examplebegin
#5 a = 1;
#5 a = 2;
#5 a = 3;
end
146Intel Confidential
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.
Examplefork
begin
$display( "First Block\n" );
# 20ns;
end
begin
$display( "Second Block\n" );
@eventA;
end
join
8-147 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
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
fork………
join_any // any block finished
beginfork
…join_none // no waiting at all@(sig1);
end
NOTEChild processes spawned by
a fork…join_none do not start to execute until the parent
process hits a blocking statement
join_any join_none
other blocks continue as dynamic threads
8-148 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Process Control – Wait Fork
With Dynamic processes SystemVerilog needed to provide more global detection that spawned processes have completed.
The wait fork statement is used to ensure that all child processes (spawned bythe process where it is called) have completed execution.
beginfork
task1();task2();
join_any // continue when either task completes
forktask3();task4();
join_none // continue regardless
wait fork; // block until tasks 1-4 completeend
Q6.1
8-149 • SV for Verification Using Questa: Functional Coverage Copyright © 2005 Mentor Graphics Corporation
Process Control – Disable Fork
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.
// 2 child tasks spawned in parallel, first to finish triggers join_any
// Kills the slower task (including any grandchild processes and so on)
task run_tests;fork
simul_test1;simul_test2;
joinendtask
task test_with_timeout;fork
run_tests();timeout( 1000 );
join_anydisable fork;
endtask
Q6.1
150Intel Confidential
Events Trigger Types [1]
� Triggering an event� Named events are triggered
using -> operator.� Triggering an event
unblocks all processes currently waiting on the event.
� These events are such that trigger state cannot be observed but only their effect.
� Event can be visualized in wave window.
module event_testing ();
event a, b;
bit clk;
always @(posedge clk) -> a;
always @(negedge clk) -> b;
initial
begin
clk = 1'b0;
forever #10 clk = !clk ;
end
endmodule
151Intel Confidential
Events Trigger Types [2]
� Nonblocking event trigger� They are triggered using
->> operator.� The statement executes
without blocking and it creates a nonblockingassign update event in the time in which the event occurs.
� The effect of this event is felt during the nonblockingassignment region of a simulation cycle.
Examplealways @(posedge clk)
begin
if (counter == 2)
->> a;
counter++;
end
initial
begin
forever @(a)
$display("event a
triggered @ %0t, $time);
end
152Intel Confidential
Waiting for an event
� @ is used to wait for an event.
� The @ operator blocks the calling process until the given event is triggered.
Examplemodule event_testing ();
event a, b, c;
bit clk;
always @(posedge clk) -> a;
always @(negedge clk) -> b;
always @(a or b)
-> c;
initial
begin
clk = 1'b0;
forever #10 clk = !clk ;
end
endmodule
153Intel Confidential
Event Sequencing: wait_order()
� wait_order construct suspends the calling process until all specified events are triggered in the given order [left to right].
� If any events are triggered out of order then it causes a fail of the operation.
Examplebit 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.
154Intel Confidential
Event Variables [1]
� Merging Events� When one event variable
is assigned to another, both merge into one event variable.
� Executing -> on either one of the events affects processes waiting on either event variable.
Exampleevent a, b;
a = b;-> a; // also triggers b
-> b; // also triggers a
155Intel Confidential
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.
Exampleevent E1 = null;
156Intel Confidential
Event Variables [3]
� Event Comparison� Event variables can be
compared against other event variables or the special value null.
� Equality (==) with another event or with null.
� Inequality (!=) with another event or with null.
Exampleevent E1, E2;
if ( E1 ) // same as if ( E1 != null )
E1 = E2;
if ( E1 == E2 )
$display( "E1 and E2 are the
same event" );
157Intel Confidential
Semaphores
� Can be described as counters used to control access to shared resources by multiple processes [threads].
Printmanager
Printer1[1]
Printer2[1]
Printer3[1]
3 keys2 keys
Printer1[0]
158Intel Confidential
Semaphore Methods
� Semaphore provides following built-in methods:
Try to get one or more keys without blocking.
try_get()
Obtain one or more keys.get()
Return one or more keys back.
put()
Create a semaphore with specified number of keys.
new()
UseMethod
159Intel Confidential
Semaphore example
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
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);endendmodule: semaphore_test
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
160Intel Confidential
Mailboxes
� Mailbox is a communication mechanism that allows messages to be exchanged between different processes.
Process 2Process 1
161Intel Confidential
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
162Intel Confidential
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:
Copies a message from mailbox without actually removing it.
peek()
Try to place a message in mailbox without blocking.Useful only for bounded mailboxes.
try_put()
Try to retrieve a message from the mailbox without blocking.
try_get()/try_peek()
Retrieve a message from mailbox.get()
Place a message in a mailbox.put()
Create a new mailbox.new()
UseMethod
163Intel Confidential
Mailbox examplemb_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: tendmodule: mailbox_ex
module mailbox_ex ();class Xaction;
rand bit [2:0] addr;endclasstypedef mailbox #(Xaction) mbx;mbx mb = new ();
initial begin: tXaction xaction;int mb_size;
for (int i=0; i<5; i++)beginxaction = new;xaction.addr = 3’b111;$display("BEFORE:: Addr = %h",
xaction.addr);mb.put(xaction);
end
164Intel Confidential
BACKUP
165Intel Confidential
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 = new[10];foreach (arr_x[i]) statementforeach (arr_y[m,n,p]) statementforeach (arr_z[i,j]) statement
end
166Intel Confidential
‘unique’ and ‘priority’ modifiers {BACKUP}
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 importantBoth modifiers require that if no fall-through
else/default statement is available, and no branch is true, an error is generated
167Intel Confidential
Lab 5: CRC}
168Intel Confidential
Lab 5: CRC (cont) {BACKUP}
Implement the CRC algorithm shown in the previous foil.
The operators << (left shift) and ^ (xor) will be needed.
Process the bitstream given in the lab file and report the CRC.
169Intel Confidential
Constraint Guards {BACKUP}
Guards prevent the application of constraints, similar to implication, but remove the constraint from consideration of the constraint solver
Use the same implication operator, just using state variables
(!global_reset_state && cmd) -> (cmd_type != IDLE)
Can even test obj pointers for null(a != null && a.x > 10) ->
(y < 100 && y > a.x)
170Intel Confidential
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
171Intel Confidential
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
172Intel Confidential
Random Stability {BACKUP}
� SV has thread random stability