Variadic Functions in VHDL

Here’s a function that will take an arbitrary number of ints as arguments.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

package my_package is
    procedure sum(nums: in integer_vector);
end package;

package body my_package is
    procedure sum(nums: in integer_vector) is
        variable total : integer := 0;
    begin
        report integer'image(nums'length) & " elements";
        for i in nums'range loop
            total := total + nums(i);
        end loop;
        report "Total: " & integer'image(total);
    end procedure;
end package;

Within the function, the type of nums is equivalent to integer_vector. We can call nums'length, iterate over it with a for loop, etc.

To use the sum procedure, instantiate it in the VHDL architecture like this.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use work.my_package.all;

entity variadic_functions is
end entity;

architecture behavior of variadic_functions is
begin
    process
    begin
        sum((1, 2));
        sum((1, 2, 3));
        sum((1, 2, 3, 4));
        wait;
    end process;
end architecture;

When you run this code, you should observe the output generated by the report statements.

# Expected simulation output
2 elements
Total: 3
3 elements
Total: 6
4 elements
Total: 10

Another key aspect of functions in VHDL is their ability to handle arrays and loops, which we’ll look at next.