[PATCH] D50607: Silence GCC warning about broken strict aliasing rules

Kim Gräsman via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sun Aug 12 05:39:38 PDT 2018


kimgr created this revision.
kimgr added reviewers: sammccall, xiangzhai, HaoLiu, llvm-commits.

The as<T>() method would trigger the following warning on GCC <7:

  warning: dereferencing type-punned pointer will break
      strict-aliasing rules [-Wstrict-aliasing]
  
    return *reinterpret_cast<T *>(Union.buffer);
                                              ^

Union.buffer is guaranteed to be aligned to whatever types it contains,
and json::Value maintains the invariant that it only calls as<T>() for a
T it has previously placement-newed into Union.buffer. This should
follow the rules for strict aliasing.

Older GCCs might be incorrectly identifying this as a strict-aliasing
violation and undefined behavior, which could lead to misoptimizations
down the line. We seen no evidence of such behavior.

No functional change intended.


Repository:
  rL LLVM

https://reviews.llvm.org/D50607

Files:
  include/llvm/Support/JSON.h


Index: include/llvm/Support/JSON.h
===================================================================
--- include/llvm/Support/JSON.h
+++ include/llvm/Support/JSON.h
@@ -452,7 +452,23 @@
     new (reinterpret_cast<T *>(Union.buffer)) T(std::forward<U>(V)...);
   }
   template <typename T> T &as() const {
+#if defined(__GNUC__) && !defined(__clang) && (__GNUC__ < 7)
+// Silence
+//
+//   warning: dereferencing type-punned pointer will break strict-aliasing rules
+//   [-Wstrict-aliasing]
+//
+// This private method is always called after type-checking, so the
+// reinterpret_cast<> just re-casts the char buffer to the type that was
+// placement-new-ed into it. Because AlignedCharArrayUnion guarantees correct
+// alignment for all contained types, this plays by the strict aliasing rules.
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif
     return *reinterpret_cast<T *>(Union.buffer);
+#if defined(__GNUC__) && !defined(__clang) && (__GNUC__ < 7)
+#pragma GCC diagnostic pop
+#endif
   }
 
   template <typename Indenter>


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D50607.160253.patch
Type: text/x-patch
Size: 1075 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20180812/0e3b9129/attachment.bin>


More information about the llvm-commits mailing list