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