// CD40181B: 4-bit arithmetic logic unit (ALU), the CMOS version of the
// 74181.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (12)
// and VDD (24), are left out.
//
// The model uses the active-high reading of the datasheet: A, B and F are
// numbers with 1 = high.  Then the carry in Cn and the carry out Cn+4 are
// active low: Cn = 0 adds one more, Cn+4 = 0 means that the result has a
// fifth bit.  M = 1 selects one of 16 logic functions of A and B, bit by
// bit; M = 0 one of 16 arithmetic functions, chosen by S3-S0.  For
// example, S = 1001 gives A plus B, and S = 0110 with Cn = 0 gives A minus
// B.  A=B is 1 when F3-F0 are all 1, which in subtraction with Cn = 1,
// F = A minus B minus 1, means that A equals B.  P and G, active low, say
// whether the four bits propagate or generate a carry; a look-ahead carry
// chip such as the 40182 uses them to join several ALUs.
//
// Inside, each bit makes two signals from A, B and S3-S0, here x and y.
// The arithmetic result is x plus y plus the carry in; the logic result is
// NOT (x XOR y).  The model computes the same, without the gates of the
// chip.  Synthesizable.

module cd40181
(
    input  logic b0,      // Pin 1
    input  logic a0,      // Pin 2
    input  logic s3,      // Pin 3
    input  logic s2,      // Pin 4
    input  logic s1,      // Pin 5
    input  logic s0,      // Pin 6
    input  logic cn,      // Pin 7:  carry in, 0 = add one more
    input  logic m,       // Pin 8:  1 = logic, 0 = arithmetic
    output logic f0,      // Pin 9
    output logic f1,      // Pin 10
    output logic f2,      // Pin 11
                          // Pin 12: VSS
    output logic f3,      // Pin 13
    output logic a_eq_b,  // Pin 14: 1 = F is 1111
    output logic p,       // Pin 15: carry propagate, active low
    output logic cn4,     // Pin 16: carry out, 0 = a fifth bit
    output logic g,       // Pin 17: carry generate, active low
    input  logic b3,      // Pin 18
    input  logic a3,      // Pin 19
    input  logic b2,      // Pin 20
    input  logic a2,      // Pin 21
    input  logic b1,      // Pin 22
    input  logic a1       // Pin 23
                          // Pin 24: VDD
);

    wire [3:0] a = { a3, a2, a1, a0 };
    wire [3:0] b = { b3, b2, b1, b0 };

    wire [3:0] x = a | (b & { 4 { s0 } }) | (~ b & { 4 { s1 } });
    wire [3:0] y = (a & ~ b & { 4 { s2 } }) | (a & b & { 4 { s3 } });

    wire [4:0] sum = { 1'b0, x } + { 1'b0, y } + { 4'b0, ~ cn };
    wire [3:0] f   = m ? ~ (x ^ y) : sum [3:0];

    assign { f3, f2, f1, f0 } = f;

    assign a_eq_b = & f;
    assign cn4    = ~ sum [4];
    assign p      = ~ (& x);
    assign g      = ~ (y [3] | x [3] & y [2] | x [3] & x [2] & y [1] | x [3] & x [2] & x [1] & y [0]);

endmodule
