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