floating point to integer casts can cause undefined behaviour #10184
Description
Status as of 2020-04-18
We intend to stabilize the saturating-float-casts behavior for as
, and have stabilized unsafe library functions that handle the previous behavior. See #71269 for the latest discussion on that stabilization process.
Status as of 2018-11-05
A flag has been implemented in the compiler, -Zsaturating-float-casts
, which will cause all float to integer casts have "saturating" behavior where if it's out of bounds it's clamped to the nearest bound. A call for benchmarking of this change went out awhile ago. Results, while positive in many projects, are quite negative for some projects and indicates that we're not done here.
The next steps are figuring out how to recover performance for these cases:
- One option is to take today's
as
cast behavior (which is UB in some cases) and addunsafe
functions for the relevant types and such. - Another is to wait for LLVM to add a
freeze
concept which means that we get a garbage bit pattern, but it's at least not UB - Another is to implement casts via inline assembly in LLVM IR, as the current codegen is not heavily optimized.
Old status
UPDATE (by @nikomatsakis): After much discussion, we've got the rudiments of a plan for how to address this problem. But we need some help with actually investigating the performance impact and working out the final details!
ORIGINAL ISSUE FOLLOWS:
If the value cannot fit in ty2, the results are undefined.
1.04E+17 as u8