xref: /freebsd/contrib/llvm-project/llvm/include/llvm/ADT/SmallVector.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file defines the SmallVector class.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_ADT_SMALLVECTOR_H
15 #define LLVM_ADT_SMALLVECTOR_H
16 
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/Support/Compiler.h"
19 #include <algorithm>
20 #include <cassert>
21 #include <cstddef>
22 #include <cstdint>
23 #include <cstdlib>
24 #include <cstring>
25 #include <functional>
26 #include <initializer_list>
27 #include <iterator>
28 #include <limits>
29 #include <memory>
30 #include <new>
31 #include <type_traits>
32 #include <utility>
33 
34 namespace llvm {
35 
36 template <typename T> class ArrayRef;
37 
38 template <typename IteratorT> class iterator_range;
39 
40 template <class Iterator>
41 using EnableIfConvertibleToInputIterator = std::enable_if_t<std::is_convertible<
42     typename std::iterator_traits<Iterator>::iterator_category,
43     std::input_iterator_tag>::value>;
44 
45 /// This is all the stuff common to all SmallVectors.
46 ///
47 /// The template parameter specifies the type which should be used to hold the
48 /// Size and Capacity of the SmallVector, so it can be adjusted.
49 /// Using 32 bit size is desirable to shrink the size of the SmallVector.
50 /// Using 64 bit size is desirable for cases like SmallVector<char>, where a
51 /// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
52 /// buffering bitcode output - which can exceed 4GB.
53 template <class Size_T> class SmallVectorBase {
54 protected:
55   void *BeginX;
56   Size_T Size = 0, Capacity;
57 
58   /// The maximum value of the Size_T used.
SizeTypeMax()59   static constexpr size_t SizeTypeMax() {
60     return std::numeric_limits<Size_T>::max();
61   }
62 
63   SmallVectorBase() = delete;
SmallVectorBase(void * FirstEl,size_t TotalCapacity)64   SmallVectorBase(void *FirstEl, size_t TotalCapacity)
65       : BeginX(FirstEl), Capacity(static_cast<Size_T>(TotalCapacity)) {}
66 
67   /// This is a helper for \a grow() that's out of line to reduce code
68   /// duplication.  This function will report a fatal error if it can't grow at
69   /// least to \p MinSize.
70   LLVM_ABI void *mallocForGrow(void *FirstEl, size_t MinSize, size_t TSize,
71                                size_t &NewCapacity);
72 
73   /// This is an implementation of the grow() method which only works
74   /// on POD-like data types and is out of line to reduce code duplication.
75   /// This function will report a fatal error if it cannot increase capacity.
76   LLVM_ABI void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
77 
78 public:
size()79   size_t size() const { return Size; }
capacity()80   size_t capacity() const { return Capacity; }
81 
empty()82   [[nodiscard]] bool empty() const { return !Size; }
83 
84 protected:
85   /// Set the array size to \p N, which the current array must have enough
86   /// capacity for.
87   ///
88   /// This does not construct or destroy any elements in the vector.
set_size(size_t N)89   void set_size(size_t N) {
90     assert(N <= capacity()); // implies no overflow in assignment
91     Size = static_cast<Size_T>(N);
92   }
93 
94   /// Set the array data pointer to \p Begin and capacity to \p N.
95   ///
96   /// This does not construct or destroy any elements in the vector.
97   //  This does not clean up any existing allocation.
set_allocation_range(void * Begin,size_t N)98   void set_allocation_range(void *Begin, size_t N) {
99     assert(N <= SizeTypeMax());
100     BeginX = Begin;
101     Capacity = static_cast<Size_T>(N);
102   }
103 };
104 
105 template <class T>
106 using SmallVectorSizeType =
107     std::conditional_t<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t,
108                        uint32_t>;
109 
110 /// Figure out the offset of the first element.
111 template <class T, typename = void> struct SmallVectorAlignmentAndSize {
112   alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
113       SmallVectorBase<SmallVectorSizeType<T>>)];
114   alignas(T) char FirstEl[sizeof(T)];
115 };
116 
117 /// This is the part of SmallVectorTemplateBase which does not depend on whether
118 /// the type T is a POD. The extra dummy template argument is used by ArrayRef
119 /// to avoid unnecessarily requiring T to be complete.
120 template <typename T, typename = void>
121 class SmallVectorTemplateCommon
122     : public SmallVectorBase<SmallVectorSizeType<T>> {
123   using Base = SmallVectorBase<SmallVectorSizeType<T>>;
124 
125 protected:
126   /// Find the address of the first element.  For this pointer math to be valid
127   /// with small-size of 0 for T with lots of alignment, it's important that
128   /// SmallVectorStorage is properly-aligned even for small-size of 0.
getFirstEl()129   void *getFirstEl() const {
130     return const_cast<void *>(reinterpret_cast<const void *>(
131         reinterpret_cast<const char *>(this) +
132         offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)));
133   }
134   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
135 
SmallVectorTemplateCommon(size_t Size)136   SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
137 
grow_pod(size_t MinSize,size_t TSize)138   void grow_pod(size_t MinSize, size_t TSize) {
139     Base::grow_pod(getFirstEl(), MinSize, TSize);
140   }
141 
142   /// Return true if this is a smallvector which has not had dynamic
143   /// memory allocated for it.
isSmall()144   bool isSmall() const { return this->BeginX == getFirstEl(); }
145 
146   /// Put this vector in a state of being small.
resetToSmall()147   void resetToSmall() {
148     this->BeginX = getFirstEl();
149     this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
150   }
151 
152   /// Return true if V is an internal reference to the given range.
isReferenceToRange(const void * V,const void * First,const void * Last)153   bool isReferenceToRange(const void *V, const void *First, const void *Last) const {
154     // Use std::less to avoid UB.
155     std::less<> LessThan;
156     return !LessThan(V, First) && LessThan(V, Last);
157   }
158 
159   /// Return true if V is an internal reference to this vector.
isReferenceToStorage(const void * V)160   bool isReferenceToStorage(const void *V) const {
161     return isReferenceToRange(V, this->begin(), this->end());
162   }
163 
164   /// Return true if First and Last form a valid (possibly empty) range in this
165   /// vector's storage.
isRangeInStorage(const void * First,const void * Last)166   bool isRangeInStorage(const void *First, const void *Last) const {
167     // Use std::less to avoid UB.
168     std::less<> LessThan;
169     return !LessThan(First, this->begin()) && !LessThan(Last, First) &&
170            !LessThan(this->end(), Last);
171   }
172 
173   /// Return true unless Elt will be invalidated by resizing the vector to
174   /// NewSize.
isSafeToReferenceAfterResize(const void * Elt,size_t NewSize)175   bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
176     // Past the end.
177     if (LLVM_LIKELY(!isReferenceToStorage(Elt)))
178       return true;
179 
180     // Return false if Elt will be destroyed by shrinking.
181     if (NewSize <= this->size())
182       return Elt < this->begin() + NewSize;
183 
184     // Return false if we need to grow.
185     return NewSize <= this->capacity();
186   }
187 
188   /// Check whether Elt will be invalidated by resizing the vector to NewSize.
assertSafeToReferenceAfterResize(const void * Elt,size_t NewSize)189   void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
190     assert(isSafeToReferenceAfterResize(Elt, NewSize) &&
191            "Attempting to reference an element of the vector in an operation "
192            "that invalidates it");
193   }
194 
195   /// Check whether Elt will be invalidated by increasing the size of the
196   /// vector by N.
197   void assertSafeToAdd(const void *Elt, size_t N = 1) {
198     this->assertSafeToReferenceAfterResize(Elt, this->size() + N);
199   }
200 
201   /// Check whether any part of the range will be invalidated by clearing.
assertSafeToReferenceAfterClear(const T * From,const T * To)202   void assertSafeToReferenceAfterClear(const T *From, const T *To) {
203     if (From == To)
204       return;
205     this->assertSafeToReferenceAfterResize(From, 0);
206     this->assertSafeToReferenceAfterResize(To - 1, 0);
207   }
208   template <
209       class ItTy,
210       std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
211                        bool> = false>
assertSafeToReferenceAfterClear(ItTy,ItTy)212   void assertSafeToReferenceAfterClear(ItTy, ItTy) {}
213 
214   /// Check whether any part of the range will be invalidated by growing.
assertSafeToAddRange(const T * From,const T * To)215   void assertSafeToAddRange(const T *From, const T *To) {
216     if (From == To)
217       return;
218     this->assertSafeToAdd(From, To - From);
219     this->assertSafeToAdd(To - 1, To - From);
220   }
221   template <
222       class ItTy,
223       std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
224                        bool> = false>
assertSafeToAddRange(ItTy,ItTy)225   void assertSafeToAddRange(ItTy, ItTy) {}
226 
227   /// Reserve enough space to add one element, and return the updated element
228   /// pointer in case it was a reference to the storage.
229   template <class U>
reserveForParamAndGetAddressImpl(U * This,const T & Elt,size_t N)230   static const T *reserveForParamAndGetAddressImpl(U *This, const T &Elt,
231                                                    size_t N) {
232     size_t NewSize = This->size() + N;
233     if (LLVM_LIKELY(NewSize <= This->capacity()))
234       return &Elt;
235 
236     bool ReferencesStorage = false;
237     int64_t Index = -1;
238     if (!U::TakesParamByValue) {
239       if (LLVM_UNLIKELY(This->isReferenceToStorage(&Elt))) {
240         ReferencesStorage = true;
241         Index = &Elt - This->begin();
242       }
243     }
244     This->grow(NewSize);
245     return ReferencesStorage ? This->begin() + Index : &Elt;
246   }
247 
248 public:
249   using size_type = size_t;
250   using difference_type = ptrdiff_t;
251   using value_type = T;
252   using iterator = T *;
253   using const_iterator = const T *;
254 
255   using const_reverse_iterator = std::reverse_iterator<const_iterator>;
256   using reverse_iterator = std::reverse_iterator<iterator>;
257 
258   using reference = T &;
259   using const_reference = const T &;
260   using pointer = T *;
261   using const_pointer = const T *;
262 
263   using Base::capacity;
264   using Base::empty;
265   using Base::size;
266 
267   // forward iterator creation methods.
begin()268   iterator begin() { return (iterator)this->BeginX; }
begin()269   const_iterator begin() const { return (const_iterator)this->BeginX; }
end()270   iterator end() { return begin() + size(); }
end()271   const_iterator end() const { return begin() + size(); }
272 
273   // reverse iterator creation methods.
rbegin()274   reverse_iterator rbegin()            { return reverse_iterator(end()); }
rbegin()275   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
rend()276   reverse_iterator rend()              { return reverse_iterator(begin()); }
rend()277   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
278 
size_in_bytes()279   size_type size_in_bytes() const { return size() * sizeof(T); }
max_size()280   size_type max_size() const {
281     return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
282   }
283 
capacity_in_bytes()284   size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
285 
286   /// Return a pointer to the vector's buffer, even if empty().
data()287   pointer data() { return pointer(begin()); }
288   /// Return a pointer to the vector's buffer, even if empty().
data()289   const_pointer data() const { return const_pointer(begin()); }
290 
291   reference operator[](size_type idx) {
292     assert(idx < size());
293     return begin()[idx];
294   }
295   const_reference operator[](size_type idx) const {
296     assert(idx < size());
297     return begin()[idx];
298   }
299 
front()300   reference front() {
301     assert(!empty());
302     return begin()[0];
303   }
front()304   const_reference front() const {
305     assert(!empty());
306     return begin()[0];
307   }
308 
back()309   reference back() {
310     assert(!empty());
311     return end()[-1];
312   }
back()313   const_reference back() const {
314     assert(!empty());
315     return end()[-1];
316   }
317 };
318 
319 /// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
320 /// method implementations that are designed to work with non-trivial T's.
321 ///
322 /// We approximate is_trivially_copyable with trivial move/copy construction and
323 /// trivial destruction. While the standard doesn't specify that you're allowed
324 /// copy these types with memcpy, there is no way for the type to observe this.
325 /// This catches the important case of std::pair<POD, POD>, which is not
326 /// trivially assignable.
327 template <typename T, bool = (std::is_trivially_copy_constructible<T>::value) &&
328                              (std::is_trivially_move_constructible<T>::value) &&
329                              std::is_trivially_destructible<T>::value>
330 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
331   friend class SmallVectorTemplateCommon<T>;
332 
333 protected:
334   static constexpr bool TakesParamByValue = false;
335   using ValueParamT = const T &;
336 
SmallVectorTemplateBase(size_t Size)337   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
338 
destroy_range(T * S,T * E)339   static void destroy_range(T *S, T *E) {
340     while (S != E) {
341       --E;
342       E->~T();
343     }
344   }
345 
346   /// Move the range [I, E) into the uninitialized memory starting with "Dest",
347   /// constructing elements as needed.
348   template<typename It1, typename It2>
uninitialized_move(It1 I,It1 E,It2 Dest)349   static void uninitialized_move(It1 I, It1 E, It2 Dest) {
350     std::uninitialized_move(I, E, Dest);
351   }
352 
353   /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
354   /// constructing elements as needed.
355   template<typename It1, typename It2>
uninitialized_copy(It1 I,It1 E,It2 Dest)356   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
357     std::uninitialized_copy(I, E, Dest);
358   }
359 
360   /// Grow the allocated memory (without initializing new elements), doubling
361   /// the size of the allocated memory. Guarantees space for at least one more
362   /// element, or MinSize more elements if specified.
363   void grow(size_t MinSize = 0);
364 
365   /// Create a new allocation big enough for \p MinSize and pass back its size
366   /// in \p NewCapacity. This is the first section of \a grow().
367   T *mallocForGrow(size_t MinSize, size_t &NewCapacity);
368 
369   /// Move existing elements over to the new allocation \p NewElts, the middle
370   /// section of \a grow().
371   void moveElementsForGrow(T *NewElts);
372 
373   /// Transfer ownership of the allocation, finishing up \a grow().
374   void takeAllocationForGrow(T *NewElts, size_t NewCapacity);
375 
376   /// Reserve enough space to add one element, and return the updated element
377   /// pointer in case it was a reference to the storage.
378   const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
379     return this->reserveForParamAndGetAddressImpl(this, Elt, N);
380   }
381 
382   /// Reserve enough space to add one element, and return the updated element
383   /// pointer in case it was a reference to the storage.
384   T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
385     return const_cast<T *>(
386         this->reserveForParamAndGetAddressImpl(this, Elt, N));
387   }
388 
forward_value_param(T && V)389   static T &&forward_value_param(T &&V) { return std::move(V); }
forward_value_param(const T & V)390   static const T &forward_value_param(const T &V) { return V; }
391 
growAndAssign(size_t NumElts,const T & Elt)392   void growAndAssign(size_t NumElts, const T &Elt) {
393     // Grow manually in case Elt is an internal reference.
394     size_t NewCapacity;
395     T *NewElts = mallocForGrow(NumElts, NewCapacity);
396     std::uninitialized_fill_n(NewElts, NumElts, Elt);
397     this->destroy_range(this->begin(), this->end());
398     takeAllocationForGrow(NewElts, NewCapacity);
399     this->set_size(NumElts);
400   }
401 
growAndEmplaceBack(ArgTypes &&...Args)402   template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
403     // Grow manually in case one of Args is an internal reference.
404     size_t NewCapacity;
405     T *NewElts = mallocForGrow(0, NewCapacity);
406     ::new ((void *)(NewElts + this->size())) T(std::forward<ArgTypes>(Args)...);
407     moveElementsForGrow(NewElts);
408     takeAllocationForGrow(NewElts, NewCapacity);
409     this->set_size(this->size() + 1);
410     return this->back();
411   }
412 
413 public:
push_back(const T & Elt)414   void push_back(const T &Elt) {
415     const T *EltPtr = reserveForParamAndGetAddress(Elt);
416     ::new ((void *)this->end()) T(*EltPtr);
417     this->set_size(this->size() + 1);
418   }
419 
push_back(T && Elt)420   void push_back(T &&Elt) {
421     T *EltPtr = reserveForParamAndGetAddress(Elt);
422     ::new ((void *)this->end()) T(::std::move(*EltPtr));
423     this->set_size(this->size() + 1);
424   }
425 
pop_back()426   void pop_back() {
427     this->set_size(this->size() - 1);
428     this->end()->~T();
429   }
430 };
431 
432 // Define this out-of-line to dissuade the C++ compiler from inlining it.
433 template <typename T, bool TriviallyCopyable>
grow(size_t MinSize)434 void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
435   size_t NewCapacity;
436   T *NewElts = mallocForGrow(MinSize, NewCapacity);
437   moveElementsForGrow(NewElts);
438   takeAllocationForGrow(NewElts, NewCapacity);
439 }
440 
441 template <typename T, bool TriviallyCopyable>
mallocForGrow(size_t MinSize,size_t & NewCapacity)442 T *SmallVectorTemplateBase<T, TriviallyCopyable>::mallocForGrow(
443     size_t MinSize, size_t &NewCapacity) {
444   return static_cast<T *>(
445       SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow(
446           this->getFirstEl(), MinSize, sizeof(T), NewCapacity));
447 }
448 
449 // Define this out-of-line to dissuade the C++ compiler from inlining it.
450 template <typename T, bool TriviallyCopyable>
moveElementsForGrow(T * NewElts)451 void SmallVectorTemplateBase<T, TriviallyCopyable>::moveElementsForGrow(
452     T *NewElts) {
453   // Move the elements over.
454   this->uninitialized_move(this->begin(), this->end(), NewElts);
455 
456   // Destroy the original elements.
457   destroy_range(this->begin(), this->end());
458 }
459 
460 // Define this out-of-line to dissuade the C++ compiler from inlining it.
461 template <typename T, bool TriviallyCopyable>
takeAllocationForGrow(T * NewElts,size_t NewCapacity)462 void SmallVectorTemplateBase<T, TriviallyCopyable>::takeAllocationForGrow(
463     T *NewElts, size_t NewCapacity) {
464   // If this wasn't grown from the inline copy, deallocate the old space.
465   if (!this->isSmall())
466     free(this->begin());
467 
468   this->set_allocation_range(NewElts, NewCapacity);
469 }
470 
471 /// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
472 /// method implementations that are designed to work with trivially copyable
473 /// T's. This allows using memcpy in place of copy/move construction and
474 /// skipping destruction.
475 template <typename T>
476 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
477   friend class SmallVectorTemplateCommon<T>;
478 
479 protected:
480   /// True if it's cheap enough to take parameters by value. Doing so avoids
481   /// overhead related to mitigations for reference invalidation.
482   static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void *);
483 
484   /// Either const T& or T, depending on whether it's cheap enough to take
485   /// parameters by value.
486   using ValueParamT = std::conditional_t<TakesParamByValue, T, const T &>;
487 
SmallVectorTemplateBase(size_t Size)488   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
489 
490   // No need to do a destroy loop for POD's.
destroy_range(T *,T *)491   static void destroy_range(T *, T *) {}
492 
493   /// Move the range [I, E) onto the uninitialized memory
494   /// starting with "Dest", constructing elements into it as needed.
495   template<typename It1, typename It2>
uninitialized_move(It1 I,It1 E,It2 Dest)496   static void uninitialized_move(It1 I, It1 E, It2 Dest) {
497     // Just do a copy.
498     uninitialized_copy(I, E, Dest);
499   }
500 
501   /// Copy the range [I, E) onto the uninitialized memory
502   /// starting with "Dest", constructing elements into it as needed.
503   template<typename It1, typename It2>
uninitialized_copy(It1 I,It1 E,It2 Dest)504   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
505     // Arbitrary iterator types; just use the basic implementation.
506     std::uninitialized_copy(I, E, Dest);
507   }
508 
509   /// Copy the range [I, E) onto the uninitialized memory
510   /// starting with "Dest", constructing elements into it as needed.
511   template <typename T1, typename T2>
512   static void uninitialized_copy(
513       T1 *I, T1 *E, T2 *Dest,
514       std::enable_if_t<std::is_same<std::remove_const_t<T1>, T2>::value> * =
515           nullptr) {
516     // Use memcpy for PODs iterated by pointers (which includes SmallVector
517     // iterators): std::uninitialized_copy optimizes to memmove, but we can
518     // use memcpy here. Note that I and E are iterators and thus might be
519     // invalid for memcpy if they are equal.
520     if (I != E)
521       std::memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
522   }
523 
524   /// Double the size of the allocated memory, guaranteeing space for at
525   /// least one more element or MinSize if specified.
526   void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
527 
528   /// Reserve enough space to add one element, and return the updated element
529   /// pointer in case it was a reference to the storage.
530   const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
531     return this->reserveForParamAndGetAddressImpl(this, Elt, N);
532   }
533 
534   /// Reserve enough space to add one element, and return the updated element
535   /// pointer in case it was a reference to the storage.
536   T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
537     return const_cast<T *>(
538         this->reserveForParamAndGetAddressImpl(this, Elt, N));
539   }
540 
541   /// Copy \p V or return a reference, depending on \a ValueParamT.
forward_value_param(ValueParamT V)542   static ValueParamT forward_value_param(ValueParamT V) { return V; }
543 
growAndAssign(size_t NumElts,T Elt)544   void growAndAssign(size_t NumElts, T Elt) {
545     // Elt has been copied in case it's an internal reference, side-stepping
546     // reference invalidation problems without losing the realloc optimization.
547     this->set_size(0);
548     this->grow(NumElts);
549     std::uninitialized_fill_n(this->begin(), NumElts, Elt);
550     this->set_size(NumElts);
551   }
552 
growAndEmplaceBack(ArgTypes &&...Args)553   template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
554     // Use push_back with a copy in case Args has an internal reference,
555     // side-stepping reference invalidation problems without losing the realloc
556     // optimization.
557     push_back(T(std::forward<ArgTypes>(Args)...));
558     return this->back();
559   }
560 
561 public:
push_back(ValueParamT Elt)562   void push_back(ValueParamT Elt) {
563     const T *EltPtr = reserveForParamAndGetAddress(Elt);
564     std::memcpy(reinterpret_cast<void *>(this->end()), EltPtr, sizeof(T));
565     this->set_size(this->size() + 1);
566   }
567 
pop_back()568   void pop_back() { this->set_size(this->size() - 1); }
569 };
570 
571 /// This class consists of common code factored out of the SmallVector class to
572 /// reduce code duplication based on the SmallVector 'N' template parameter.
573 template <typename T>
574 class SmallVectorImpl : public SmallVectorTemplateBase<T> {
575   using SuperClass = SmallVectorTemplateBase<T>;
576 
577 public:
578   using iterator = typename SuperClass::iterator;
579   using const_iterator = typename SuperClass::const_iterator;
580   using reference = typename SuperClass::reference;
581   using size_type = typename SuperClass::size_type;
582 
583 protected:
584   using SmallVectorTemplateBase<T>::TakesParamByValue;
585   using ValueParamT = typename SuperClass::ValueParamT;
586 
587   // Default ctor - Initialize to empty.
SmallVectorImpl(unsigned N)588   explicit SmallVectorImpl(unsigned N)
589       : SmallVectorTemplateBase<T>(N) {}
590 
assignRemote(SmallVectorImpl && RHS)591   void assignRemote(SmallVectorImpl &&RHS) {
592     this->destroy_range(this->begin(), this->end());
593     if (!this->isSmall())
594       free(this->begin());
595     this->BeginX = RHS.BeginX;
596     this->Size = RHS.Size;
597     this->Capacity = RHS.Capacity;
598     RHS.resetToSmall();
599   }
600 
~SmallVectorImpl()601   ~SmallVectorImpl() {
602     // Subclass has already destructed this vector's elements.
603     // If this wasn't grown from the inline copy, deallocate the old space.
604     if (!this->isSmall())
605       free(this->begin());
606   }
607 
608 public:
609   SmallVectorImpl(const SmallVectorImpl &) = delete;
610 
clear()611   void clear() {
612     this->destroy_range(this->begin(), this->end());
613     this->Size = 0;
614   }
615 
616 private:
617   // Make set_size() private to avoid misuse in subclasses.
618   using SuperClass::set_size;
619 
resizeImpl(size_type N)620   template <bool ForOverwrite> void resizeImpl(size_type N) {
621     if (N == this->size())
622       return;
623 
624     if (N < this->size()) {
625       this->truncate(N);
626       return;
627     }
628 
629     this->reserve(N);
630     for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
631       if (ForOverwrite)
632         new (&*I) T;
633       else
634         new (&*I) T();
635     this->set_size(N);
636   }
637 
638 public:
resize(size_type N)639   void resize(size_type N) { resizeImpl<false>(N); }
640 
641   /// Like resize, but \ref T is POD, the new values won't be initialized.
resize_for_overwrite(size_type N)642   void resize_for_overwrite(size_type N) { resizeImpl<true>(N); }
643 
644   /// Like resize, but requires that \p N is less than \a size().
truncate(size_type N)645   void truncate(size_type N) {
646     assert(this->size() >= N && "Cannot increase size with truncate");
647     this->destroy_range(this->begin() + N, this->end());
648     this->set_size(N);
649   }
650 
resize(size_type N,ValueParamT NV)651   void resize(size_type N, ValueParamT NV) {
652     if (N == this->size())
653       return;
654 
655     if (N < this->size()) {
656       this->truncate(N);
657       return;
658     }
659 
660     // N > this->size(). Defer to append.
661     this->append(N - this->size(), NV);
662   }
663 
reserve(size_type N)664   void reserve(size_type N) {
665     if (this->capacity() < N)
666       this->grow(N);
667   }
668 
pop_back_n(size_type NumItems)669   void pop_back_n(size_type NumItems) {
670     assert(this->size() >= NumItems);
671     truncate(this->size() - NumItems);
672   }
673 
pop_back_val()674   [[nodiscard]] T pop_back_val() {
675     T Result = ::std::move(this->back());
676     this->pop_back();
677     return Result;
678   }
679 
680   void swap(SmallVectorImpl &RHS);
681 
682   /// Add the specified range to the end of the SmallVector.
683   template <typename ItTy, typename = EnableIfConvertibleToInputIterator<ItTy>>
append(ItTy in_start,ItTy in_end)684   void append(ItTy in_start, ItTy in_end) {
685     this->assertSafeToAddRange(in_start, in_end);
686     size_type NumInputs = std::distance(in_start, in_end);
687     this->reserve(this->size() + NumInputs);
688     this->uninitialized_copy(in_start, in_end, this->end());
689     this->set_size(this->size() + NumInputs);
690   }
691 
692   /// Append \p NumInputs copies of \p Elt to the end.
append(size_type NumInputs,ValueParamT Elt)693   void append(size_type NumInputs, ValueParamT Elt) {
694     const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs);
695     std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr);
696     this->set_size(this->size() + NumInputs);
697   }
698 
append(std::initializer_list<T> IL)699   void append(std::initializer_list<T> IL) {
700     append(IL.begin(), IL.end());
701   }
702 
append(const SmallVectorImpl & RHS)703   void append(const SmallVectorImpl &RHS) { append(RHS.begin(), RHS.end()); }
704 
assign(size_type NumElts,ValueParamT Elt)705   void assign(size_type NumElts, ValueParamT Elt) {
706     // Note that Elt could be an internal reference.
707     if (NumElts > this->capacity()) {
708       this->growAndAssign(NumElts, Elt);
709       return;
710     }
711 
712     // Assign over existing elements.
713     std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt);
714     if (NumElts > this->size())
715       std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt);
716     else if (NumElts < this->size())
717       this->destroy_range(this->begin() + NumElts, this->end());
718     this->set_size(NumElts);
719   }
720 
721   // FIXME: Consider assigning over existing elements, rather than clearing &
722   // re-initializing them - for all assign(...) variants.
723 
724   template <typename ItTy, typename = EnableIfConvertibleToInputIterator<ItTy>>
assign(ItTy in_start,ItTy in_end)725   void assign(ItTy in_start, ItTy in_end) {
726     this->assertSafeToReferenceAfterClear(in_start, in_end);
727     clear();
728     append(in_start, in_end);
729   }
730 
assign(std::initializer_list<T> IL)731   void assign(std::initializer_list<T> IL) {
732     clear();
733     append(IL);
734   }
735 
assign(const SmallVectorImpl & RHS)736   void assign(const SmallVectorImpl &RHS) { assign(RHS.begin(), RHS.end()); }
737 
erase(const_iterator CI)738   iterator erase(const_iterator CI) {
739     // Just cast away constness because this is a non-const member function.
740     iterator I = const_cast<iterator>(CI);
741 
742     assert(this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds.");
743 
744     iterator N = I;
745     // Shift all elts down one.
746     std::move(I+1, this->end(), I);
747     // Drop the last elt.
748     this->pop_back();
749     return(N);
750   }
751 
erase(const_iterator CS,const_iterator CE)752   iterator erase(const_iterator CS, const_iterator CE) {
753     // Just cast away constness because this is a non-const member function.
754     iterator S = const_cast<iterator>(CS);
755     iterator E = const_cast<iterator>(CE);
756 
757     assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds.");
758 
759     iterator N = S;
760     // Shift all elts down.
761     iterator I = std::move(E, this->end(), S);
762     // Drop the last elts.
763     this->destroy_range(I, this->end());
764     this->set_size(I - this->begin());
765     return(N);
766   }
767 
768 private:
insert_one_impl(iterator I,ArgType && Elt)769   template <class ArgType> iterator insert_one_impl(iterator I, ArgType &&Elt) {
770     // Callers ensure that ArgType is derived from T.
771     static_assert(
772         std::is_same<std::remove_const_t<std::remove_reference_t<ArgType>>,
773                      T>::value,
774         "ArgType must be derived from T!");
775 
776     if (I == this->end()) {  // Important special case for empty vector.
777       this->push_back(::std::forward<ArgType>(Elt));
778       return this->end()-1;
779     }
780 
781     assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
782 
783     // Grow if necessary.
784     size_t Index = I - this->begin();
785     std::remove_reference_t<ArgType> *EltPtr =
786         this->reserveForParamAndGetAddress(Elt);
787     I = this->begin() + Index;
788 
789     ::new ((void*) this->end()) T(::std::move(this->back()));
790     // Push everything else over.
791     std::move_backward(I, this->end()-1, this->end());
792     this->set_size(this->size() + 1);
793 
794     // If we just moved the element we're inserting, be sure to update
795     // the reference (never happens if TakesParamByValue).
796     static_assert(!TakesParamByValue || std::is_same<ArgType, T>::value,
797                   "ArgType must be 'T' when taking by value!");
798     if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end()))
799       ++EltPtr;
800 
801     *I = ::std::forward<ArgType>(*EltPtr);
802     return I;
803   }
804 
805 public:
insert(iterator I,T && Elt)806   iterator insert(iterator I, T &&Elt) {
807     return insert_one_impl(I, this->forward_value_param(std::move(Elt)));
808   }
809 
insert(iterator I,const T & Elt)810   iterator insert(iterator I, const T &Elt) {
811     return insert_one_impl(I, this->forward_value_param(Elt));
812   }
813 
insert(iterator I,size_type NumToInsert,ValueParamT Elt)814   iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) {
815     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
816     size_t InsertElt = I - this->begin();
817 
818     if (I == this->end()) {  // Important special case for empty vector.
819       append(NumToInsert, Elt);
820       return this->begin()+InsertElt;
821     }
822 
823     assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
824 
825     // Ensure there is enough space, and get the (maybe updated) address of
826     // Elt.
827     const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert);
828 
829     // Uninvalidate the iterator.
830     I = this->begin()+InsertElt;
831 
832     // If there are more elements between the insertion point and the end of the
833     // range than there are being inserted, we can use a simple approach to
834     // insertion.  Since we already reserved space, we know that this won't
835     // reallocate the vector.
836     if (size_t(this->end()-I) >= NumToInsert) {
837       T *OldEnd = this->end();
838       append(std::move_iterator<iterator>(this->end() - NumToInsert),
839              std::move_iterator<iterator>(this->end()));
840 
841       // Copy the existing elements that get replaced.
842       std::move_backward(I, OldEnd-NumToInsert, OldEnd);
843 
844       // If we just moved the element we're inserting, be sure to update
845       // the reference (never happens if TakesParamByValue).
846       if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
847         EltPtr += NumToInsert;
848 
849       std::fill_n(I, NumToInsert, *EltPtr);
850       return I;
851     }
852 
853     // Otherwise, we're inserting more elements than exist already, and we're
854     // not inserting at the end.
855 
856     // Move over the elements that we're about to overwrite.
857     T *OldEnd = this->end();
858     this->set_size(this->size() + NumToInsert);
859     size_t NumOverwritten = OldEnd-I;
860     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
861 
862     // If we just moved the element we're inserting, be sure to update
863     // the reference (never happens if TakesParamByValue).
864     if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
865       EltPtr += NumToInsert;
866 
867     // Replace the overwritten part.
868     std::fill_n(I, NumOverwritten, *EltPtr);
869 
870     // Insert the non-overwritten middle part.
871     std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr);
872     return I;
873   }
874 
875   template <typename ItTy, typename = EnableIfConvertibleToInputIterator<ItTy>>
insert(iterator I,ItTy From,ItTy To)876   iterator insert(iterator I, ItTy From, ItTy To) {
877     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
878     size_t InsertElt = I - this->begin();
879 
880     if (I == this->end()) {  // Important special case for empty vector.
881       append(From, To);
882       return this->begin()+InsertElt;
883     }
884 
885     assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
886 
887     // Check that the reserve that follows doesn't invalidate the iterators.
888     this->assertSafeToAddRange(From, To);
889 
890     size_t NumToInsert = std::distance(From, To);
891 
892     // Ensure there is enough space.
893     reserve(this->size() + NumToInsert);
894 
895     // Uninvalidate the iterator.
896     I = this->begin()+InsertElt;
897 
898     // If there are more elements between the insertion point and the end of the
899     // range than there are being inserted, we can use a simple approach to
900     // insertion.  Since we already reserved space, we know that this won't
901     // reallocate the vector.
902     if (size_t(this->end()-I) >= NumToInsert) {
903       T *OldEnd = this->end();
904       append(std::move_iterator<iterator>(this->end() - NumToInsert),
905              std::move_iterator<iterator>(this->end()));
906 
907       // Copy the existing elements that get replaced.
908       std::move_backward(I, OldEnd-NumToInsert, OldEnd);
909 
910       std::copy(From, To, I);
911       return I;
912     }
913 
914     // Otherwise, we're inserting more elements than exist already, and we're
915     // not inserting at the end.
916 
917     // Move over the elements that we're about to overwrite.
918     T *OldEnd = this->end();
919     this->set_size(this->size() + NumToInsert);
920     size_t NumOverwritten = OldEnd-I;
921     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
922 
923     // Replace the overwritten part.
924     for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
925       *J = *From;
926       ++J; ++From;
927     }
928 
929     // Insert the non-overwritten middle part.
930     this->uninitialized_copy(From, To, OldEnd);
931     return I;
932   }
933 
insert(iterator I,std::initializer_list<T> IL)934   void insert(iterator I, std::initializer_list<T> IL) {
935     insert(I, IL.begin(), IL.end());
936   }
937 
emplace_back(ArgTypes &&...Args)938   template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
939     if (LLVM_UNLIKELY(this->size() >= this->capacity()))
940       return this->growAndEmplaceBack(std::forward<ArgTypes>(Args)...);
941 
942     ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
943     this->set_size(this->size() + 1);
944     return this->back();
945   }
946 
947   SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
948 
949   SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
950 
951   bool operator==(const SmallVectorImpl &RHS) const {
952     if (this->size() != RHS.size()) return false;
953     return std::equal(this->begin(), this->end(), RHS.begin());
954   }
955   bool operator!=(const SmallVectorImpl &RHS) const {
956     return !(*this == RHS);
957   }
958 
959   bool operator<(const SmallVectorImpl &RHS) const {
960     return std::lexicographical_compare(this->begin(), this->end(),
961                                         RHS.begin(), RHS.end());
962   }
963   bool operator>(const SmallVectorImpl &RHS) const { return RHS < *this; }
964   bool operator<=(const SmallVectorImpl &RHS) const { return !(*this > RHS); }
965   bool operator>=(const SmallVectorImpl &RHS) const { return !(*this < RHS); }
966 };
967 
968 template <typename T>
swap(SmallVectorImpl<T> & RHS)969 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
970   if (this == &RHS) return;
971 
972   // We can only avoid copying elements if neither vector is small.
973   if (!this->isSmall() && !RHS.isSmall()) {
974     std::swap(this->BeginX, RHS.BeginX);
975     std::swap(this->Size, RHS.Size);
976     std::swap(this->Capacity, RHS.Capacity);
977     return;
978   }
979   this->reserve(RHS.size());
980   RHS.reserve(this->size());
981 
982   // Swap the shared elements.
983   size_t NumShared = this->size();
984   if (NumShared > RHS.size()) NumShared = RHS.size();
985   for (size_type i = 0; i != NumShared; ++i)
986     std::swap((*this)[i], RHS[i]);
987 
988   // Copy over the extra elts.
989   if (this->size() > RHS.size()) {
990     size_t EltDiff = this->size() - RHS.size();
991     this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
992     RHS.set_size(RHS.size() + EltDiff);
993     this->destroy_range(this->begin()+NumShared, this->end());
994     this->set_size(NumShared);
995   } else if (RHS.size() > this->size()) {
996     size_t EltDiff = RHS.size() - this->size();
997     this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
998     this->set_size(this->size() + EltDiff);
999     this->destroy_range(RHS.begin()+NumShared, RHS.end());
1000     RHS.set_size(NumShared);
1001   }
1002 }
1003 
1004 template <typename T>
1005 SmallVectorImpl<T> &SmallVectorImpl<T>::
1006   operator=(const SmallVectorImpl<T> &RHS) {
1007   // Avoid self-assignment.
1008   if (this == &RHS) return *this;
1009 
1010   // If we already have sufficient space, assign the common elements, then
1011   // destroy any excess.
1012   size_t RHSSize = RHS.size();
1013   size_t CurSize = this->size();
1014   if (CurSize >= RHSSize) {
1015     // Assign common elements.
1016     iterator NewEnd;
1017     if (RHSSize)
1018       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
1019     else
1020       NewEnd = this->begin();
1021 
1022     // Destroy excess elements.
1023     this->destroy_range(NewEnd, this->end());
1024 
1025     // Trim.
1026     this->set_size(RHSSize);
1027     return *this;
1028   }
1029 
1030   // If we have to grow to have enough elements, destroy the current elements.
1031   // This allows us to avoid copying them during the grow.
1032   // FIXME: don't do this if they're efficiently moveable.
1033   if (this->capacity() < RHSSize) {
1034     // Destroy current elements.
1035     this->clear();
1036     CurSize = 0;
1037     this->grow(RHSSize);
1038   } else if (CurSize) {
1039     // Otherwise, use assignment for the already-constructed elements.
1040     std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
1041   }
1042 
1043   // Copy construct the new elements in place.
1044   this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
1045                            this->begin()+CurSize);
1046 
1047   // Set end.
1048   this->set_size(RHSSize);
1049   return *this;
1050 }
1051 
1052 template <typename T>
1053 SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
1054   // Avoid self-assignment.
1055   if (this == &RHS) return *this;
1056 
1057   // If the RHS isn't small, clear this vector and then steal its buffer.
1058   if (!RHS.isSmall()) {
1059     this->assignRemote(std::move(RHS));
1060     return *this;
1061   }
1062 
1063   // If we already have sufficient space, assign the common elements, then
1064   // destroy any excess.
1065   size_t RHSSize = RHS.size();
1066   size_t CurSize = this->size();
1067   if (CurSize >= RHSSize) {
1068     // Assign common elements.
1069     iterator NewEnd = this->begin();
1070     if (RHSSize)
1071       NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
1072 
1073     // Destroy excess elements and trim the bounds.
1074     this->destroy_range(NewEnd, this->end());
1075     this->set_size(RHSSize);
1076 
1077     // Clear the RHS.
1078     RHS.clear();
1079 
1080     return *this;
1081   }
1082 
1083   // If we have to grow to have enough elements, destroy the current elements.
1084   // This allows us to avoid copying them during the grow.
1085   // FIXME: this may not actually make any sense if we can efficiently move
1086   // elements.
1087   if (this->capacity() < RHSSize) {
1088     // Destroy current elements.
1089     this->clear();
1090     CurSize = 0;
1091     this->grow(RHSSize);
1092   } else if (CurSize) {
1093     // Otherwise, use assignment for the already-constructed elements.
1094     std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
1095   }
1096 
1097   // Move-construct the new elements in place.
1098   this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
1099                            this->begin()+CurSize);
1100 
1101   // Set end.
1102   this->set_size(RHSSize);
1103 
1104   RHS.clear();
1105   return *this;
1106 }
1107 
1108 /// Storage for the SmallVector elements.  This is specialized for the N=0 case
1109 /// to avoid allocating unnecessary storage.
1110 template <typename T, unsigned N>
1111 struct SmallVectorStorage {
1112   alignas(T) char InlineElts[N * sizeof(T)];
1113 };
1114 
1115 /// We need the storage to be properly aligned even for small-size of 0 so that
1116 /// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
1117 /// well-defined.
1118 template <typename T> struct alignas(T) SmallVectorStorage<T, 0> {};
1119 
1120 /// Forward declaration of SmallVector so that
1121 /// calculateSmallVectorDefaultInlinedElements can reference
1122 /// `sizeof(SmallVector<T, 0>)`.
1123 template <typename T, unsigned N> class LLVM_GSL_OWNER SmallVector;
1124 
1125 /// Helper class for calculating the default number of inline elements for
1126 /// `SmallVector<T>`.
1127 ///
1128 /// This should be migrated to a constexpr function when our minimum
1129 /// compiler support is enough for multi-statement constexpr functions.
1130 template <typename T> struct CalculateSmallVectorDefaultInlinedElements {
1131   // Parameter controlling the default number of inlined elements
1132   // for `SmallVector<T>`.
1133   //
1134   // The default number of inlined elements ensures that
1135   // 1. There is at least one inlined element.
1136   // 2. `sizeof(SmallVector<T>) <= kPreferredSmallVectorSizeof` unless
1137   // it contradicts 1.
1138   static constexpr size_t kPreferredSmallVectorSizeof = 64;
1139 
1140   // static_assert that sizeof(T) is not "too big".
1141   //
1142   // Because our policy guarantees at least one inlined element, it is possible
1143   // for an arbitrarily large inlined element to allocate an arbitrarily large
1144   // amount of inline storage. We generally consider it an antipattern for a
1145   // SmallVector to allocate an excessive amount of inline storage, so we want
1146   // to call attention to these cases and make sure that users are making an
1147   // intentional decision if they request a lot of inline storage.
1148   //
1149   // We want this assertion to trigger in pathological cases, but otherwise
1150   // not be too easy to hit. To accomplish that, the cutoff is actually somewhat
1151   // larger than kPreferredSmallVectorSizeof (otherwise,
1152   // `SmallVector<SmallVector<T>>` would be one easy way to trip it, and that
1153   // pattern seems useful in practice).
1154   //
1155   // One wrinkle is that this assertion is in theory non-portable, since
1156   // sizeof(T) is in general platform-dependent. However, we don't expect this
1157   // to be much of an issue, because most LLVM development happens on 64-bit
1158   // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for
1159   // 32-bit hosts, dodging the issue. The reverse situation, where development
1160   // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a
1161   // 64-bit host, is expected to be very rare.
1162   static_assert(
1163       sizeof(T) <= 256,
1164       "You are trying to use a default number of inlined elements for "
1165       "`SmallVector<T>` but `sizeof(T)` is really big! Please use an "
1166       "explicit number of inlined elements with `SmallVector<T, N>` to make "
1167       "sure you really want that much inline storage.");
1168 
1169   // Discount the size of the header itself when calculating the maximum inline
1170   // bytes.
1171   static constexpr size_t PreferredInlineBytes =
1172       kPreferredSmallVectorSizeof - sizeof(SmallVector<T, 0>);
1173   static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T);
1174   static constexpr size_t value =
1175       NumElementsThatFit == 0 ? 1 : NumElementsThatFit;
1176 };
1177 
1178 /// This is a 'vector' (really, a variable-sized array), optimized
1179 /// for the case when the array is small.  It contains some number of elements
1180 /// in-place, which allows it to avoid heap allocation when the actual number of
1181 /// elements is below that threshold.  This allows normal "small" cases to be
1182 /// fast without losing generality for large inputs.
1183 ///
1184 /// \note
1185 /// In the absence of a well-motivated choice for the number of inlined
1186 /// elements \p N, it is recommended to use \c SmallVector<T> (that is,
1187 /// omitting the \p N). This will choose a default number of inlined elements
1188 /// reasonable for allocation on the stack (for example, trying to keep \c
1189 /// sizeof(SmallVector<T>) around 64 bytes).
1190 ///
1191 /// \warning This does not attempt to be exception safe.
1192 ///
1193 /// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h
1194 template <typename T,
1195           unsigned N = CalculateSmallVectorDefaultInlinedElements<T>::value>
1196 class LLVM_GSL_OWNER SmallVector : public SmallVectorImpl<T>,
1197                                    SmallVectorStorage<T, N> {
1198 public:
1199   SmallVector() : SmallVectorImpl<T>(N) {}
1200 
1201   ~SmallVector() {
1202     // Destroy the constructed elements in the vector.
1203     this->destroy_range(this->begin(), this->end());
1204   }
1205 
1206   explicit SmallVector(size_t Size)
1207     : SmallVectorImpl<T>(N) {
1208     this->resize(Size);
1209   }
1210 
1211   SmallVector(size_t Size, const T &Value)
1212     : SmallVectorImpl<T>(N) {
1213     this->assign(Size, Value);
1214   }
1215 
1216   template <typename ItTy, typename = EnableIfConvertibleToInputIterator<ItTy>>
1217   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
1218     this->append(S, E);
1219   }
1220 
1221   template <typename RangeTy>
1222   explicit SmallVector(const iterator_range<RangeTy> &R)
1223       : SmallVectorImpl<T>(N) {
1224     this->append(R.begin(), R.end());
1225   }
1226 
1227   SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
1228     this->append(IL);
1229   }
1230 
1231   template <typename U,
1232             typename = std::enable_if_t<std::is_convertible<U, T>::value>>
1233   explicit SmallVector(ArrayRef<U> A) : SmallVectorImpl<T>(N) {
1234     this->append(A.begin(), A.end());
1235   }
1236 
1237   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
1238     if (!RHS.empty())
1239       SmallVectorImpl<T>::operator=(RHS);
1240   }
1241 
1242   SmallVector &operator=(const SmallVector &RHS) {
1243     SmallVectorImpl<T>::operator=(RHS);
1244     return *this;
1245   }
1246 
1247   SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
1248     if (!RHS.empty())
1249       SmallVectorImpl<T>::operator=(::std::move(RHS));
1250   }
1251 
1252   SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
1253     if (!RHS.empty())
1254       SmallVectorImpl<T>::operator=(::std::move(RHS));
1255   }
1256 
1257   SmallVector &operator=(SmallVector &&RHS) {
1258     if (N) {
1259       SmallVectorImpl<T>::operator=(::std::move(RHS));
1260       return *this;
1261     }
1262     // SmallVectorImpl<T>::operator= does not leverage N==0. Optimize the
1263     // case.
1264     if (this == &RHS)
1265       return *this;
1266     if (RHS.empty()) {
1267       this->destroy_range(this->begin(), this->end());
1268       this->Size = 0;
1269     } else {
1270       this->assignRemote(std::move(RHS));
1271     }
1272     return *this;
1273   }
1274 
1275   SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
1276     SmallVectorImpl<T>::operator=(::std::move(RHS));
1277     return *this;
1278   }
1279 
1280   SmallVector &operator=(std::initializer_list<T> IL) {
1281     this->assign(IL);
1282     return *this;
1283   }
1284 };
1285 
1286 template <typename T, unsigned N>
1287 inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
1288   return X.capacity_in_bytes();
1289 }
1290 
1291 template <typename RangeType>
1292 using ValueTypeFromRangeType =
1293     std::remove_const_t<std::remove_reference_t<decltype(*std::begin(
1294         std::declval<RangeType &>()))>>;
1295 
1296 /// Given a range of type R, iterate the entire range and return a
1297 /// SmallVector with elements of the vector.  This is useful, for example,
1298 /// when you want to iterate a range and then sort the results.
1299 template <unsigned Size, typename R>
1300 SmallVector<ValueTypeFromRangeType<R>, Size> to_vector(R &&Range) {
1301   return {std::begin(Range), std::end(Range)};
1302 }
1303 template <typename R>
1304 SmallVector<ValueTypeFromRangeType<R>> to_vector(R &&Range) {
1305   return {std::begin(Range), std::end(Range)};
1306 }
1307 
1308 template <typename Out, unsigned Size, typename R>
1309 SmallVector<Out, Size> to_vector_of(R &&Range) {
1310   return {std::begin(Range), std::end(Range)};
1311 }
1312 
1313 template <typename Out, typename R> SmallVector<Out> to_vector_of(R &&Range) {
1314   return {std::begin(Range), std::end(Range)};
1315 }
1316 
1317 // Explicit instantiations
1318 extern template class llvm::SmallVectorBase<uint32_t>;
1319 #if SIZE_MAX > UINT32_MAX
1320 extern template class llvm::SmallVectorBase<uint64_t>;
1321 #endif
1322 
1323 // Provide DenseMapInfo for SmallVector of a type which has info.
1324 template <typename T, unsigned N> struct DenseMapInfo<llvm::SmallVector<T, N>> {
1325   static SmallVector<T, N> getEmptyKey() {
1326     return {DenseMapInfo<T>::getEmptyKey()};
1327   }
1328 
1329   static SmallVector<T, N> getTombstoneKey() {
1330     return {DenseMapInfo<T>::getTombstoneKey()};
1331   }
1332 
1333   static unsigned getHashValue(const SmallVector<T, N> &V) {
1334     return static_cast<unsigned>(hash_combine_range(V));
1335   }
1336 
1337   static bool isEqual(const SmallVector<T, N> &LHS,
1338                       const SmallVector<T, N> &RHS) {
1339     return LHS == RHS;
1340   }
1341 };
1342 
1343 } // end namespace llvm
1344 
1345 namespace std {
1346 
1347   /// Implement std::swap in terms of SmallVector swap.
1348   template<typename T>
1349   inline void
1350   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
1351     LHS.swap(RHS);
1352   }
1353 
1354   /// Implement std::swap in terms of SmallVector swap.
1355   template<typename T, unsigned N>
1356   inline void
1357   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
1358     LHS.swap(RHS);
1359   }
1360 
1361 } // end namespace std
1362 
1363 #endif // LLVM_ADT_SMALLVECTOR_H
1364