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