library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity add is generic ( WIDTH : positive := 8); port ( input1 : in std_logic_vector(WIDTH-1 downto 0); input2 : in std_logic_vector(WIDTH-1 downto 0); output : out std_logic_vector(WIDTH-1 downto 0); carry : out std_logic ); end add; architecture BHV1 of add is begin process (input1, input2) variable temp_add : std_logic_vector(WIDTH downto 0); begin -- This architecture uses a variable to store the temporary sum, which -- is then written to the output and carry -- The important thing to remember about variables is that their values are -- updated immediately. Therefore, the lines of code following the sum -- will see the updated value. temp_add := std_logic_vector(resize(unsigned(input1), WIDTH+1) + resize(unsigned(input2), WIDTH+1)); output <= temp_add(WIDTH-1 downto 0); carry <= temp_add(WIDTH); end process; end BHV1; architecture BHV2 of add is -- In this architecture, we use a signal instead of a variable signal temp_add : std_logic_vector(WIDTH downto 0); begin process (input1, input2) begin -- COMMON MISTAKE -- The following code will not work as expected. The reason is that signals -- are not updated until the end of a process. -- Consider the following example: -- 1) temp_add = 0, input1 = 0, and input2 = 15 -- 2) Input1 changes to 10 causing the process to execute -- 3) The sum of input1 and input2 (25) is assiged to temp_add, but the -- value won't actually be updated until the end of the process -- 4) the following lines see the previous value of temp_add (0) instead -- of the new value (25), which causes "output" to be 0. -- 5) Input1 changes to 20, causing the process to execute -- 6) Temp_add is assigned the new value of 35, but the following lines -- will see the previous value of 25, causing the output to be set to 25. -- SUMMARY -- Variables are updated immediately, signals are updated at the end of the -- process -- Signals are also updated on "wait" statements, but you should not have -- any these statements in synthesizeable code. Unless I tell you -- otherwise, wait statements should only appear in testbenches. temp_add <= std_logic_vector(resize(unsigned(input1), WIDTH+1) + resize(unsigned(input2), WIDTH+1)); output <= temp_add(WIDTH-1 downto 0); carry <= temp_add(WIDTH); end process; end BHV2;