Fix LLP64 detection in SwapByteOrder.h
authorReid Kleckner <rnk@google.com>
Wed, 26 Feb 2020 18:41:59 +0000 (10:41 -0800)
committerReid Kleckner <rnk@google.com>
Wed, 26 Feb 2020 18:59:45 +0000 (10:59 -0800)
MSVC does not define __LONG_MAX__, so we were just getting lucky in this
conditional:
  #if __LONG_MAX__ == __INT_MAX__

Undefined identifiers evaluate to zero in preprocessor conditionals, so
this became true, which happens to work for MSVC platforms.

Instead, use this pattern and let the compiler constant fold:
  return sizeof(long) == sizeof(int) ? SwapByteOrder_32((uint32_t)C)
                                     : SwapByteOrder_64((uint64_t)C);

llvm/include/llvm/Support/SwapByteOrder.h

index 94ba1aa..a8bfc39 100644 (file)
@@ -104,15 +104,16 @@ inline   signed short getSwappedBytes(  signed short C) { return SwapByteOrder_1
 inline unsigned int   getSwappedBytes(unsigned int   C) { return SwapByteOrder_32(C); }
 inline   signed int   getSwappedBytes(  signed int   C) { return SwapByteOrder_32(C); }
 
-#if __LONG_MAX__ == __INT_MAX__
-inline unsigned long  getSwappedBytes(unsigned long  C) { return SwapByteOrder_32(C); }
-inline   signed long  getSwappedBytes(  signed long  C) { return SwapByteOrder_32(C); }
-#elif __LONG_MAX__ == __LONG_LONG_MAX__
-inline unsigned long  getSwappedBytes(unsigned long  C) { return SwapByteOrder_64(C); }
-inline   signed long  getSwappedBytes(  signed long  C) { return SwapByteOrder_64(C); }
-#else
-#error "Unknown long size!"
-#endif
+inline unsigned long getSwappedBytes(unsigned long C) {
+  // Handle LLP64 and LP64 platforms.
+  return sizeof(long) == sizeof(int) ? SwapByteOrder_32((uint32_t)C)
+                                     : SwapByteOrder_64((uint64_t)C);
+}
+inline signed long getSwappedBytes(signed long C) {
+  // Handle LLP64 and LP64 platforms.
+  return sizeof(long) == sizeof(int) ? SwapByteOrder_32((uint32_t)C)
+                                     : SwapByteOrder_64((uint64_t)C);
+}
 
 inline unsigned long long getSwappedBytes(unsigned long long C) {
   return SwapByteOrder_64(C);