<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/84038>84038</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            LLVM fails to optimize emulated arithmetic right shift down to a single ashr 
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          johnplatts
      </td>
    </tr>
</table>

<pre>
    Here is a snippet that LLVM fails to optimize down to a single ashr operation:
```
define i32 @i32_arith_shr(i32, i32) local_unnamed_addr #0 {
  %pos_shr_result = lshr i32 %0, %1
  ; inverted_a == ~((uint32_t)a)
  %inverted_a = xor i32 %0, -1
  ; inverted_a_shr_result = (~((uint32_t)a)) >> b
  %inverted_a_shr_result = lshr i32 %inverted_a, %1
  ; neg_shr_result = ~((~((uint32_t)a)) >> b)
 %neg_shr_result = xor i32 %inverted_a_shr_result, -1
  %a_is_ge_0 = icmp sge i32 %0, 0
  %arith_shr_result = select i1 %a_is_ge_0, i32 %pos_shr_result, i32 %neg_shr_result
  ret i32 %arith_shr_result
}
```

Here is the equivalent snippet in C or C++:
```
int IntArithShr(int a, int b) {
  return (a >= 0) ? (int)((unsigned)a >> b) : (int)(~((~(unsigned)a) >> b));
}
```

If `a < 0`, `int` is a twos complement signed integer type that has no padding bits, and `a >> b` is an arithmetic right shift, then `a >> b` is equal to `(int)(~((~(unsigned)a) >> b))` since the MSB of `~(unsigned)a` is zero if `a < 0`, zeroes are shifted into the upper `sizeof(unsigned)*CHAR_BIT-b` bits of `(~(unsigned)a) >> b`, the bitwise inverse of 0 is 1, and ones are shifted into the upper `sizeof(int)*CHAR_BIT-b` bits of `a >> b` if `a < 0`.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJycVcFu2zgQ_Rr6MkhAk5IiHXSw4xoN0F62i70KlDSSWFCkSlLJNof99gUpO7F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