Level 45: My ISA

Task

Build an 8-bit ALU with three operations selected by sel[1:0]:

  • sel=0 (ADD) — addition: result = a + b (use Adder8)
  • sel=1 (AND) — bitwise AND: result[i] = a[i] & b[i]
  • sel=2 (OR) — bitwise OR: result[i] = a[i] | b[i]

The OpSelector module takes two 8-bit operands a and b, a 2-bit selector sel, and produces an 8-bit result. Use generate-for for bitwise operations and MUX.

Related materials

Solution

The circuit has three parts:

  1. Adder8 — addition module (already in boilerplate): Adder8 add(sum, carry, a, b).
  2. Bitwise AND/OR via generate-for (i=0..7): and(and_out[i], a[i], b[i]) and or(or_out[i], a[i], b[i]).
  3. Sel decoder + MUX: NOT sel[0], NOT sel[1] → AND-trees for s_add (00), s_and (01), s_or (10). For each bit j (generate-for): result[j] = (sum[j] & s_add) | (and_out[j] & s_and) | (or_out[j] & s_or).
module OpSelector(
    input wire [7:0] a,
    input wire [7:0] b,
    input wire [1:0] sel,
    output wire [7:0] result
);
  wire [7:0] sum;
  wire carry;
  Adder8 add(sum, carry, a, b);

  wire [7:0] and_out, or_out;
  generate
    genvar i;
    for (i = 0; i < 8; i = i + 1) begin : bit_gates
      and ga(and_out[i], a[i], b[i]);
      or  go(or_out[i], a[i], b[i]);
    end
  endgenerate

  wire n0, n1;
  not gn0(n0, sel[0]);
  not gn1(n1, sel[1]);
  wire s_add, s_and, s_or;
  and gs_add(s_add, n0, n1);
  and gs_and(s_and, sel[0], n1);
  and gs_or(s_or, n0, sel[1]);

  generate
    genvar j;
    for (j = 0; j < 8; j = j + 1) begin : mux
      wire r_s, r_a, r_o;
      and ma(r_s, sum[j], s_add);
      and mb(r_a, and_out[j], s_and);
      and mc(r_o, or_out[j], s_or);
      wire r01;
      or md(r01, r_s, r_a);
      or me(result[j], r01, r_o);
    end
  endgenerate
endmodule

Total: 1×Adder8, 8×AND + 8×OR (bitwise), 2×NOT + 3×AND (decoder), 24×AND + 16×OR (MUX via generate-for). ~62 elements.