Stack.v 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Stack
  3. * mainly used for backing up registers in assembly
  4. * 32 bits wide, can store an entire register per entry
  5. * 128 words long
  6. * TODO optional: send interrupt when pop on empty stack
  7. */
  8. module Stack (
  9. input clk,
  10. input reset,
  11. input [31:0] d,
  12. output [31:0] q,
  13. input push,
  14. input pop,
  15. input clear, hold
  16. );
  17. reg [9:0] ptr = 10'd0; // stack pointer
  18. reg [31:0] stack [1023:0]; // stack
  19. reg [31:0] ramResult = 32'd0;
  20. reg useRamResult = 1'b0;
  21. reg [31:0] qreg = 32'd0;
  22. assign q = (useRamResult) ? ramResult : qreg;
  23. always @(posedge clk)
  24. begin
  25. if (reset)
  26. begin
  27. ptr <= 10'd0;
  28. useRamResult <= 32'd0;
  29. qreg <= 32'd0;
  30. end
  31. else
  32. begin
  33. if (push)
  34. begin
  35. stack[ptr] <= d;
  36. ptr <= ptr + 1'b1;
  37. //$display("%d: push @%d := %d", $time, ptr, d);
  38. end
  39. if (pop)
  40. begin
  41. useRamResult <= 1'b0;
  42. ramResult <= stack[ptr - 1'b1];
  43. if (clear)
  44. begin
  45. qreg <= 32'd0;
  46. end
  47. else if (hold)
  48. begin
  49. qreg <= qreg;
  50. end
  51. else
  52. begin
  53. useRamResult <= 1'b1;
  54. ptr <= ptr - 1'b1;
  55. //q <= stack[ptr - 1'b1]; // simulation does not like this when ptr = 0
  56. //$display("%d: pop @%d := %d", $time, ptr, stack[ptr - 1'b1]);
  57. end
  58. end
  59. end
  60. end
  61. /*
  62. integer i;
  63. initial
  64. begin
  65. for (i = 0; i < 1024; i = i + 1)
  66. begin
  67. stack[i] = 32'd0;
  68. end
  69. end
  70. */
  71. endmodule