[PATCH] D39245: [ADT] Shuffle containers before sorting to uncover non-deterministic behavior

Mandeep Singh Grang via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sat Mar 10 11:02:10 PST 2018


This revision was not accepted when it landed; it landed in state "Needs Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rL327219: [ADT] Shuffle containers before sorting to uncover non-deterministic behavior (authored by mgrang, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D39245?vs=137828&id=137916#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D39245

Files:
  llvm/trunk/include/llvm/ADT/STLExtras.h


Index: llvm/trunk/include/llvm/ADT/STLExtras.h
===================================================================
--- llvm/trunk/include/llvm/ADT/STLExtras.h
+++ llvm/trunk/include/llvm/ADT/STLExtras.h
@@ -36,6 +36,10 @@
 #include <type_traits>
 #include <utility>
 
+#ifdef EXPENSIVE_CHECKS
+#include <random> // for std::mt19937
+#endif
+
 namespace llvm {
 
 // Only used by compiler if both template types are the same.  Useful when
@@ -762,6 +766,10 @@
   // behavior with an empty sequence.
   auto NElts = End - Start;
   if (NElts <= 1) return;
+#ifdef EXPENSIVE_CHECKS
+  std::mt19937 Generator(std::random_device{}());
+  std::shuffle(Start, End, Generator);
+#endif
   qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
 }
 
@@ -775,10 +783,34 @@
   // behavior with an empty sequence.
   auto NElts = End - Start;
   if (NElts <= 1) return;
+#ifdef EXPENSIVE_CHECKS
+  std::mt19937 Generator(std::random_device{}());
+  std::shuffle(Start, End, Generator);
+#endif
   qsort(&*Start, NElts, sizeof(*Start),
         reinterpret_cast<int (*)(const void *, const void *)>(Compare));
 }
 
+// Provide wrappers to std::sort which shuffle the elements before sorting
+// to help uncover non-deterministic behavior (PR35135).
+template <typename IteratorTy>
+inline void sort(IteratorTy Start, IteratorTy End) {
+#ifdef EXPENSIVE_CHECKS
+  std::mt19937 Generator(std::random_device{}());
+  std::shuffle(Start, End, Generator);
+#endif
+  std::sort(Start, End);
+}
+
+template <typename IteratorTy, typename Compare>
+inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
+#ifdef EXPENSIVE_CHECKS
+  std::mt19937 Generator(std::random_device{}());
+  std::shuffle(Start, End, Generator);
+#endif
+  std::sort(Start, End, Comp);
+}
+
 //===----------------------------------------------------------------------===//
 //     Extra additions to <algorithm>
 //===----------------------------------------------------------------------===//


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D39245.137916.patch
Type: text/x-patch
Size: 1982 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20180310/5d00bbf3/attachment.bin>


More information about the llvm-commits mailing list