Subprograms: Functions & Procedures

pure (default) functions depend only on arguments; impure functions may read external signals/files.

16.1 Functions (return one value, no side effects, no wait)

pure (default) functions depend only on arguments; impure functions may read external signals/files.

function parity(v : std_logic_vector) return std_logic is
  variable p : std_logic := '0';
begin
  for i in v'range loop
    p := p xor v(i);
  end loop;
  return p;
end function;

function log2ceil(n : positive) return natural is
  variable r : natural := 0;
begin
  while 2**r < n loop
    r := r + 1;
  end loop;
  return r;
end function;

constant ADDR_W : natural := log2ceil(DEPTH);   -- functions in constant expressions

16.2 Procedures (multiple outputs, may contain wait, side effects)

Parameter classes: constant (default for in), variable (default for out/inout), signal, file.

procedure add_sat(a, b : in unsigned; signal y : out unsigned; overflow : out boolean) is
  variable s : unsigned(a'length downto 0);
begin
  s := resize(a, a'length + 1) + b;
  overflow := s(s'high) = '1';
  if overflow then y <= (y'range => '1'); else y <= s(a'length - 1 downto 0); end if;
end procedure;

-- Testbench procedure with waits
procedure send_byte(signal tx : out std_logic; data : std_logic_vector(7 downto 0); bit_time : time) is
begin
  tx <= '0'; wait for bit_time;                              -- start bit
  for i in 0 to 7 loop tx <= data(i); wait for bit_time; end loop;
  tx <= '1'; wait for bit_time;                              -- stop bit
end procedure;

16.3 Overloading

function to_slv(i : integer; w : natural) return std_logic_vector;
function to_slv(b : boolean) return std_logic_vector;
function "+"(a : pixel_t; b : pixel_t) return pixel_t;     -- operator overloading