title: Calculating the Overflow Flag in an ALU
body: <p>First of all, forgive me if this isn't the right place to post this question, but I wasn't sure where it should go. I am currently working on simulating an ALU in Xilinx with VHDL. The ALU has the following inputs and outputs:</p>
  
  <p><strong>Inputs</strong></p>
  
  <ul>
  <li><strong><em>A</em></strong> and <strong><em>B</em></strong>: two 8-bit operands</li>
  <li><strong><em>Ci</em></strong>: single-bit carry in</li>
  <li><strong><em>Op</em></strong>:  4-bit opcode for the multiplexers</li>
  </ul>
  
  <p><strong>Outputs</strong></p>
  
  <ul>
  <li><strong><em>Y</em></strong>: 8-bit output operands</li>
  <li><strong><em>Co</em></strong>: single-bit carry out</li>
  <li><strong><em>V</em></strong>: overflow flag (1 if there is overflow, 0 otherwise)</li>
  <li><strong><em>Z</em></strong>: zero flag (1 if zero, 0 otherwise)</li>
  <li><strong><em>S</em></strong>: sign flag (1 if -ve, 0 if +ve)</li>
  </ul>
  
  <p>The ALU performs the operations detailed in the table below:</p>
  
  <p><a href="https://i.stack.imgur.com/TyM9q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TyM9q.png" alt="table here"></a></p>
  
  <p>I have implemented it using multiplexers and an adder, as illustrated in the diagram below:</p>
  
  <p><a href="https://i.stack.imgur.com/LZPkq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LZPkq.png" alt="here"></a></p>
  
  <p>My question is:</p>
  
  <blockquote>
    <p>How do I calculate the value of the overflow flag, <strong>V</strong>?</p>
  </blockquote>
  
  <p>I am aware that:</p>
  
  <ul>
  <li>If adding a positive to a negative, overflow will not occur</li>
  <li>If there is no carry/borrow, then the overflow can be calculated by evaluating the expression  </li>
  </ul>
  
  <pre class="lang-vhdl prettyprint-override"><code>(not A(7) and not B(7) and Y(7)) or (A(7) and B(7) and not Y(7))
  </code></pre>
  
  <p>where <em>A(7)</em>, <em>B(7)</em> and <em>Y(7)</em> are the 8th bit of <strong><em>A</em></strong>, <strong><em>B</em></strong> and <strong><em>Y</em></strong>     respectively.</p>
  
  <ul>
  <li>In the case of a carry/borrow, There is an overflow if and only if the carry-in and carry-out of the most significant bit are different.</li>
  </ul>
  
  <p>I don't know how to implement this logically in VHDL code however - especially in the case of a carry. </p>