SmallVector: return a valid iterator for the rare case of inserting an empty range...
[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     iterator N = I;
467     // Shift all elts down one.
468     std::copy(I+1, this->end(), I);
469     // Drop the last elt.
470     this->pop_back();
471     return(N);
472   }
473
474   iterator erase(iterator S, iterator E) {
475     iterator N = S;
476     // Shift all elts down.
477     iterator I = std::copy(E, this->end(), S);
478     // Drop the last elts.
479     this->destroy_range(I, this->end());
480     this->setEnd(I);
481     return(N);
482   }
483
484 #if LLVM_USE_RVALUE_REFERENCES
485   iterator insert(iterator I, T &&Elt) {
486     if (I == this->end()) {  // Important special case for empty vector.
487       this->push_back(::std::move(Elt));
488       return this->end()-1;
489     }
490
491     if (this->EndX < this->CapacityX) {
492     Retry:
493       ::new ((void*) this->end()) T(::std::move(this->back()));
494       this->setEnd(this->end()+1);
495       // Push everything else over.
496       this->move_backward(I, this->end()-1, this->end());
497
498       // If we just moved the element we're inserting, be sure to update
499       // the reference.
500       T *EltPtr = &Elt;
501       if (I <= EltPtr && EltPtr < this->EndX)
502         ++EltPtr;
503
504       *I = ::std::move(*EltPtr);
505       return I;
506     }
507     size_t EltNo = I-this->begin();
508     this->grow();
509     I = this->begin()+EltNo;
510     goto Retry;
511   }
512 #endif
513
514   iterator insert(iterator I, const T &Elt) {
515     if (I == this->end()) {  // Important special case for empty vector.
516       this->push_back(Elt);
517       return this->end()-1;
518     }
519
520     if (this->EndX < this->CapacityX) {
521     Retry:
522       ::new ((void*) this->end()) T(this->back());
523       this->setEnd(this->end()+1);
524       // Push everything else over.
525       this->move_backward(I, this->end()-1, this->end());
526
527       // If we just moved the element we're inserting, be sure to update
528       // the reference.
529       const T *EltPtr = &Elt;
530       if (I <= EltPtr && EltPtr < this->EndX)
531         ++EltPtr;
532
533       *I = *EltPtr;
534       return I;
535     }
536     size_t EltNo = I-this->begin();
537     this->grow();
538     I = this->begin()+EltNo;
539     goto Retry;
540   }
541
542   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
543     if (I == this->end()) {  // Important special case for empty vector.
544       append(NumToInsert, Elt);
545       return NumToInsert == 0 ? this->end() : this->end()-1;
546     }
547
548     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
549     size_t InsertElt = I - this->begin();
550
551     // Ensure there is enough space.
552     reserve(static_cast<unsigned>(this->size() + NumToInsert));
553
554     // Uninvalidate the iterator.
555     I = this->begin()+InsertElt;
556
557     // If there are more elements between the insertion point and the end of the
558     // range than there are being inserted, we can use a simple approach to
559     // insertion.  Since we already reserved space, we know that this won't
560     // reallocate the vector.
561     if (size_t(this->end()-I) >= NumToInsert) {
562       T *OldEnd = this->end();
563       append(this->end()-NumToInsert, this->end());
564
565       // Copy the existing elements that get replaced.
566       this->move_backward(I, OldEnd-NumToInsert, OldEnd);
567
568       std::fill_n(I, NumToInsert, Elt);
569       return I;
570     }
571
572     // Otherwise, we're inserting more elements than exist already, and we're
573     // not inserting at the end.
574
575     // Copy over the elements that we're about to overwrite.
576     T *OldEnd = this->end();
577     this->setEnd(this->end() + NumToInsert);
578     size_t NumOverwritten = OldEnd-I;
579     this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
580
581     // Replace the overwritten part.
582     std::fill_n(I, NumOverwritten, Elt);
583
584     // Insert the non-overwritten middle part.
585     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
586     return I;
587   }
588
589   template<typename ItTy>
590   iterator insert(iterator I, ItTy From, ItTy To) {
591     if (I == this->end()) {  // Important special case for empty vector.
592       append(From, To);
593       return From == To ? this->end() : this->end()-1;
594     }
595
596     size_t NumToInsert = std::distance(From, To);
597     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
598     size_t InsertElt = I - this->begin();
599
600     // Ensure there is enough space.
601     reserve(static_cast<unsigned>(this->size() + NumToInsert));
602
603     // Uninvalidate the iterator.
604     I = this->begin()+InsertElt;
605
606     // If there are more elements between the insertion point and the end of the
607     // range than there are being inserted, we can use a simple approach to
608     // insertion.  Since we already reserved space, we know that this won't
609     // reallocate the vector.
610     if (size_t(this->end()-I) >= NumToInsert) {
611       T *OldEnd = this->end();
612       append(this->end()-NumToInsert, this->end());
613
614       // Copy the existing elements that get replaced.
615       this->move_backward(I, OldEnd-NumToInsert, OldEnd);
616
617       std::copy(From, To, I);
618       return I;
619     }
620
621     // Otherwise, we're inserting more elements than exist already, and we're
622     // not inserting at the end.
623
624     // Copy over the elements that we're about to overwrite.
625     T *OldEnd = this->end();
626     this->setEnd(this->end() + NumToInsert);
627     size_t NumOverwritten = OldEnd-I;
628     this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
629
630     // Replace the overwritten part.
631     for (; NumOverwritten > 0; --NumOverwritten) {
632       *I = *From;
633       ++I; ++From;
634     }
635
636     // Insert the non-overwritten middle part.
637     this->uninitialized_copy(From, To, OldEnd);
638     return I;
639   }
640
641   SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
642
643 #if LLVM_USE_RVALUE_REFERENCES
644   SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
645 #endif
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_size - Set the array size to \arg N, which the current array must have
661   /// enough 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(unsigned 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 (unsigned i = 0; i != static_cast<unsigned>(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 #if LLVM_USE_RVALUE_REFERENCES
764 template <typename T>
765 SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
766   // Avoid self-assignment.
767   if (this == &RHS) return *this;
768
769   // If the RHS isn't small, clear this vector and then steal its buffer.
770   if (!RHS.isSmall()) {
771     this->destroy_range(this->begin(), this->end());
772     if (!this->isSmall()) free(this->begin());
773     this->BeginX = RHS.BeginX;
774     this->EndX = RHS.EndX;
775     this->CapacityX = RHS.CapacityX;
776     RHS.resetToSmall();
777     return *this;
778   }
779
780   // If we already have sufficient space, assign the common elements, then
781   // destroy any excess.
782   size_t RHSSize = RHS.size();
783   size_t CurSize = this->size();
784   if (CurSize >= RHSSize) {
785     // Assign common elements.
786     iterator NewEnd = this->begin();
787     if (RHSSize)
788       NewEnd = this->move(RHS.begin(), RHS.end(), NewEnd);
789
790     // Destroy excess elements and trim the bounds.
791     this->destroy_range(NewEnd, this->end());
792     this->setEnd(NewEnd);
793
794     // Clear the RHS.
795     RHS.clear();
796
797     return *this;
798   }
799
800   // If we have to grow to have enough elements, destroy the current elements.
801   // This allows us to avoid copying them during the grow.
802   // FIXME: this may not actually make any sense if we can efficiently move
803   // elements.
804   if (this->capacity() < RHSSize) {
805     // Destroy current elements.
806     this->destroy_range(this->begin(), this->end());
807     this->setEnd(this->begin());
808     CurSize = 0;
809     this->grow(RHSSize);
810   } else if (CurSize) {
811     // Otherwise, use assignment for the already-constructed elements.
812     this->move(RHS.begin(), RHS.end(), this->begin());
813   }
814
815   // Move-construct the new elements in place.
816   this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
817                            this->begin()+CurSize);
818
819   // Set end.
820   this->setEnd(this->begin()+RHSSize);
821
822   RHS.clear();
823   return *this;
824 }
825 #endif
826
827 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
828 /// for the case when the array is small.  It contains some number of elements
829 /// in-place, which allows it to avoid heap allocation when the actual number of
830 /// elements is below that threshold.  This allows normal "small" cases to be
831 /// fast without losing generality for large inputs.
832 ///
833 /// Note that this does not attempt to be exception safe.
834 ///
835 template <typename T, unsigned N>
836 class SmallVector : public SmallVectorImpl<T> {
837   /// InlineElts - These are 'N-1' elements that are stored inline in the body
838   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
839   typedef typename SmallVectorImpl<T>::U U;
840   enum {
841     // MinUs - The number of U's require to cover N T's.
842     MinUs = (static_cast<unsigned int>(sizeof(T))*N +
843              static_cast<unsigned int>(sizeof(U)) - 1) /
844             static_cast<unsigned int>(sizeof(U)),
845
846     // NumInlineEltsElts - The number of elements actually in this array.  There
847     // is already one in the parent class, and we have to round up to avoid
848     // having a zero-element array.
849     NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
850
851     // NumTsAvailable - The number of T's we actually have space for, which may
852     // be more than N due to rounding.
853     NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
854                      static_cast<unsigned int>(sizeof(T))
855   };
856   U InlineElts[NumInlineEltsElts];
857 public:
858   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
859   }
860
861   explicit SmallVector(unsigned Size, const T &Value = T())
862     : SmallVectorImpl<T>(NumTsAvailable) {
863     this->assign(Size, Value);
864   }
865
866   template<typename ItTy>
867   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
868     this->append(S, E);
869   }
870
871   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
872     if (!RHS.empty())
873       SmallVectorImpl<T>::operator=(RHS);
874   }
875
876   const SmallVector &operator=(const SmallVector &RHS) {
877     SmallVectorImpl<T>::operator=(RHS);
878     return *this;
879   }
880
881 #if LLVM_USE_RVALUE_REFERENCES
882   SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(NumTsAvailable) {
883     if (!RHS.empty())
884       SmallVectorImpl<T>::operator=(::std::move(RHS));
885   }
886
887   const SmallVector &operator=(SmallVector &&RHS) {
888     SmallVectorImpl<T>::operator=(::std::move(RHS));
889     return *this;
890   }
891 #endif
892
893 };
894
895 /// Specialize SmallVector at N=0.  This specialization guarantees
896 /// that it can be instantiated at an incomplete T if none of its
897 /// members are required.
898 template <typename T>
899 class SmallVector<T,0> : public SmallVectorImpl<T> {
900 public:
901   SmallVector() : SmallVectorImpl<T>(0) {}
902
903   explicit SmallVector(unsigned Size, const T &Value = T())
904     : SmallVectorImpl<T>(0) {
905     this->assign(Size, Value);
906   }
907
908   template<typename ItTy>
909   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(0) {
910     this->append(S, E);
911   }
912
913   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(0) {
914     SmallVectorImpl<T>::operator=(RHS);
915   }
916
917   SmallVector &operator=(const SmallVectorImpl<T> &RHS) {
918     return SmallVectorImpl<T>::operator=(RHS);
919   }
920
921 };
922
923 template<typename T, unsigned N>
924 static inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
925   return X.capacity_in_bytes();
926 }
927
928 } // End llvm namespace
929
930 namespace std {
931   /// Implement std::swap in terms of SmallVector swap.
932   template<typename T>
933   inline void
934   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
935     LHS.swap(RHS);
936   }
937
938   /// Implement std::swap in terms of SmallVector swap.
939   template<typename T, unsigned N>
940   inline void
941   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
942     LHS.swap(RHS);
943   }
944 }
945
946 #endif