ch3-Function

2019-10-24

Functions

The primary purpose of a function is to return a value that can be used in an expression and cannot consume simulation time.

  • A function cannot have time controlled statements like @, #, fork join, or wait
  • A function cannot start a task since tasks are allowed to consume simulation time

Click here to refresh functions in Verilog !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module tb;

// There are two ways to call the function:
initial begin
// 1. Call function and assign value to a variable, and then use variable
int s = sum(3, 4);
$display ("sum(3,4) = %0d", s);

// 2. Call function and directly use value returned
$display ("sum(5,9) = %0d", sum(5,9));

$display ("mul(3,1) = %0d", mul(3,1));
end

// This function returns value of type "byte", and accepts two
// arguments "x" and "y". A return variable of the same name as
// function is implicitly declared and hence "sum" can be directly
// assigned without having to declare a separate return variable
function byte sum (int x, int y);
sum = x + y;
endfunction

// Instead of assigning to "mul", the computed value can be returned
// using "return" keyword
function byte mul (int x, y);
return x * y;
endfunction
endmodule

Simulation Log

1
2
3
4
5
ncsim> run
sum(3,4) = 7
sum(5,9) = 14
mul(3,1) = 3
ncsim: *W,RNQUIE: Simulation is complete.

Click to try this example in a simulator! img

Using declarations and directions

​ Although ANSI-C style declaration was later introduced in Verilog, the old style declaration of port directions are still valid. SystemVerilog functions can have arguments declared as input and output ports as shown in the example below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
module tb;
initial begin
int res, s;
s = sum(5,9);
$display ("s = %0d", sum(5,9));
$display ("sum(5,9) = %0d", sum(5,9));
$display ("mul(3,1) = %0d", mul(3,1,res));
$display ("res = %0d", res);
end

// Function has an 8-bit return value and accepts two inputs
// and provides the result through its output port and return val
function bit [7:0] sum;
input int x, y;
output sum;
sum = x + y;
endfunction

// Same as above but ports are given inline
function byte mul (input int x, y, output int res);
res = x*y + 1;
return x * y;
endfunction
endmodule

参数方向:input、output、inout、ref四种。

Difference between function and task

Function Task
Cannot have time-controlling statements/delay, and hence executes in the same simulation time unit Can contain time-controlling statements/delay and may only complete at some other time
Cannot enable a task Can enable other tasks and functions
Should have atleast one input argument and cannot have output or inout arguments Can have zero or more arguments of any type
Can return only a single value Cannot return a value, but can achieve the same effect using output arguments

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!