// mac.sv // Pipelined signed multiply-accumulate, written so synthesis can pack it // into one DSP block: input registers, a product register and an // accumulator register, matching the internal registers of a typical DSP slice. // // Every cycle with in_valid = 1 adds a*b to the running sum. // first = 1 starts a new sum (the accumulator loads a*b instead of adding). // Latency from inputs to acc is 3 clock cycles; out_valid marks updated sums. // Data registers have no reset: DSP pipeline registers are smaller and // faster to pack without one. Only the valid flags are reset. `timescale 1ns/1ps module mac #( parameter int AW = 16, // width of a parameter int BW = 16, // width of b parameter int ACCW = 40 // accumulator width: AW + BW + guard bits ) ( input logic clk, input logic rst, input logic in_valid, input logic first, input logic signed [AW-1:0] a, input logic signed [BW-1:0] b, output logic out_valid, output logic signed [ACCW-1:0] acc ); // Stage 1: input registers. logic signed [AW-1:0] a_r; logic signed [BW-1:0] b_r; logic v1, first1; // Stage 2: product register. logic signed [AW+BW-1:0] p_r; logic v2, first2; always_ff @(posedge clk) begin a_r <= a; b_r <= b; first1 <= first; p_r <= a_r * b_r; first2 <= first1; if (v2) begin acc <= first2 ? ACCW'(p_r) : acc + ACCW'(p_r); end end always_ff @(posedge clk) begin if (rst) begin v1 <= 1'b0; v2 <= 1'b0; out_valid <= 1'b0; end else begin v1 <= in_valid; v2 <= v1; out_valid <= v2; end end endmodule