--------------------------------------------------------------------------
-- Project: JCPU, a portable 8-bit RISC CPU written in VHDL
-- This file: The call/return/data stack
--
-- Copyright (C) 2007 J. Ahrensfeld
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.
--
-- For questions and ideas, please contact the author at jens@jayfield.org
--
--------------------------------------------------------------------------

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.ALL;

use work.cpu_pkg.all;

entity stack_ctrl is
Generic (
	addr_width : integer := 3
);
Port (
	rst			: in  STD_LOGIC;
	clk			: in  STD_LOGIC;
	push		: in  STD_LOGIC;
	pop			: in  STD_LOGIC;
	ptr_out		: out unsigned (addr_width-1 downto 0);
	din			: in  inst_addr_t;
	dout		: out inst_addr_t;
	mem_we		: out STD_LOGIC
	);
end stack_ctrl;

architecture Behavioral of stack_ctrl is

	signal ptr : unsigned (addr_width-1 downto 0);

begin

	ptr_out <= ptr;

stk_ptr:
	process(rst, clk, ptr, push, pop)
	begin
		if rst = '1' then
			ptr <= (others => '0');
			dout <= (others => '0');
			mem_we <= '0';
		elsif rising_edge(clk) then
			mem_we <= push;
			if push = '1' then
				ptr <= ptr + 1;
				dout <= din;
			elsif pop = '1' then
				ptr <= ptr - 1;
			end if;
		end if;
	end process;

end Behavioral;

