[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
Sun Oct 29 19:12:11 PDT 2017


mgrang updated this revision to Diff 120762.
mgrang added a comment.

Enabled the change under NDEBUG.


Repository:
  rL LLVM

https://reviews.llvm.org/D39245

Files:
  include/llvm/ADT/STLExtras.h


Index: include/llvm/ADT/STLExtras.h
===================================================================
--- include/llvm/ADT/STLExtras.h
+++ include/llvm/ADT/STLExtras.h
@@ -35,6 +35,10 @@
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
 
+#ifndef NDEBUG
+#include <random> // for std::mt19937
+#endif
+
 namespace llvm {
 
 // Only used by compiler if both template types are the same.  Useful when
@@ -771,6 +775,10 @@
   // behavior with an empty sequence.
   auto NElts = End - Start;
   if (NElts <= 1) return;
+#ifndef NDEBUG
+  std::mt19937 Generator(std::random_device{}());
+  std::shuffle(Start, End, Generator);
+#endif
   qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
 }
 
@@ -784,10 +792,33 @@
   // behavior with an empty sequence.
   auto NElts = End - Start;
   if (NElts <= 1) return;
+#ifndef NDEBUG
+  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.
+template <typename IteratorTy>
+inline void sort(IteratorTy Start, IteratorTy End) {
+#ifndef NDEBUG
+  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) {
+#ifndef NDEBUG
+  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.120762.patch
Type: text/x-patch
Size: 1880 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20171030/876af026/attachment.bin>


More information about the llvm-commits mailing list