Search code examples
verilogmux

Behavioral verilog: creating multiple muxes with 1 module


If I have a module defined like this:

module mux_1x2(in, out, select);

and I need 32 of them, I know that using structural coding I can do:

mux_1x2 mux01(in[0], out[0], select);
mux_1s2 mux02(in[1], out[1], select); 
etc...

But how can I use behavioral programming to make 32 of these in some sort of loop without having to explicitly define each one?

edit: Just for context, I'm trying to make a 2-stage 64-bit carry-select adder


Solution

  • You can use a generate block: (IEEE1364-2001 and above)

    genvar gidx;
    generate
      for(gidx=0; gidx<32; gidx=gidx+1) begin : loop
        mux_1x2 mux(in[gidx], out[gidx], select);
      end
    endgenerate
    

    Or array the instance: (IEEE1364-1995 and above)

    mux_1x2 mux[0:31] ( .in(in) , .out(out) , .select(select)  );
    

    Or parameterize:

    module mux_1x2 #(parameter WIDTH=1) (input [WIDTH-1:0] in, output [WIDTH-1:0] out, input select);
      // ...
    endmodule
    // ...
    mux_1x2 #(32) mux ( .in(in) , .out(out) , .select(select) );