title: 32 bit adder subtractor ALU using generate
body: <p>I need to implement a 32 bit adder subtractor ALU for a class assignment. I have a 1-bit adder subtractor that works fine and the operation is made with the help of a select statement (code for all is given below). Anyway, the problem I am facing is that I am unable to figure out how to use the carry/borrow out of one module to the subsequent module. </p>
  
  <pre><code>module add_sub(select, i0, i1, cin, out, cout
      );
  
  input i0, i1, select, cin;
  output out, cout;
  wire y0, y1, y2, y3, y4, y5, y6;
  wire z0, z1, z2, z3, z4;
  
  //diff = i0 xor i1 xor cin
  //borrow = cin. ~(i1 xor i2) or ~x.y
  
  xor (y0, i1, cin);
  xor (y1, i0, y0); //y1=diff or sum as only carry and borrow vary between adder and subtractor circuits
  
  xor (y2, i1, i0);
  and (y3, cin, ~y2);
  and (y4, ~i0, i1);
  or (y6, y5, y4); //y6 = borrow
  
  and (z0, i0, i1);
  xor (z1, i0, i1);
  and (z2, cin, z1);
  or (z3, z0, z2); //z3= carry out for sum
  
  //conditional operator for assigning sum or difference. if select = 0, we add, else subtract
  
  assign out = y1;
  assign cout = select ? y6 : z3;
  
  endmodule
  </code></pre>
  
  <p>This module is instantiated in a loop in the alu module that is given below...</p>
  
  <pre><code>module alu(sel, num1, num2, alu_cin, alu_out, alu_c
      );
  
  
  parameter N = 32;
  input sel; //select line for add or sub
  input [N-1:0] num1; //two inputs
  input [N-1:0] num2;
  input alu_cin;
  
  output [N-1:0] alu_out; //32 bit output
  output alu_c;            // becomes final carry or borrow accordingly
  
  genvar i;
  
  generate for (i=0; i&lt;=N-1; i=i+1) 
  
      begin: alu_loop
  
          if (i == 0)
              add_sub as_i (sel, num1[i], num2[i], alu_cin, alu_out[i], alu_c);
          else
              add_sub as_i (sel, num1[i], num2[i], alu_loop[i-1].as_i.cout[i-1], alu_out[i], alu_c);
      end
  
  endgenerate   
  
  
  
  
  endmodule
  </code></pre>
  
  <p>In the test bench for the alu, I gave appropriate 32 bit values and the select value as I need. The problem comes with </p>
  
  <pre><code>add_sub as_i (sel, num1[i], num2[i], alu_loop[i-1].as_i.cout[i-1], alu_out[i], alu_c);
  </code></pre>
  
  <p>It says "Indexing cannot be applied to a scalar." as I am trying to simulate it. Syntax check is completed perfectly.</p>
  
  <p>I need access to cout from the one-bit module to pass it on as cin to the next one. The alu_c can be overwritten as only the last one bit is needed. </p>
  
  <p>Any help would be appreciated. Thanks in advance. :) All this is done on Xilinx ISE through Verilog modules. </p>