[llvm] r232265 - array_pod_sort: Since we're checking the length anyways also ignore one-element ranges

Benjamin Kramer benny.kra at googlemail.com
Sat Mar 14 07:53:14 PDT 2015


Author: d0k
Date: Sat Mar 14 09:53:14 2015
New Revision: 232265

URL: http://llvm.org/viewvc/llvm-project?rev=232265&view=rev
Log:
array_pod_sort: Since we're checking the length anyways also ignore one-element ranges

Sorting them is obviously a noop and we can skip the libc call. This is
surprisingly common in clang. NFC.

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

Modified: llvm/trunk/include/llvm/ADT/STLExtras.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/STLExtras.h?rev=232265&r1=232264&r2=232265&view=diff
==============================================================================
--- llvm/trunk/include/llvm/ADT/STLExtras.h (original)
+++ llvm/trunk/include/llvm/ADT/STLExtras.h Sat Mar 14 09:53:14 2015
@@ -263,10 +263,11 @@ inline int (*get_array_pod_sort_comparat
 /// default to std::less.
 template<class IteratorTy>
 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
-  // Don't dereference start iterator of empty sequence.
-  if (Start == End) return;
-  qsort(&*Start, End-Start, sizeof(*Start),
-        get_array_pod_sort_comparator(*Start));
+  // Don't inefficiently call qsort with one element or trigger undefined
+  // behavior with an empty sequence.
+  auto NElts = End - Start;
+  if (NElts <= 1) return;
+  qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
 }
 
 template <class IteratorTy>
@@ -275,9 +276,11 @@ inline void array_pod_sort(
     int (*Compare)(
         const typename std::iterator_traits<IteratorTy>::value_type *,
         const typename std::iterator_traits<IteratorTy>::value_type *)) {
-  // Don't dereference start iterator of empty sequence.
-  if (Start == End) return;
-  qsort(&*Start, End - Start, sizeof(*Start),
+  // Don't inefficiently call qsort with one element or trigger undefined
+  // behavior with an empty sequence.
+  auto NElts = End - Start;
+  if (NElts <= 1) return;
+  qsort(&*Start, NElts, sizeof(*Start),
         reinterpret_cast<int (*)(const void *, const void *)>(Compare));
 }
 





More information about the llvm-commits mailing list