Make the copy member of StringRef/ArrayRef generic wrt allocators.
[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     if (this->EndX < this->CapacityX) {
227     Retry:
228       ::new ((void*) this->end()) T(Elt);
229       this->setEnd(this->end()+1);
230       return;
231     }
232     this->grow();
233     goto Retry;
234   }
235
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
247   void pop_back() {
248     this->setEnd(this->end()-1);
249     this->end()->~T();
250   }
251 };
252
253 // Define this out-of-line to dissuade the C++ compiler from inlining it.
254 template <typename T, bool isPodLike>
255 void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
256   size_t CurCapacity = this->capacity();
257   size_t CurSize = this->size();
258   // Always grow, even from zero.  
259   size_t NewCapacity = size_t(NextPowerOf2(CurCapacity+2));
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&) LLVM_DELETED_FUNCTION;
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 LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val() {
418     T Result = ::std::move(this->back());
419     this->pop_back();
420     return Result;
421   }
422
423   void swap(SmallVectorImpl &RHS);
424
425   /// append - Add the specified range to the end of the SmallVector.
426   ///
427   template<typename in_iter>
428   void append(in_iter in_start, in_iter in_end) {
429     size_type NumInputs = std::distance(in_start, in_end);
430     // Grow allocated space if needed.
431     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
432       this->grow(this->size()+NumInputs);
433
434     // Copy the new elements over.
435     // TODO: NEED To compile time dispatch on whether in_iter is a random access
436     // iterator to use the fast uninitialized_copy.
437     std::uninitialized_copy(in_start, in_end, this->end());
438     this->setEnd(this->end() + NumInputs);
439   }
440
441   /// append - Add the specified range to the end of the SmallVector.
442   ///
443   void append(size_type NumInputs, const T &Elt) {
444     // Grow allocated space if needed.
445     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
446       this->grow(this->size()+NumInputs);
447
448     // Copy the new elements over.
449     std::uninitialized_fill_n(this->end(), NumInputs, Elt);
450     this->setEnd(this->end() + NumInputs);
451   }
452
453   void assign(unsigned NumElts, const T &Elt) {
454     clear();
455     if (this->capacity() < NumElts)
456       this->grow(NumElts);
457     this->setEnd(this->begin()+NumElts);
458     std::uninitialized_fill(this->begin(), this->end(), Elt);
459   }
460
461   iterator erase(iterator I) {
462     assert(I >= this->begin() && "Iterator to erase is out of bounds.");
463     assert(I < this->end() && "Erasing at past-the-end iterator.");
464
465     iterator N = I;
466     // Shift all elts down one.
467     this->move(I+1, this->end(), I);
468     // Drop the last elt.
469     this->pop_back();
470     return(N);
471   }
472
473   iterator erase(iterator S, iterator E) {
474     assert(S >= this->begin() && "Range to erase is out of bounds.");
475     assert(S <= E && "Trying to erase invalid range.");
476     assert(E <= this->end() && "Trying to erase past the end.");
477
478     iterator N = S;
479     // Shift all elts down.
480     iterator I = this->move(E, this->end(), S);
481     // Drop the last elts.
482     this->destroy_range(I, this->end());
483     this->setEnd(I);
484     return(N);
485   }
486
487   iterator insert(iterator I, T &&Elt) {
488     if (I == this->end()) {  // Important special case for empty vector.
489       this->push_back(::std::move(Elt));
490       return this->end()-1;
491     }
492
493     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
494     assert(I <= this->end() && "Inserting past the end of the vector.");
495
496     if (this->EndX < this->CapacityX) {
497     Retry:
498       ::new ((void*) this->end()) T(::std::move(this->back()));
499       this->setEnd(this->end()+1);
500       // Push everything else over.
501       this->move_backward(I, this->end()-1, this->end());
502
503       // If we just moved the element we're inserting, be sure to update
504       // the reference.
505       T *EltPtr = &Elt;
506       if (I <= EltPtr && EltPtr < this->EndX)
507         ++EltPtr;
508
509       *I = ::std::move(*EltPtr);
510       return I;
511     }
512     size_t EltNo = I-this->begin();
513     this->grow();
514     I = this->begin()+EltNo;
515     goto Retry;
516   }
517
518   iterator insert(iterator I, const T &Elt) {
519     if (I == this->end()) {  // Important special case for empty vector.
520       this->push_back(Elt);
521       return this->end()-1;
522     }
523
524     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
525     assert(I <= this->end() && "Inserting past the end of the vector.");
526
527     if (this->EndX < this->CapacityX) {
528     Retry:
529       ::new ((void*) this->end()) T(this->back());
530       this->setEnd(this->end()+1);
531       // Push everything else over.
532       this->move_backward(I, this->end()-1, this->end());
533
534       // If we just moved the element we're inserting, be sure to update
535       // the reference.
536       const T *EltPtr = &Elt;
537       if (I <= EltPtr && EltPtr < this->EndX)
538         ++EltPtr;
539
540       *I = *EltPtr;
541       return I;
542     }
543     size_t EltNo = I-this->begin();
544     this->grow();
545     I = this->begin()+EltNo;
546     goto Retry;
547   }
548
549   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
550     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
551     size_t InsertElt = I - this->begin();
552
553     if (I == this->end()) {  // Important special case for empty vector.
554       append(NumToInsert, Elt);
555       return this->begin()+InsertElt;
556     }
557
558     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
559     assert(I <= this->end() && "Inserting past the end of the vector.");
560
561     // Ensure there is enough space.
562     reserve(static_cast<unsigned>(this->size() + NumToInsert));
563
564     // Uninvalidate the iterator.
565     I = this->begin()+InsertElt;
566
567     // If there are more elements between the insertion point and the end of the
568     // range than there are being inserted, we can use a simple approach to
569     // insertion.  Since we already reserved space, we know that this won't
570     // reallocate the vector.
571     if (size_t(this->end()-I) >= NumToInsert) {
572       T *OldEnd = this->end();
573       append(this->end()-NumToInsert, this->end());
574
575       // Copy the existing elements that get replaced.
576       this->move_backward(I, OldEnd-NumToInsert, OldEnd);
577
578       std::fill_n(I, NumToInsert, Elt);
579       return I;
580     }
581
582     // Otherwise, we're inserting more elements than exist already, and we're
583     // not inserting at the end.
584
585     // Move over the elements that we're about to overwrite.
586     T *OldEnd = this->end();
587     this->setEnd(this->end() + NumToInsert);
588     size_t NumOverwritten = OldEnd-I;
589     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
590
591     // Replace the overwritten part.
592     std::fill_n(I, NumOverwritten, Elt);
593
594     // Insert the non-overwritten middle part.
595     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
596     return I;
597   }
598
599   template<typename ItTy>
600   iterator insert(iterator I, ItTy From, ItTy To) {
601     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
602     size_t InsertElt = I - this->begin();
603
604     if (I == this->end()) {  // Important special case for empty vector.
605       append(From, To);
606       return this->begin()+InsertElt;
607     }
608
609     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
610     assert(I <= this->end() && "Inserting past the end of the vector.");
611
612     size_t NumToInsert = std::distance(From, To);
613
614     // Ensure there is enough space.
615     reserve(static_cast<unsigned>(this->size() + NumToInsert));
616
617     // Uninvalidate the iterator.
618     I = this->begin()+InsertElt;
619
620     // If there are more elements between the insertion point and the end of the
621     // range than there are being inserted, we can use a simple approach to
622     // insertion.  Since we already reserved space, we know that this won't
623     // reallocate the vector.
624     if (size_t(this->end()-I) >= NumToInsert) {
625       T *OldEnd = this->end();
626       append(this->end()-NumToInsert, this->end());
627
628       // Copy the existing elements that get replaced.
629       this->move_backward(I, OldEnd-NumToInsert, OldEnd);
630
631       std::copy(From, To, I);
632       return I;
633     }
634
635     // Otherwise, we're inserting more elements than exist already, and we're
636     // not inserting at the end.
637
638     // Move over the elements that we're about to overwrite.
639     T *OldEnd = this->end();
640     this->setEnd(this->end() + NumToInsert);
641     size_t NumOverwritten = OldEnd-I;
642     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
643
644     // Replace the overwritten part.
645     for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
646       *J = *From;
647       ++J; ++From;
648     }
649
650     // Insert the non-overwritten middle part.
651     this->uninitialized_copy(From, To, OldEnd);
652     return I;
653   }
654
655   SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
656
657   SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
658
659   bool operator==(const SmallVectorImpl &RHS) const {
660     if (this->size() != RHS.size()) return false;
661     return std::equal(this->begin(), this->end(), RHS.begin());
662   }
663   bool operator!=(const SmallVectorImpl &RHS) const {
664     return !(*this == RHS);
665   }
666
667   bool operator<(const SmallVectorImpl &RHS) const {
668     return std::lexicographical_compare(this->begin(), this->end(),
669                                         RHS.begin(), RHS.end());
670   }
671
672   /// Set the array size to \p N, which the current array must have enough
673   /// capacity for.
674   ///
675   /// This does not construct or destroy any elements in the vector.
676   ///
677   /// Clients can use this in conjunction with capacity() to write past the end
678   /// of the buffer when they know that more elements are available, and only
679   /// update the size later. This avoids the cost of value initializing elements
680   /// which will only be overwritten.
681   void set_size(unsigned N) {
682     assert(N <= this->capacity());
683     this->setEnd(this->begin() + N);
684   }
685 };
686
687
688 template <typename T>
689 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
690   if (this == &RHS) return;
691
692   // We can only avoid copying elements if neither vector is small.
693   if (!this->isSmall() && !RHS.isSmall()) {
694     std::swap(this->BeginX, RHS.BeginX);
695     std::swap(this->EndX, RHS.EndX);
696     std::swap(this->CapacityX, RHS.CapacityX);
697     return;
698   }
699   if (RHS.size() > this->capacity())
700     this->grow(RHS.size());
701   if (this->size() > RHS.capacity())
702     RHS.grow(this->size());
703
704   // Swap the shared elements.
705   size_t NumShared = this->size();
706   if (NumShared > RHS.size()) NumShared = RHS.size();
707   for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
708     std::swap((*this)[i], RHS[i]);
709
710   // Copy over the extra elts.
711   if (this->size() > RHS.size()) {
712     size_t EltDiff = this->size() - RHS.size();
713     this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
714     RHS.setEnd(RHS.end()+EltDiff);
715     this->destroy_range(this->begin()+NumShared, this->end());
716     this->setEnd(this->begin()+NumShared);
717   } else if (RHS.size() > this->size()) {
718     size_t EltDiff = RHS.size() - this->size();
719     this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
720     this->setEnd(this->end() + EltDiff);
721     this->destroy_range(RHS.begin()+NumShared, RHS.end());
722     RHS.setEnd(RHS.begin()+NumShared);
723   }
724 }
725
726 template <typename T>
727 SmallVectorImpl<T> &SmallVectorImpl<T>::
728   operator=(const SmallVectorImpl<T> &RHS) {
729   // Avoid self-assignment.
730   if (this == &RHS) return *this;
731
732   // If we already have sufficient space, assign the common elements, then
733   // destroy any excess.
734   size_t RHSSize = RHS.size();
735   size_t CurSize = this->size();
736   if (CurSize >= RHSSize) {
737     // Assign common elements.
738     iterator NewEnd;
739     if (RHSSize)
740       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
741     else
742       NewEnd = this->begin();
743
744     // Destroy excess elements.
745     this->destroy_range(NewEnd, this->end());
746
747     // Trim.
748     this->setEnd(NewEnd);
749     return *this;
750   }
751
752   // If we have to grow to have enough elements, destroy the current elements.
753   // This allows us to avoid copying them during the grow.
754   // FIXME: don't do this if they're efficiently moveable.
755   if (this->capacity() < RHSSize) {
756     // Destroy current elements.
757     this->destroy_range(this->begin(), this->end());
758     this->setEnd(this->begin());
759     CurSize = 0;
760     this->grow(RHSSize);
761   } else if (CurSize) {
762     // Otherwise, use assignment for the already-constructed elements.
763     std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
764   }
765
766   // Copy construct the new elements in place.
767   this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
768                            this->begin()+CurSize);
769
770   // Set end.
771   this->setEnd(this->begin()+RHSSize);
772   return *this;
773 }
774
775 template <typename T>
776 SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
777   // Avoid self-assignment.
778   if (this == &RHS) return *this;
779
780   // If the RHS isn't small, clear this vector and then steal its buffer.
781   if (!RHS.isSmall()) {
782     this->destroy_range(this->begin(), this->end());
783     if (!this->isSmall()) free(this->begin());
784     this->BeginX = RHS.BeginX;
785     this->EndX = RHS.EndX;
786     this->CapacityX = RHS.CapacityX;
787     RHS.resetToSmall();
788     return *this;
789   }
790
791   // If we already have sufficient space, assign the common elements, then
792   // destroy any excess.
793   size_t RHSSize = RHS.size();
794   size_t CurSize = this->size();
795   if (CurSize >= RHSSize) {
796     // Assign common elements.
797     iterator NewEnd = this->begin();
798     if (RHSSize)
799       NewEnd = this->move(RHS.begin(), RHS.end(), NewEnd);
800
801     // Destroy excess elements and trim the bounds.
802     this->destroy_range(NewEnd, this->end());
803     this->setEnd(NewEnd);
804
805     // Clear the RHS.
806     RHS.clear();
807
808     return *this;
809   }
810
811   // If we have to grow to have enough elements, destroy the current elements.
812   // This allows us to avoid copying them during the grow.
813   // FIXME: this may not actually make any sense if we can efficiently move
814   // elements.
815   if (this->capacity() < RHSSize) {
816     // Destroy current elements.
817     this->destroy_range(this->begin(), this->end());
818     this->setEnd(this->begin());
819     CurSize = 0;
820     this->grow(RHSSize);
821   } else if (CurSize) {
822     // Otherwise, use assignment for the already-constructed elements.
823     this->move(RHS.begin(), RHS.end(), this->begin());
824   }
825
826   // Move-construct the new elements in place.
827   this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
828                            this->begin()+CurSize);
829
830   // Set end.
831   this->setEnd(this->begin()+RHSSize);
832
833   RHS.clear();
834   return *this;
835 }
836
837 /// Storage for the SmallVector elements which aren't contained in
838 /// SmallVectorTemplateCommon. There are 'N-1' elements here. The remaining '1'
839 /// element is in the base class. This is specialized for the N=1 and N=0 cases
840 /// to avoid allocating unnecessary storage.
841 template <typename T, unsigned N>
842 struct SmallVectorStorage {
843   typename SmallVectorTemplateCommon<T>::U InlineElts[N - 1];
844 };
845 template <typename T> struct SmallVectorStorage<T, 1> {};
846 template <typename T> struct SmallVectorStorage<T, 0> {};
847
848 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
849 /// for the case when the array is small.  It contains some number of elements
850 /// in-place, which allows it to avoid heap allocation when the actual number of
851 /// elements is below that threshold.  This allows normal "small" cases to be
852 /// fast without losing generality for large inputs.
853 ///
854 /// Note that this does not attempt to be exception safe.
855 ///
856 template <typename T, unsigned N>
857 class SmallVector : public SmallVectorImpl<T> {
858   /// Storage - Inline space for elements which aren't stored in the base class.
859   SmallVectorStorage<T, N> Storage;
860 public:
861   SmallVector() : SmallVectorImpl<T>(N) {
862   }
863
864   explicit SmallVector(unsigned Size, const T &Value = T())
865     : SmallVectorImpl<T>(N) {
866     this->assign(Size, Value);
867   }
868
869   template<typename ItTy>
870   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
871     this->append(S, E);
872   }
873
874   template <typename RangeTy>
875   explicit SmallVector(const llvm::iterator_range<RangeTy> R)
876       : SmallVectorImpl<T>(N) {
877     this->append(R.begin(), R.end());
878   }
879
880   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
881     if (!RHS.empty())
882       SmallVectorImpl<T>::operator=(RHS);
883   }
884
885   const SmallVector &operator=(const SmallVector &RHS) {
886     SmallVectorImpl<T>::operator=(RHS);
887     return *this;
888   }
889
890   SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
891     if (!RHS.empty())
892       SmallVectorImpl<T>::operator=(::std::move(RHS));
893   }
894
895   const SmallVector &operator=(SmallVector &&RHS) {
896     SmallVectorImpl<T>::operator=(::std::move(RHS));
897     return *this;
898   }
899 };
900
901 template<typename T, unsigned N>
902 static inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
903   return X.capacity_in_bytes();
904 }
905
906 } // End llvm namespace
907
908 namespace std {
909   /// Implement std::swap in terms of SmallVector swap.
910   template<typename T>
911   inline void
912   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
913     LHS.swap(RHS);
914   }
915
916   /// Implement std::swap in terms of SmallVector swap.
917   template<typename T, unsigned N>
918   inline void
919   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
920     LHS.swap(RHS);
921   }
922 }
923
924 #endif