[Support] Avoid UB in sys::fs::perms::operator~. NFC.
authorAhmed Bougacha <ahmed.bougacha@gmail.com>
Wed, 26 Apr 2017 00:48:28 +0000 (00:48 +0000)
committerAhmed Bougacha <ahmed.bougacha@gmail.com>
Wed, 26 Apr 2017 00:48:28 +0000 (00:48 +0000)
This was exposed in r297945 and r301220: the intermediate complement
is a 32-bit value, and casting it to 'perms' invokes UB.

llvm-svn: 301373

llvm/include/llvm/Support/FileSystem.h

index 29515c2..e3c5de7 100644 (file)
@@ -116,7 +116,9 @@ inline perms &operator&=(perms &l, perms r) {
   return l;
 }
 inline perms operator~(perms x) {
-  return static_cast<perms>(~static_cast<unsigned short>(x));
+  // Avoid UB by explicitly truncating the (unsigned) ~ result.
+  return static_cast<perms>(
+      static_cast<unsigned short>(~static_cast<unsigned short>(x)));
 }
 
 class UniqueID {