Task and Function - amirrezatav/Verilog_VHDL GitHub Wiki

Verilog Functions

The purpose of a function is to return a value that is to be used in an expression. A function definition always start with the keyword function followed by the return type, name and a port list enclosed in parentheses. Verilog knows that a function definition is over when it finds the endfunction keyword. Note that a function shall have at least one input declared and the return type will be void if the function does not return anything.

Syntax

function [automatic] [return_type] name ([port_list]);
[statements]
endfunctionn

The keyword automatic will make the function reentrant and items declared within the task are dynamically allocated rather than shared between different invocations of the task. This will be useful for recursive functions and when the same function is executed concurrently by N processes when forked.

Function declarations

There are two ways to declare inputs to a function:

// #1
function [7:0] sum;
   input [7:0] a, b;
   begin
      sum = a + b;
   end
endfunction

// #2
function [7:0] sum (input [7:0] a, b);
   begin
   sum = a + b;
   end
endfunction

Returning a value from a function

The function definition will implicitly create an internal variable of the same name as that of the function. Hence it is illegal to declare another variable of the same name inside the scope of the function. The return value is initialized by assigning the function result to the internal variable.

sum = a + b;

Calling a function

A function call is an operand with an expression and has a syntax as shown below.

   reg [7:0] result;
   reg [7:0] a, b;
   initial begin
      a = 4;
      b = 5;
      #10 result = sum (a, b);
   end

Function rules

  1. A function cannot contain any time-controlled statements like #, @, wait, posedge, negedge
  2. A function cannot start a task because it may consume simulation time, but can call other functions
  3. A function should have atleast one input
  4. A function cannot have non-blocking assignments or force-release or assign-deassign
  5. A function cannot have any triggers
  6. A function cannot have an output or inout

Recursive Functions

Functions that call itself are called recursive functions. In the example shown below, a recursive function is written to compute the factorial of a given number.

module tb;
   initial begin
      integer result = factorial(4);
      $display("factorial(4) = %0d", result);
   end
   function automatic integer factorial(integer i);
      integer result = i;
      // This function is called within the body of this
      // function with a different argument
      if (i) begin
         result = i * factorial(i-1);
         $display("i=%0d result=%0d", i, result);
      end else
         result = 1;
         return result;
   endfunction
endmodule