http://stackoverflow.com/questions/22200666/problems-with-wires-declared-inside-verilog-generate-blocks


Within a generate block, I have multiple if statements. When I declare a wire in the first if statement - I can't use it in other if statements

See the following stripped down example of my module:

module my_module 
#(parameter integer NUM_X_PORTS = 1,
  parameter integer NUM_Y_PORTS = 1)
 (
  // port declarations
 );

generate 

  if (NUM_X_PORTS > 0) begin
    wire [NUM_X_PORTS-1:0] x1;
    // logic filled in here
  end

  if (NUM_Y_PORTS > 0) begin
    wire [NUM_Y_PORTS-1:0] y1;
    // logic filled in here
  end

  if ((NUM_X_PORTS > 0) && (NUM_Y_PORTS > 0)) begin
    for (i=0; i<NUM_Y_PORTS; i=i+1) begin
      assign z[i] = y1[i] & |x1; // I can't use x1 and y1 here
    end

endgenerate

The error message from both VCS and nLint is that indentifiers x1 and y1 have not been declared.

But they have been declared within previous generated if statements - what is the problem here?

=======================================================================================================

The wires x1 and y1 are defined outside of scope of the assignment. One solution is to add and reference scope lables:

if (NUM_X_PORTS > 0) begin : scope_x1
  wire [NUM_X_PORTS-1:0] x1;
  // logic filled in here
end

if (NUM_Y_PORTS > 0) begin : scope_y1
  wire [NUM_Y_PORTS-1:0] y1;
  // logic filled in here
end

if ((NUM_X_PORTS > 0) && (NUM_Y_PORTS > 0)) begin : scope_z
  for (i=0; i<NUM_Y_PORTS; i=i+1) begin : scopes_z_i_ // loop has unique scope
    // x1 & y1 accessed by scope label found by its parent
    assign z[i] = scope_y1.y1[i] & |scope_x1.x1; 
  end
end

For the assignment to work, the declaration of x1 and y1 must exist withing the scope of scope_2 or its parent.

if ((NUM_X_PORTS > 0) && (NUM_Y_PORTS > 0)) begin  : scope_z
  wire [NUM_X_PORTS-1:0] x1;
  wire [NUM_Y_PORTS-1:0] y1;
  // logic filled in here
  for (i=0; i<NUM_Y_PORTS; i=i+1) begin : scopes_z_i_ // loop has unique scope
    assign z[i] = y1[i] & |x1; // everything is withing scope_z
  end
end

In both this cases x1 and y1 are limited in scope. If you do not wish the wire to exist when its respected NUM_*_PORTS > 0 is false, then you must follow the first example.

See IEEE Std 1800-2012 § 27. Generate constructs for more on generate