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