aboutsummaryrefslogtreecommitdiff
path: root/gcc/hwint.h
diff options
context:
space:
mode:
authorMikael Morin <mikael@gcc.gnu.org>2015-08-19 13:42:36 +0000
committerMikael Morin <mikael@gcc.gnu.org>2015-08-19 13:42:36 +0000
commitd63c864834782e37f78834d168e7e383d2c080b3 (patch)
tree7fc210dbbfce746c7c7751a31a39af13ad6a75b5 /gcc/hwint.h
parentdce573c43f4e754e2aa0224a67626792b31eaf26 (diff)
downloadgcc-d63c864834782e37f78834d168e7e383d2c080b3.zip
gcc-d63c864834782e37f78834d168e7e383d2c080b3.tar.gz
gcc-d63c864834782e37f78834d168e7e383d2c080b3.tar.bz2
Avoid signed left shift undefined behaviour in sext_hwi
gcc/ PR other/67042 * hwint.h (sext_hwi): Switch to unsigned for the left shift, and conditionalize the whole on __GNUC__. Add fallback code depending neither on undefined nor implementation-defined behaviour. From-SVN: r227008
Diffstat (limited to 'gcc/hwint.h')
-rw-r--r--gcc/hwint.h18
1 files changed, 17 insertions, 1 deletions
diff --git a/gcc/hwint.h b/gcc/hwint.h
index 3793986..4acbf8e 100644
--- a/gcc/hwint.h
+++ b/gcc/hwint.h
@@ -244,11 +244,27 @@ sext_hwi (HOST_WIDE_INT src, unsigned int prec)
if (prec == HOST_BITS_PER_WIDE_INT)
return src;
else
+#if defined (__GNUC__)
{
+ /* Take the faster path if the implementation-defined bits it's relying
+ on are implemented the way we expect them to be. Namely, conversion
+ from unsigned to signed preserves bit pattern, and right shift of
+ a signed value propagates the sign bit.
+ We have to convert from signed to unsigned and back, because when left
+ shifting signed values, any overflow is undefined behaviour. */
gcc_checking_assert (prec < HOST_BITS_PER_WIDE_INT);
int shift = HOST_BITS_PER_WIDE_INT - prec;
- return (src << shift) >> shift;
+ return ((HOST_WIDE_INT) ((unsigned HOST_WIDE_INT) src << shift)) >> shift;
}
+#else
+ {
+ /* Fall back to the slower, well defined path otherwise. */
+ gcc_checking_assert (prec < HOST_BITS_PER_WIDE_INT);
+ HOST_WIDE_INT sign_mask = HOST_WIDE_INT_1 << (prec - 1);
+ HOST_WIDE_INT value_mask = (HOST_WIDE_INT_1U << prec) - HOST_WIDE_INT_1U;
+ return (((src & value_mask) ^ sign_mask) - sign_mask);
+ }
+#endif
}
/* Zero extend SRC starting from PREC. */