1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/iterator_range.h"
18 #include "llvm/Support/AlignOf.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/type_traits.h"
22 #include <algorithm>
23 #include <cassert>
24 #include <cstddef>
25 #include <cstdlib>
26 #include <cstring>
27 #include <initializer_list>
28 #include <iterator>
29 #include <memory>
30 
31 namespace llvm {
32 
33 /// This is all the non-templated stuff common to all SmallVectors.
34 class SmallVectorBase {
35 protected:
36   void *BeginX, *EndX, *CapacityX;
37 
38 protected:
SmallVectorBase(void * FirstEl,size_t Size)39   SmallVectorBase(void *FirstEl, size_t Size)
40     : BeginX(FirstEl), EndX(FirstEl), CapacityX((char*)FirstEl+Size) {}
41 
42   /// This is an implementation of the grow() method which only works
43   /// on POD-like data types and is out of line to reduce code duplication.
44   void grow_pod(void *FirstEl, size_t MinSizeInBytes, size_t TSize);
45 
46 public:
47   /// This returns size()*sizeof(T).
size_in_bytes()48   size_t size_in_bytes() const {
49     return size_t((char*)EndX - (char*)BeginX);
50   }
51 
52   /// capacity_in_bytes - This returns capacity()*sizeof(T).
capacity_in_bytes()53   size_t capacity_in_bytes() const {
54     return size_t((char*)CapacityX - (char*)BeginX);
55   }
56 
empty()57   bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return BeginX == EndX; }
58 };
59 
60 template <typename T, unsigned N> struct SmallVectorStorage;
61 
62 /// This is the part of SmallVectorTemplateBase which does not depend on whether
63 /// the type T is a POD. The extra dummy template argument is used by ArrayRef
64 /// to avoid unnecessarily requiring T to be complete.
65 template <typename T, typename = void>
66 class SmallVectorTemplateCommon : public SmallVectorBase {
67 private:
68   template <typename, unsigned> friend struct SmallVectorStorage;
69 
70   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
71   // don't want it to be automatically run, so we need to represent the space as
72   // something else.  Use an array of char of sufficient alignment.
73   typedef llvm::AlignedCharArrayUnion<T> U;
74   U FirstEl;
75   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
76 
77 protected:
SmallVectorTemplateCommon(size_t Size)78   SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(&FirstEl, Size) {}
79 
grow_pod(size_t MinSizeInBytes,size_t TSize)80   void grow_pod(size_t MinSizeInBytes, size_t TSize) {
81     SmallVectorBase::grow_pod(&FirstEl, MinSizeInBytes, TSize);
82   }
83 
84   /// Return true if this is a smallvector which has not had dynamic
85   /// memory allocated for it.
isSmall()86   bool isSmall() const {
87     return BeginX == static_cast<const void*>(&FirstEl);
88   }
89 
90   /// Put this vector in a state of being small.
resetToSmall()91   void resetToSmall() {
92     BeginX = EndX = CapacityX = &FirstEl;
93   }
94 
setEnd(T * P)95   void setEnd(T *P) { this->EndX = P; }
96 public:
97   typedef size_t size_type;
98   typedef ptrdiff_t difference_type;
99   typedef T value_type;
100   typedef T *iterator;
101   typedef const T *const_iterator;
102 
103   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
104   typedef std::reverse_iterator<iterator> reverse_iterator;
105 
106   typedef T &reference;
107   typedef const T &const_reference;
108   typedef T *pointer;
109   typedef const T *const_pointer;
110 
111   // forward iterator creation methods.
112   LLVM_ATTRIBUTE_ALWAYS_INLINE
begin()113   iterator begin() { return (iterator)this->BeginX; }
114   LLVM_ATTRIBUTE_ALWAYS_INLINE
begin()115   const_iterator begin() const { return (const_iterator)this->BeginX; }
116   LLVM_ATTRIBUTE_ALWAYS_INLINE
end()117   iterator end() { return (iterator)this->EndX; }
118   LLVM_ATTRIBUTE_ALWAYS_INLINE
end()119   const_iterator end() const { return (const_iterator)this->EndX; }
120 protected:
capacity_ptr()121   iterator capacity_ptr() { return (iterator)this->CapacityX; }
capacity_ptr()122   const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
123 public:
124 
125   // reverse iterator creation methods.
rbegin()126   reverse_iterator rbegin()            { return reverse_iterator(end()); }
rbegin()127   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
rend()128   reverse_iterator rend()              { return reverse_iterator(begin()); }
rend()129   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
130 
131   LLVM_ATTRIBUTE_ALWAYS_INLINE
size()132   size_type size() const { return end()-begin(); }
max_size()133   size_type max_size() const { return size_type(-1) / sizeof(T); }
134 
135   /// Return the total number of elements in the currently allocated buffer.
capacity()136   size_t capacity() const { return capacity_ptr() - begin(); }
137 
138   /// Return a pointer to the vector's buffer, even if empty().
data()139   pointer data() { return pointer(begin()); }
140   /// Return a pointer to the vector's buffer, even if empty().
data()141   const_pointer data() const { return const_pointer(begin()); }
142 
143   LLVM_ATTRIBUTE_ALWAYS_INLINE
144   reference operator[](size_type idx) {
145     assert(idx < size());
146     return begin()[idx];
147   }
148   LLVM_ATTRIBUTE_ALWAYS_INLINE
149   const_reference operator[](size_type idx) const {
150     assert(idx < size());
151     return begin()[idx];
152   }
153 
front()154   reference front() {
155     assert(!empty());
156     return begin()[0];
157   }
front()158   const_reference front() const {
159     assert(!empty());
160     return begin()[0];
161   }
162 
back()163   reference back() {
164     assert(!empty());
165     return end()[-1];
166   }
back()167   const_reference back() const {
168     assert(!empty());
169     return end()[-1];
170   }
171 };
172 
173 /// SmallVectorTemplateBase<isPodLike = false> - This is where we put method
174 /// implementations that are designed to work with non-POD-like T's.
175 template <typename T, bool isPodLike>
176 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
177 protected:
SmallVectorTemplateBase(size_t Size)178   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
179 
destroy_range(T * S,T * E)180   static void destroy_range(T *S, T *E) {
181     while (S != E) {
182       --E;
183       E->~T();
184     }
185   }
186 
187   /// Use move-assignment to move the range [I, E) onto the
188   /// objects starting with "Dest".  This is just <memory>'s
189   /// std::move, but not all stdlibs actually provide that.
190   template<typename It1, typename It2>
move(It1 I,It1 E,It2 Dest)191   static It2 move(It1 I, It1 E, It2 Dest) {
192     for (; I != E; ++I, ++Dest)
193       *Dest = ::std::move(*I);
194     return Dest;
195   }
196 
197   /// Use move-assignment to move the range
198   /// [I, E) onto the objects ending at "Dest", moving objects
199   /// in reverse order.  This is just <algorithm>'s
200   /// std::move_backward, but not all stdlibs actually provide that.
201   template<typename It1, typename It2>
move_backward(It1 I,It1 E,It2 Dest)202   static It2 move_backward(It1 I, It1 E, It2 Dest) {
203     while (I != E)
204       *--Dest = ::std::move(*--E);
205     return Dest;
206   }
207 
208   /// Move the range [I, E) into the uninitialized memory starting with "Dest",
209   /// constructing elements as needed.
210   template<typename It1, typename It2>
uninitialized_move(It1 I,It1 E,It2 Dest)211   static void uninitialized_move(It1 I, It1 E, It2 Dest) {
212     for (; I != E; ++I, ++Dest)
213       ::new ((void*) &*Dest) T(::std::move(*I));
214   }
215 
216   /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
217   /// constructing elements as needed.
218   template<typename It1, typename It2>
uninitialized_copy(It1 I,It1 E,It2 Dest)219   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
220     std::uninitialized_copy(I, E, Dest);
221   }
222 
223   /// Grow the allocated memory (without initializing new elements), doubling
224   /// the size of the allocated memory. Guarantees space for at least one more
225   /// element, or MinSize more elements if specified.
226   void grow(size_t MinSize = 0);
227 
228 public:
push_back(const T & Elt)229   void push_back(const T &Elt) {
230     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
231       this->grow();
232     ::new ((void*) this->end()) T(Elt);
233     this->setEnd(this->end()+1);
234   }
235 
push_back(T && Elt)236   void push_back(T &&Elt) {
237     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
238       this->grow();
239     ::new ((void*) this->end()) T(::std::move(Elt));
240     this->setEnd(this->end()+1);
241   }
242 
pop_back()243   void pop_back() {
244     this->setEnd(this->end()-1);
245     this->end()->~T();
246   }
247 };
248 
249 // Define this out-of-line to dissuade the C++ compiler from inlining it.
250 template <typename T, bool isPodLike>
grow(size_t MinSize)251 void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
252   size_t CurCapacity = this->capacity();
253   size_t CurSize = this->size();
254   // Always grow, even from zero.
255   size_t NewCapacity = size_t(NextPowerOf2(CurCapacity+2));
256   if (NewCapacity < MinSize)
257     NewCapacity = MinSize;
258   T *NewElts = static_cast<T*>(malloc(NewCapacity*sizeof(T)));
259 
260   // Move the elements over.
261   this->uninitialized_move(this->begin(), this->end(), NewElts);
262 
263   // Destroy the original elements.
264   destroy_range(this->begin(), this->end());
265 
266   // If this wasn't grown from the inline copy, deallocate the old space.
267   if (!this->isSmall())
268     free(this->begin());
269 
270   this->setEnd(NewElts+CurSize);
271   this->BeginX = NewElts;
272   this->CapacityX = this->begin()+NewCapacity;
273 }
274 
275 
276 /// SmallVectorTemplateBase<isPodLike = true> - This is where we put method
277 /// implementations that are designed to work with POD-like T's.
278 template <typename T>
279 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
280 protected:
SmallVectorTemplateBase(size_t Size)281   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
282 
283   // No need to do a destroy loop for POD's.
destroy_range(T *,T *)284   static void destroy_range(T *, T *) {}
285 
286   /// Use move-assignment to move the range [I, E) onto the
287   /// objects starting with "Dest".  For PODs, this is just memcpy.
288   template<typename It1, typename It2>
move(It1 I,It1 E,It2 Dest)289   static It2 move(It1 I, It1 E, It2 Dest) {
290     return ::std::copy(I, E, Dest);
291   }
292 
293   /// Use move-assignment to move the range [I, E) onto the objects ending at
294   /// "Dest", moving objects in reverse order.
295   template<typename It1, typename It2>
move_backward(It1 I,It1 E,It2 Dest)296   static It2 move_backward(It1 I, It1 E, It2 Dest) {
297     return ::std::copy_backward(I, E, Dest);
298   }
299 
300   /// Move the range [I, E) onto the uninitialized memory
301   /// starting with "Dest", constructing elements into it as needed.
302   template<typename It1, typename It2>
uninitialized_move(It1 I,It1 E,It2 Dest)303   static void uninitialized_move(It1 I, It1 E, It2 Dest) {
304     // Just do a copy.
305     uninitialized_copy(I, E, Dest);
306   }
307 
308   /// Copy the range [I, E) onto the uninitialized memory
309   /// starting with "Dest", constructing elements into it as needed.
310   template<typename It1, typename It2>
uninitialized_copy(It1 I,It1 E,It2 Dest)311   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
312     // Arbitrary iterator types; just use the basic implementation.
313     std::uninitialized_copy(I, E, Dest);
314   }
315 
316   /// Copy the range [I, E) onto the uninitialized memory
317   /// starting with "Dest", constructing elements into it as needed.
318   template <typename T1, typename T2>
319   static void uninitialized_copy(
320       T1 *I, T1 *E, T2 *Dest,
321       typename std::enable_if<std::is_same<typename std::remove_const<T1>::type,
322                                            T2>::value>::type * = nullptr) {
323     // Use memcpy for PODs iterated by pointers (which includes SmallVector
324     // iterators): std::uninitialized_copy optimizes to memmove, but we can
325     // use memcpy here. Note that I and E are iterators and thus might be
326     // invalid for memcpy if they are equal.
327     if (I != E)
328       memcpy(Dest, I, (E - I) * sizeof(T));
329   }
330 
331   /// Double the size of the allocated memory, guaranteeing space for at
332   /// least one more element or MinSize if specified.
333   void grow(size_t MinSize = 0) {
334     this->grow_pod(MinSize*sizeof(T), sizeof(T));
335   }
336 public:
push_back(const T & Elt)337   void push_back(const T &Elt) {
338     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
339       this->grow();
340     memcpy(this->end(), &Elt, sizeof(T));
341     this->setEnd(this->end()+1);
342   }
343 
pop_back()344   void pop_back() {
345     this->setEnd(this->end()-1);
346   }
347 };
348 
349 
350 /// This class consists of common code factored out of the SmallVector class to
351 /// reduce code duplication based on the SmallVector 'N' template parameter.
352 template <typename T>
353 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
354   typedef SmallVectorTemplateBase<T, isPodLike<T>::value > SuperClass;
355 
356   SmallVectorImpl(const SmallVectorImpl&) = delete;
357 public:
358   typedef typename SuperClass::iterator iterator;
359   typedef typename SuperClass::size_type size_type;
360 
361 protected:
362   // Default ctor - Initialize to empty.
SmallVectorImpl(unsigned N)363   explicit SmallVectorImpl(unsigned N)
364     : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
365   }
366 
367 public:
~SmallVectorImpl()368   ~SmallVectorImpl() {
369     // Destroy the constructed elements in the vector.
370     this->destroy_range(this->begin(), this->end());
371 
372     // If this wasn't grown from the inline copy, deallocate the old space.
373     if (!this->isSmall())
374       free(this->begin());
375   }
376 
377 
clear()378   void clear() {
379     this->destroy_range(this->begin(), this->end());
380     this->EndX = this->BeginX;
381   }
382 
resize(size_type N)383   void resize(size_type N) {
384     if (N < this->size()) {
385       this->destroy_range(this->begin()+N, this->end());
386       this->setEnd(this->begin()+N);
387     } else if (N > this->size()) {
388       if (this->capacity() < N)
389         this->grow(N);
390       for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
391         new (&*I) T();
392       this->setEnd(this->begin()+N);
393     }
394   }
395 
resize(size_type N,const T & NV)396   void resize(size_type N, const T &NV) {
397     if (N < this->size()) {
398       this->destroy_range(this->begin()+N, this->end());
399       this->setEnd(this->begin()+N);
400     } else if (N > this->size()) {
401       if (this->capacity() < N)
402         this->grow(N);
403       std::uninitialized_fill(this->end(), this->begin()+N, NV);
404       this->setEnd(this->begin()+N);
405     }
406   }
407 
reserve(size_type N)408   void reserve(size_type N) {
409     if (this->capacity() < N)
410       this->grow(N);
411   }
412 
pop_back_val()413   T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val() {
414     T Result = ::std::move(this->back());
415     this->pop_back();
416     return Result;
417   }
418 
419   void swap(SmallVectorImpl &RHS);
420 
421   /// Add the specified range to the end of the SmallVector.
422   template<typename in_iter>
append(in_iter in_start,in_iter in_end)423   void append(in_iter in_start, in_iter in_end) {
424     size_type NumInputs = std::distance(in_start, in_end);
425     // Grow allocated space if needed.
426     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
427       this->grow(this->size()+NumInputs);
428 
429     // Copy the new elements over.
430     this->uninitialized_copy(in_start, in_end, this->end());
431     this->setEnd(this->end() + NumInputs);
432   }
433 
434   /// Add the specified range to the end of the SmallVector.
append(size_type NumInputs,const T & Elt)435   void append(size_type NumInputs, const T &Elt) {
436     // Grow allocated space if needed.
437     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
438       this->grow(this->size()+NumInputs);
439 
440     // Copy the new elements over.
441     std::uninitialized_fill_n(this->end(), NumInputs, Elt);
442     this->setEnd(this->end() + NumInputs);
443   }
444 
append(std::initializer_list<T> IL)445   void append(std::initializer_list<T> IL) {
446     append(IL.begin(), IL.end());
447   }
448 
assign(size_type NumElts,const T & Elt)449   void assign(size_type NumElts, const T &Elt) {
450     clear();
451     if (this->capacity() < NumElts)
452       this->grow(NumElts);
453     this->setEnd(this->begin()+NumElts);
454     std::uninitialized_fill(this->begin(), this->end(), Elt);
455   }
456 
assign(std::initializer_list<T> IL)457   void assign(std::initializer_list<T> IL) {
458     clear();
459     append(IL);
460   }
461 
erase(iterator I)462   iterator erase(iterator I) {
463     assert(I >= this->begin() && "Iterator to erase is out of bounds.");
464     assert(I < this->end() && "Erasing at past-the-end iterator.");
465 
466     iterator N = I;
467     // Shift all elts down one.
468     this->move(I+1, this->end(), I);
469     // Drop the last elt.
470     this->pop_back();
471     return(N);
472   }
473 
erase(iterator S,iterator E)474   iterator erase(iterator S, iterator E) {
475     assert(S >= this->begin() && "Range to erase is out of bounds.");
476     assert(S <= E && "Trying to erase invalid range.");
477     assert(E <= this->end() && "Trying to erase past the end.");
478 
479     iterator N = S;
480     // Shift all elts down.
481     iterator I = this->move(E, this->end(), S);
482     // Drop the last elts.
483     this->destroy_range(I, this->end());
484     this->setEnd(I);
485     return(N);
486   }
487 
insert(iterator I,T && Elt)488   iterator insert(iterator I, T &&Elt) {
489     if (I == this->end()) {  // Important special case for empty vector.
490       this->push_back(::std::move(Elt));
491       return this->end()-1;
492     }
493 
494     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
495     assert(I <= this->end() && "Inserting past the end of the vector.");
496 
497     if (this->EndX >= this->CapacityX) {
498       size_t EltNo = I-this->begin();
499       this->grow();
500       I = this->begin()+EltNo;
501     }
502 
503     ::new ((void*) this->end()) T(::std::move(this->back()));
504     // Push everything else over.
505     this->move_backward(I, this->end()-1, this->end());
506     this->setEnd(this->end()+1);
507 
508     // If we just moved the element we're inserting, be sure to update
509     // the reference.
510     T *EltPtr = &Elt;
511     if (I <= EltPtr && EltPtr < this->EndX)
512       ++EltPtr;
513 
514     *I = ::std::move(*EltPtr);
515     return I;
516   }
517 
insert(iterator I,const T & Elt)518   iterator insert(iterator I, const T &Elt) {
519     if (I == this->end()) {  // Important special case for empty vector.
520       this->push_back(Elt);
521       return this->end()-1;
522     }
523 
524     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
525     assert(I <= this->end() && "Inserting past the end of the vector.");
526 
527     if (this->EndX >= this->CapacityX) {
528       size_t EltNo = I-this->begin();
529       this->grow();
530       I = this->begin()+EltNo;
531     }
532     ::new ((void*) this->end()) T(std::move(this->back()));
533     // Push everything else over.
534     this->move_backward(I, this->end()-1, this->end());
535     this->setEnd(this->end()+1);
536 
537     // If we just moved the element we're inserting, be sure to update
538     // the reference.
539     const T *EltPtr = &Elt;
540     if (I <= EltPtr && EltPtr < this->EndX)
541       ++EltPtr;
542 
543     *I = *EltPtr;
544     return I;
545   }
546 
insert(iterator I,size_type NumToInsert,const T & Elt)547   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
548     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
549     size_t InsertElt = I - this->begin();
550 
551     if (I == this->end()) {  // Important special case for empty vector.
552       append(NumToInsert, Elt);
553       return this->begin()+InsertElt;
554     }
555 
556     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
557     assert(I <= this->end() && "Inserting past the end of the vector.");
558 
559     // Ensure there is enough space.
560     reserve(this->size() + NumToInsert);
561 
562     // Uninvalidate the iterator.
563     I = this->begin()+InsertElt;
564 
565     // If there are more elements between the insertion point and the end of the
566     // range than there are being inserted, we can use a simple approach to
567     // insertion.  Since we already reserved space, we know that this won't
568     // reallocate the vector.
569     if (size_t(this->end()-I) >= NumToInsert) {
570       T *OldEnd = this->end();
571       append(std::move_iterator<iterator>(this->end() - NumToInsert),
572              std::move_iterator<iterator>(this->end()));
573 
574       // Copy the existing elements that get replaced.
575       this->move_backward(I, OldEnd-NumToInsert, OldEnd);
576 
577       std::fill_n(I, NumToInsert, Elt);
578       return I;
579     }
580 
581     // Otherwise, we're inserting more elements than exist already, and we're
582     // not inserting at the end.
583 
584     // Move over the elements that we're about to overwrite.
585     T *OldEnd = this->end();
586     this->setEnd(this->end() + NumToInsert);
587     size_t NumOverwritten = OldEnd-I;
588     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
589 
590     // Replace the overwritten part.
591     std::fill_n(I, NumOverwritten, Elt);
592 
593     // Insert the non-overwritten middle part.
594     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
595     return I;
596   }
597 
598   template<typename ItTy>
insert(iterator I,ItTy From,ItTy To)599   iterator insert(iterator I, ItTy From, ItTy To) {
600     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
601     size_t InsertElt = I - this->begin();
602 
603     if (I == this->end()) {  // Important special case for empty vector.
604       append(From, To);
605       return this->begin()+InsertElt;
606     }
607 
608     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
609     assert(I <= this->end() && "Inserting past the end of the vector.");
610 
611     size_t NumToInsert = std::distance(From, To);
612 
613     // Ensure there is enough space.
614     reserve(this->size() + NumToInsert);
615 
616     // Uninvalidate the iterator.
617     I = this->begin()+InsertElt;
618 
619     // If there are more elements between the insertion point and the end of the
620     // range than there are being inserted, we can use a simple approach to
621     // insertion.  Since we already reserved space, we know that this won't
622     // reallocate the vector.
623     if (size_t(this->end()-I) >= NumToInsert) {
624       T *OldEnd = this->end();
625       append(std::move_iterator<iterator>(this->end() - NumToInsert),
626              std::move_iterator<iterator>(this->end()));
627 
628       // Copy the existing elements that get replaced.
629       this->move_backward(I, OldEnd-NumToInsert, OldEnd);
630 
631       std::copy(From, To, I);
632       return I;
633     }
634 
635     // Otherwise, we're inserting more elements than exist already, and we're
636     // not inserting at the end.
637 
638     // Move over the elements that we're about to overwrite.
639     T *OldEnd = this->end();
640     this->setEnd(this->end() + NumToInsert);
641     size_t NumOverwritten = OldEnd-I;
642     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
643 
644     // Replace the overwritten part.
645     for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
646       *J = *From;
647       ++J; ++From;
648     }
649 
650     // Insert the non-overwritten middle part.
651     this->uninitialized_copy(From, To, OldEnd);
652     return I;
653   }
654 
insert(iterator I,std::initializer_list<T> IL)655   void insert(iterator I, std::initializer_list<T> IL) {
656     insert(I, IL.begin(), IL.end());
657   }
658 
emplace_back(ArgTypes &&...Args)659   template <typename... ArgTypes> void emplace_back(ArgTypes &&... Args) {
660     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
661       this->grow();
662     ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
663     this->setEnd(this->end() + 1);
664   }
665 
666   SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
667 
668   SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
669 
670   bool operator==(const SmallVectorImpl &RHS) const {
671     if (this->size() != RHS.size()) return false;
672     return std::equal(this->begin(), this->end(), RHS.begin());
673   }
674   bool operator!=(const SmallVectorImpl &RHS) const {
675     return !(*this == RHS);
676   }
677 
678   bool operator<(const SmallVectorImpl &RHS) const {
679     return std::lexicographical_compare(this->begin(), this->end(),
680                                         RHS.begin(), RHS.end());
681   }
682 
683   /// Set the array size to \p N, which the current array must have enough
684   /// capacity for.
685   ///
686   /// This does not construct or destroy any elements in the vector.
687   ///
688   /// Clients can use this in conjunction with capacity() to write past the end
689   /// of the buffer when they know that more elements are available, and only
690   /// update the size later. This avoids the cost of value initializing elements
691   /// which will only be overwritten.
set_size(size_type N)692   void set_size(size_type N) {
693     assert(N <= this->capacity());
694     this->setEnd(this->begin() + N);
695   }
696 };
697 
698 
699 template <typename T>
swap(SmallVectorImpl<T> & RHS)700 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
701   if (this == &RHS) return;
702 
703   // We can only avoid copying elements if neither vector is small.
704   if (!this->isSmall() && !RHS.isSmall()) {
705     std::swap(this->BeginX, RHS.BeginX);
706     std::swap(this->EndX, RHS.EndX);
707     std::swap(this->CapacityX, RHS.CapacityX);
708     return;
709   }
710   if (RHS.size() > this->capacity())
711     this->grow(RHS.size());
712   if (this->size() > RHS.capacity())
713     RHS.grow(this->size());
714 
715   // Swap the shared elements.
716   size_t NumShared = this->size();
717   if (NumShared > RHS.size()) NumShared = RHS.size();
718   for (size_type i = 0; i != NumShared; ++i)
719     std::swap((*this)[i], RHS[i]);
720 
721   // Copy over the extra elts.
722   if (this->size() > RHS.size()) {
723     size_t EltDiff = this->size() - RHS.size();
724     this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
725     RHS.setEnd(RHS.end()+EltDiff);
726     this->destroy_range(this->begin()+NumShared, this->end());
727     this->setEnd(this->begin()+NumShared);
728   } else if (RHS.size() > this->size()) {
729     size_t EltDiff = RHS.size() - this->size();
730     this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
731     this->setEnd(this->end() + EltDiff);
732     this->destroy_range(RHS.begin()+NumShared, RHS.end());
733     RHS.setEnd(RHS.begin()+NumShared);
734   }
735 }
736 
737 template <typename T>
738 SmallVectorImpl<T> &SmallVectorImpl<T>::
739   operator=(const SmallVectorImpl<T> &RHS) {
740   // Avoid self-assignment.
741   if (this == &RHS) return *this;
742 
743   // If we already have sufficient space, assign the common elements, then
744   // destroy any excess.
745   size_t RHSSize = RHS.size();
746   size_t CurSize = this->size();
747   if (CurSize >= RHSSize) {
748     // Assign common elements.
749     iterator NewEnd;
750     if (RHSSize)
751       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
752     else
753       NewEnd = this->begin();
754 
755     // Destroy excess elements.
756     this->destroy_range(NewEnd, this->end());
757 
758     // Trim.
759     this->setEnd(NewEnd);
760     return *this;
761   }
762 
763   // If we have to grow to have enough elements, destroy the current elements.
764   // This allows us to avoid copying them during the grow.
765   // FIXME: don't do this if they're efficiently moveable.
766   if (this->capacity() < RHSSize) {
767     // Destroy current elements.
768     this->destroy_range(this->begin(), this->end());
769     this->setEnd(this->begin());
770     CurSize = 0;
771     this->grow(RHSSize);
772   } else if (CurSize) {
773     // Otherwise, use assignment for the already-constructed elements.
774     std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
775   }
776 
777   // Copy construct the new elements in place.
778   this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
779                            this->begin()+CurSize);
780 
781   // Set end.
782   this->setEnd(this->begin()+RHSSize);
783   return *this;
784 }
785 
786 template <typename T>
787 SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
788   // Avoid self-assignment.
789   if (this == &RHS) return *this;
790 
791   // If the RHS isn't small, clear this vector and then steal its buffer.
792   if (!RHS.isSmall()) {
793     this->destroy_range(this->begin(), this->end());
794     if (!this->isSmall()) free(this->begin());
795     this->BeginX = RHS.BeginX;
796     this->EndX = RHS.EndX;
797     this->CapacityX = RHS.CapacityX;
798     RHS.resetToSmall();
799     return *this;
800   }
801 
802   // If we already have sufficient space, assign the common elements, then
803   // destroy any excess.
804   size_t RHSSize = RHS.size();
805   size_t CurSize = this->size();
806   if (CurSize >= RHSSize) {
807     // Assign common elements.
808     iterator NewEnd = this->begin();
809     if (RHSSize)
810       NewEnd = this->move(RHS.begin(), RHS.end(), NewEnd);
811 
812     // Destroy excess elements and trim the bounds.
813     this->destroy_range(NewEnd, this->end());
814     this->setEnd(NewEnd);
815 
816     // Clear the RHS.
817     RHS.clear();
818 
819     return *this;
820   }
821 
822   // If we have to grow to have enough elements, destroy the current elements.
823   // This allows us to avoid copying them during the grow.
824   // FIXME: this may not actually make any sense if we can efficiently move
825   // elements.
826   if (this->capacity() < RHSSize) {
827     // Destroy current elements.
828     this->destroy_range(this->begin(), this->end());
829     this->setEnd(this->begin());
830     CurSize = 0;
831     this->grow(RHSSize);
832   } else if (CurSize) {
833     // Otherwise, use assignment for the already-constructed elements.
834     this->move(RHS.begin(), RHS.begin()+CurSize, this->begin());
835   }
836 
837   // Move-construct the new elements in place.
838   this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
839                            this->begin()+CurSize);
840 
841   // Set end.
842   this->setEnd(this->begin()+RHSSize);
843 
844   RHS.clear();
845   return *this;
846 }
847 
848 /// Storage for the SmallVector elements which aren't contained in
849 /// SmallVectorTemplateCommon. There are 'N-1' elements here. The remaining '1'
850 /// element is in the base class. This is specialized for the N=1 and N=0 cases
851 /// to avoid allocating unnecessary storage.
852 template <typename T, unsigned N>
853 struct SmallVectorStorage {
854   typename SmallVectorTemplateCommon<T>::U InlineElts[N - 1];
855 };
856 template <typename T> struct SmallVectorStorage<T, 1> {};
857 template <typename T> struct SmallVectorStorage<T, 0> {};
858 
859 /// This is a 'vector' (really, a variable-sized array), optimized
860 /// for the case when the array is small.  It contains some number of elements
861 /// in-place, which allows it to avoid heap allocation when the actual number of
862 /// elements is below that threshold.  This allows normal "small" cases to be
863 /// fast without losing generality for large inputs.
864 ///
865 /// Note that this does not attempt to be exception safe.
866 ///
867 template <typename T, unsigned N>
868 class SmallVector : public SmallVectorImpl<T> {
869   /// Inline space for elements which aren't stored in the base class.
870   SmallVectorStorage<T, N> Storage;
871 public:
872   SmallVector() : SmallVectorImpl<T>(N) {
873   }
874 
875   explicit SmallVector(size_t Size, const T &Value = T())
876     : SmallVectorImpl<T>(N) {
877     this->assign(Size, Value);
878   }
879 
880   template<typename ItTy>
881   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
882     this->append(S, E);
883   }
884 
885   template <typename RangeTy>
886   explicit SmallVector(const llvm::iterator_range<RangeTy> R)
887       : SmallVectorImpl<T>(N) {
888     this->append(R.begin(), R.end());
889   }
890 
891   SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
892     this->assign(IL);
893   }
894 
895   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
896     if (!RHS.empty())
897       SmallVectorImpl<T>::operator=(RHS);
898   }
899 
900   const SmallVector &operator=(const SmallVector &RHS) {
901     SmallVectorImpl<T>::operator=(RHS);
902     return *this;
903   }
904 
905   SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
906     if (!RHS.empty())
907       SmallVectorImpl<T>::operator=(::std::move(RHS));
908   }
909 
910   const SmallVector &operator=(SmallVector &&RHS) {
911     SmallVectorImpl<T>::operator=(::std::move(RHS));
912     return *this;
913   }
914 
915   SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
916     if (!RHS.empty())
917       SmallVectorImpl<T>::operator=(::std::move(RHS));
918   }
919 
920   const SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
921     SmallVectorImpl<T>::operator=(::std::move(RHS));
922     return *this;
923   }
924 
925   const SmallVector &operator=(std::initializer_list<T> IL) {
926     this->assign(IL);
927     return *this;
928   }
929 };
930 
931 template<typename T, unsigned N>
932 static inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
933   return X.capacity_in_bytes();
934 }
935 
936 } // End llvm namespace
937 
938 namespace std {
939   /// Implement std::swap in terms of SmallVector swap.
940   template<typename T>
941   inline void
942   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
943     LHS.swap(RHS);
944   }
945 
946   /// Implement std::swap in terms of SmallVector swap.
947   template<typename T, unsigned N>
948   inline void
949   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
950     LHS.swap(RHS);
951   }
952 }
953 
954 #endif
955