<html>
    <head>
      <base href="https://bugs.llvm.org/">
    </head>
    <body><table border="1" cellspacing="0" cellpadding="8">
        <tr>
          <th>Bug ID</th>
          <td><a class="bz_bug_link 
          bz_status_NEW "
   title="NEW - Missed optimization to use the carry flag after subtracting"
   href="https://bugs.llvm.org/show_bug.cgi?id=46809">46809</a>
          </td>
        </tr>

        <tr>
          <th>Summary</th>
          <td>Missed optimization to use the carry flag after subtracting
          </td>
        </tr>

        <tr>
          <th>Product</th>
          <td>libraries
          </td>
        </tr>

        <tr>
          <th>Version</th>
          <td>10.0
          </td>
        </tr>

        <tr>
          <th>Hardware</th>
          <td>PC
          </td>
        </tr>

        <tr>
          <th>OS</th>
          <td>Linux
          </td>
        </tr>

        <tr>
          <th>Status</th>
          <td>NEW
          </td>
        </tr>

        <tr>
          <th>Severity</th>
          <td>normal
          </td>
        </tr>

        <tr>
          <th>Priority</th>
          <td>P
          </td>
        </tr>

        <tr>
          <th>Component</th>
          <td>Backend: X86
          </td>
        </tr>

        <tr>
          <th>Assignee</th>
          <td>unassignedbugs@nondot.org
          </td>
        </tr>

        <tr>
          <th>Reporter</th>
          <td>josephcsible@gmail.com
          </td>
        </tr>

        <tr>
          <th>CC</th>
          <td>craig.topper@gmail.com, llvm-bugs@lists.llvm.org, llvm-dev@redking.me.uk, spatel+llvm@rotateright.com
          </td>
        </tr></table>
      <p>
        <div>
        <pre>Consider these two C functions:

unsigned f1(unsigned x, unsigned y) {
    unsigned z = x - y;
    if (x < y) {
        z += 100;
    }
    return z;
}
unsigned f2(unsigned x, unsigned y) {
    unsigned z;
    if (__builtin_usub_overflow(x, y, &z)) {
        z += 100;
    }
    return z;
}

At -O3 or -Os, they both generate the same assembly:

        movl    %edi, %eax
        movl    %edi, %ecx
        subl    %esi, %ecx
        addl    $100, %ecx
        subl    %esi, %eax
        cmovbl  %ecx, %eax
        retq

<a href="https://godbolt.org/z/MevEM9">https://godbolt.org/z/MevEM9</a>

That's suboptimal. They should have instead used lea to save a move, save a
duplicate subtraction, and avoid clobbering the carry flag, like this:

        subl    %esi, %edi
        leal    100(%rdi), %eax
        cmovael %edi, %eax
        retq</pre>
        </div>
      </p>


      <hr>
      <span>You are receiving this mail because:</span>

      <ul>
          <li>You are on the CC list for the bug.</li>
      </ul>
    </body>
</html>