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