您可以按如下方式实现通用多位复用器:
type data is array(natural range <>) of
std_ulogic_vector(data_width-1 downto 0);
--## Compute the integer result of the function ceil(log(n))
--# where b is the base
function ceil_log(n, b : positive) return natural is
variable log, residual : natural;
begin
residual := n - 1;
log := 0;
while residual > 0 loop
residual := residual / b;
log := log + 1;
end loop;
return log;
end function;
function mux_data(Inputs : data; Sel : unsigned)
return std_ulogic_vector is
alias inputs_asc : data(0 to Inputs'length-1) is Inputs;
variable pad_inputs : data(0 to (2 ** Sel'length) - 1);
variable result : std_ulogic_vector(inputs_asc(0)'range);
begin
assert inputs_asc'length <= 2 ** Sel'length
report "Inputs vector size: " & integer'image(Inputs'length)
& " is too big for the selection vector"
severity failure;
pad_inputs := (others => (others => '0'));
pad_inputs(inputs_asc'range) := inputs_asc;
result := pad_inputs(to_integer(Sel));
return result;
end function;
signal mux_in : data(0 to entries-1);
signal mux_out : std_ulogic_vector(data_width-1 downto 0);
signal mux_sel : unsigned(ceil_log(entries, 2)-1 downto 0);
...
mux_out <= mux_data(mux_in, mux_sel);
mux_data 函数通过创建一个临时数组 pad_inputs 来工作,该数组保证为 2 的幂并且大于或等于条目数。它将输入复制到此数组中,任何未占用的位置默认为(others => '0')。然后它可以安全地使用整数索引来提取选定的输入。存在别名是为了确保函数能够优雅地处理基于非 0 的数组。
data 类型已定义为std_ulogic_vector 的无约束数组。 mux_data 函数将自动适应任何大小,而无需知道 entries 泛型。该函数是在传入升序范围数组的假设下编写的。降序数组仍然有效,但所选索引与选择控件的二进制值不匹配。 unsigned 选择控件通过ceil_log 函数自动配置为所需的大小。这样,逻辑将适应entries 和data_width 的任何值。对于那里的怀疑者,这将综合。
不可能(在 VHDL-2008 之前)将data 类型的信号放在端口上,因为它需要使用泛型设置的约束来声明。处理此问题的标准方法是将输入扁平化为一维数组:
port (
mux_in_1d : std_ulogic_vector(entries*data_width-1 downto 0);
...
);
...
-- Expand the flattened array back into an array of arrays
process(mux_in_1d)
begin
for i in mux_in'range loop
mux_in(i) <= mux_in_1d((i+1)*data_width-1 downto i*data_width);
end loop;
end process;
使用 VHDL-2008,您可以声明一个完全不受约束的类型 data 并在端口上使用它:
-- Declare this in a package
type data is array(natural range <>) of std_ulogic_vector;
...
port (
mux_in : data(0 to entries-1)(data_width-1 downto 0);
...
);
...
-- Substitute this line in the mux_data function
variable pad_inputs : data(0 to (2 ** Sel'length) - 1)(inputs_asc(0)'range);