Generic SV programming with generic interface ports

A few named constructs in SystemVerilog, including lets and sequences, allow untyped formal arguments. Another example, from 25.3.3, is that module ports can be declared as generic interface references. This was originally intended for “generic bundles” of signals, but, because functions and types (and even always blocks) can also be wrapped up in an interface and passed around, I was wondering if this capability could be exploited to achieve generic programming with SystemVerilog. Here’s an example showing that it might be possible.

  Given an interface that defines types "T_in" and
  "T_out" and a function "f" from  one to the other,
  define a function "lookup" with the same signature
  as "f", but implemented as a lookup table.
module lut_template(interface ifc);

  typedef ifc.T_in T_in;
  typedef ifc.T_out T_out;
  localparam N = $bits(T_in);

  T_out A[2**N];

  for (genvar I = 0; I < 2**N; I++) begin:GEN
    assign A[I] = ifc.f(T_in'(I[0+:N]));

  typedef logic [N-1:0] T_index;

  function automatic T_out lookup(T_in in);
    return A[T_index'(in)];


module test#(parameter N = 3)(output logic [2*N-1:0] out);
  example#(3) ex1();
  lut_template lut1(ex1);
  always_comb out = lut1.lookup('{5,7}); /* == 35 */
  initial begin
    #1 $display(out);

interface example#(parameter N = 1);
  typedef struct {logic [N-1:0] x, y;} T_in;
  typedef logic [2*N-1:0] T_out;
  function automatic T_out f(input T_in in);
    return (in.x * in.y);

Tell me (anonymous OK)

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s