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

    <tr>
        <th>Summary</th>
        <td>
            [APFloat] Wrong result when truncating double to float
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            miscompilation,
            llvm:optimizations
      </td>
    </tr>

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

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

<pre>
    For the following C(++) code Clang produces output that differs from any other major compilers (and from internal tests it was reduced from):
```cpp
#include <cstdio>

int main() {
    long x = 503489155L;
    double y = *(double*)&x;
    float fy = y;
    printf("%lx, %e (%a)\n%f (%a)\n", x, y, y, fy, fy);
}
```
I've pinpointed the issue to Val.convert in FPTrunc case of `llvm::ConstantFoldCastInstruction` which for `0x0.000001e02a283p-1022` double returns `0x1p-149` float, whereas one would expect (assuming the other compilers are correct here) returned value to be `0`.
Furthermore, it is represented as `float 0x36A0000000000000` in IR which may or may not be expected (if it was hex value for simple float, when there eight extra zeroes, but if it uses double width even for regular floats, then it's ok.

godbolt: https://godbolt.org/z/YM3rvY3hM
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJxlVNuO2zgM_RrlRWggy3ESP_ghkzTAAC1QLBa76KNiybG6smTokst8_ZKSdzrtGo4didQheXjoi5PP7uw8jaOigzPG3bW90iPhe8Jf8t3S3klFj0aAYfZOpl4F6lKcU4RjIlKph0H5QAfvJirskzpA83QSPwC4d9OsDZoBU1hZvLSNylthaFQhBqojvYtAvULw4gKBSX0g7ETYgWxZuft5XnZ4rW1vEiRG6mMfotSO1J8XY35CCEhB21xKS8nupexTuIyDWh5w9EQbVm_2bdU0X0j9wUO6dDGKPrMP4RBwX7by_5bw7eMX_8E4YGIo_s9fTLOHVIacBie8MQ_CjwDZKJr3GoF4zRESbYb_bXF0ziee74_h_dm-ByK7029cleUr4buborO2s0PSZ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