1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the SmallVector class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_SMALLVECTOR_H
15 #define LLVM_ADT_SMALLVECTOR_H
17 #include "llvm/Support/type_traits.h"
28 // Work around flawed VC++ implementation of std::uninitialized_copy. Define
29 // additional overloads so that elements with pointer types are recognized as
30 // scalars and not objects, causing bizarre type conversion errors.
31 template<class T1, class T2>
32 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
33 _Scalar_ptr_iterator_tag _Cat;
37 template<class T1, class T2>
38 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
39 _Scalar_ptr_iterator_tag _Cat;
43 // FIXME: It is not clear if the problem is fixed in VS 2005. What is clear
44 // is that the above hack won't work if it wasn't fixed.
51 /// SmallVectorBase - This is all the non-templated stuff common to all
53 class SmallVectorBase {
55 void *BeginX, *EndX, *CapacityX;
57 // Allocate raw space for N elements of type T. If T has a ctor or dtor, we
58 // don't want it to be automatically run, so we need to represent the space as
59 // something else. An array of char would work great, but might not be
60 // aligned sufficiently. Instead we use some number of union instances for
61 // the space, which guarantee maximal alignment.
68 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
71 SmallVectorBase(size_t Size)
72 : BeginX(&FirstEl), EndX(&FirstEl), CapacityX((char*)&FirstEl+Size) {}
74 /// isSmall - Return true if this is a smallvector which has not had dynamic
75 /// memory allocated for it.
76 bool isSmall() const {
77 return BeginX == static_cast<const void*>(&FirstEl);
80 /// size_in_bytes - This returns size()*sizeof(T).
81 size_t size_in_bytes() const {
82 return size_t((char*)EndX - (char*)BeginX);
85 /// capacity_in_bytes - This returns capacity()*sizeof(T).
86 size_t capacity_in_bytes() const {
87 return size_t((char*)CapacityX - (char*)BeginX);
90 /// grow_pod - This is an implementation of the grow() method which only works
91 /// on POD-like data types and is out of line to reduce code duplication.
92 void grow_pod(size_t MinSizeInBytes, size_t TSize);
95 bool empty() const { return BeginX == EndX; }
100 class SmallVectorTemplateCommon : public SmallVectorBase {
102 void setEnd(T *P) { this->EndX = P; }
104 SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {}
106 typedef size_t size_type;
107 typedef ptrdiff_t difference_type;
108 typedef T value_type;
110 typedef const T *const_iterator;
112 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
113 typedef std::reverse_iterator<iterator> reverse_iterator;
115 typedef T &reference;
116 typedef const T &const_reference;
118 typedef const T *const_pointer;
120 // forward iterator creation methods.
121 iterator begin() { return (iterator)this->BeginX; }
122 const_iterator begin() const { return (const_iterator)this->BeginX; }
123 iterator end() { return (iterator)this->EndX; }
124 const_iterator end() const { return (const_iterator)this->EndX; }
126 iterator capacity_ptr() { return (iterator)this->CapacityX; }
127 const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
130 // reverse iterator creation methods.
131 reverse_iterator rbegin() { return reverse_iterator(end()); }
132 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
133 reverse_iterator rend() { return reverse_iterator(begin()); }
134 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
136 size_type size() const { return end()-begin(); }
137 size_type max_size() const { return size_type(-1) / sizeof(T); }
139 /// capacity - Return the total number of elements in the currently allocated
141 size_t capacity() const { return capacity_ptr() - begin(); }
143 /// data - Return a pointer to the vector's buffer, even if empty().
144 pointer data() { return pointer(begin()); }
145 /// data - Return a pointer to the vector's buffer, even if empty().
146 const_pointer data() const { return const_pointer(begin()); }
148 reference operator[](unsigned idx) {
149 assert(begin() + idx < end());
152 const_reference operator[](unsigned idx) const {
153 assert(begin() + idx < end());
160 const_reference front() const {
167 const_reference back() const {
172 /// SmallVectorTemplateBase<isPodLike = false> - This is where we put method
173 /// implementations that are designed to work with non-POD-like T's.
174 template <typename T, bool isPodLike>
175 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
177 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
179 static void destroy_range(T *S, T *E) {
186 /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
187 /// starting with "Dest", constructing elements into it as needed.
188 template<typename It1, typename It2>
189 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
190 std::uninitialized_copy(I, E, Dest);
193 /// grow - double the size of the allocated memory, guaranteeing space for at
194 /// least one more element or MinSize if specified.
195 void grow(size_t MinSize = 0);
198 // Define this out-of-line to dissuade the C++ compiler from inlining it.
199 template <typename T, bool isPodLike>
200 void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
201 size_t CurCapacity = this->capacity();
202 size_t CurSize = this->size();
203 size_t NewCapacity = 2*CurCapacity + 1; // Always grow, even from zero.
204 if (NewCapacity < MinSize)
205 NewCapacity = MinSize;
206 T *NewElts = static_cast<T*>(malloc(NewCapacity*sizeof(T)));
208 // Copy the elements over.
209 this->uninitialized_copy(this->begin(), this->end(), NewElts);
211 // Destroy the original elements.
212 destroy_range(this->begin(), this->end());
214 // If this wasn't grown from the inline copy, deallocate the old space.
215 if (!this->isSmall())
218 this->setEnd(NewElts+CurSize);
219 this->BeginX = NewElts;
220 this->CapacityX = this->begin()+NewCapacity;
224 /// SmallVectorTemplateBase<isPodLike = true> - This is where we put method
225 /// implementations that are designed to work with POD-like T's.
226 template <typename T>
227 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
229 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
231 // No need to do a destroy loop for POD's.
232 static void destroy_range(T *, T *) {}
234 /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
235 /// starting with "Dest", constructing elements into it as needed.
236 template<typename It1, typename It2>
237 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
238 // Arbitrary iterator types; just use the basic implementation.
239 std::uninitialized_copy(I, E, Dest);
242 /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
243 /// starting with "Dest", constructing elements into it as needed.
244 template<typename T1, typename T2>
245 static void uninitialized_copy(T1 *I, T1 *E, T2 *Dest) {
246 // Use memcpy for PODs iterated by pointers (which includes SmallVector
247 // iterators): std::uninitialized_copy optimizes to memmove, but we can
249 memcpy(Dest, I, (E-I)*sizeof(T));
252 /// grow - double the size of the allocated memory, guaranteeing space for at
253 /// least one more element or MinSize if specified.
254 void grow(size_t MinSize = 0) {
255 this->grow_pod(MinSize*sizeof(T), sizeof(T));
260 /// SmallVectorImpl - This class consists of common code factored out of the
261 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
262 /// template parameter.
263 template <typename T>
264 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
265 typedef SmallVectorTemplateBase<T, isPodLike<T>::value > SuperClass;
267 SmallVectorImpl(const SmallVectorImpl&); // DISABLED.
269 typedef typename SuperClass::iterator iterator;
270 typedef typename SuperClass::size_type size_type;
272 // Default ctor - Initialize to empty.
273 explicit SmallVectorImpl(unsigned N)
274 : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
278 // Destroy the constructed elements in the vector.
279 this->destroy_range(this->begin(), this->end());
281 // If this wasn't grown from the inline copy, deallocate the old space.
282 if (!this->isSmall())
288 this->destroy_range(this->begin(), this->end());
289 this->EndX = this->BeginX;
292 void resize(unsigned N) {
293 if (N < this->size()) {
294 this->destroy_range(this->begin()+N, this->end());
295 this->setEnd(this->begin()+N);
296 } else if (N > this->size()) {
297 if (this->capacity() < N)
299 this->construct_range(this->end(), this->begin()+N, T());
300 this->setEnd(this->begin()+N);
304 void resize(unsigned N, const T &NV) {
305 if (N < this->size()) {
306 this->destroy_range(this->begin()+N, this->end());
307 this->setEnd(this->begin()+N);
308 } else if (N > this->size()) {
309 if (this->capacity() < N)
311 construct_range(this->end(), this->begin()+N, NV);
312 this->setEnd(this->begin()+N);
316 void reserve(unsigned N) {
317 if (this->capacity() < N)
321 void push_back(const T &Elt) {
322 if (this->EndX < this->CapacityX) {
324 new (this->end()) T(Elt);
325 this->setEnd(this->end()+1);
333 this->setEnd(this->end()-1);
338 T Result = this->back();
343 void swap(SmallVectorImpl &RHS);
345 /// append - Add the specified range to the end of the SmallVector.
347 template<typename in_iter>
348 void append(in_iter in_start, in_iter in_end) {
349 size_type NumInputs = std::distance(in_start, in_end);
350 // Grow allocated space if needed.
351 if (NumInputs > size_type(this->capacity_ptr()-this->end()))
352 this->grow(this->size()+NumInputs);
354 // Copy the new elements over.
355 // TODO: NEED To compile time dispatch on whether in_iter is a random access
356 // iterator to use the fast uninitialized_copy.
357 std::uninitialized_copy(in_start, in_end, this->end());
358 this->setEnd(this->end() + NumInputs);
361 /// append - Add the specified range to the end of the SmallVector.
363 void append(size_type NumInputs, const T &Elt) {
364 // Grow allocated space if needed.
365 if (NumInputs > size_type(this->capacity_ptr()-this->end()))
366 this->grow(this->size()+NumInputs);
368 // Copy the new elements over.
369 std::uninitialized_fill_n(this->end(), NumInputs, Elt);
370 this->setEnd(this->end() + NumInputs);
373 void assign(unsigned NumElts, const T &Elt) {
375 if (this->capacity() < NumElts)
377 this->setEnd(this->begin()+NumElts);
378 construct_range(this->begin(), this->end(), Elt);
381 iterator erase(iterator I) {
383 // Shift all elts down one.
384 std::copy(I+1, this->end(), I);
385 // Drop the last elt.
390 iterator erase(iterator S, iterator E) {
392 // Shift all elts down.
393 iterator I = std::copy(E, this->end(), S);
394 // Drop the last elts.
395 this->destroy_range(I, this->end());
400 iterator insert(iterator I, const T &Elt) {
401 if (I == this->end()) { // Important special case for empty vector.
403 return this->end()-1;
406 if (this->EndX < this->CapacityX) {
408 new (this->end()) T(this->back());
409 this->setEnd(this->end()+1);
410 // Push everything else over.
411 std::copy_backward(I, this->end()-1, this->end());
415 size_t EltNo = I-this->begin();
417 I = this->begin()+EltNo;
421 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
422 if (I == this->end()) { // Important special case for empty vector.
423 append(NumToInsert, Elt);
424 return this->end()-1;
427 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
428 size_t InsertElt = I - this->begin();
430 // Ensure there is enough space.
431 reserve(static_cast<unsigned>(this->size() + NumToInsert));
433 // Uninvalidate the iterator.
434 I = this->begin()+InsertElt;
436 // If there are more elements between the insertion point and the end of the
437 // range than there are being inserted, we can use a simple approach to
438 // insertion. Since we already reserved space, we know that this won't
439 // reallocate the vector.
440 if (size_t(this->end()-I) >= NumToInsert) {
441 T *OldEnd = this->end();
442 append(this->end()-NumToInsert, this->end());
444 // Copy the existing elements that get replaced.
445 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
447 std::fill_n(I, NumToInsert, Elt);
451 // Otherwise, we're inserting more elements than exist already, and we're
452 // not inserting at the end.
454 // Copy over the elements that we're about to overwrite.
455 T *OldEnd = this->end();
456 this->setEnd(this->end() + NumToInsert);
457 size_t NumOverwritten = OldEnd-I;
458 this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
460 // Replace the overwritten part.
461 std::fill_n(I, NumOverwritten, Elt);
463 // Insert the non-overwritten middle part.
464 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
468 template<typename ItTy>
469 iterator insert(iterator I, ItTy From, ItTy To) {
470 if (I == this->end()) { // Important special case for empty vector.
472 return this->end()-1;
475 size_t NumToInsert = std::distance(From, To);
476 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
477 size_t InsertElt = I - this->begin();
479 // Ensure there is enough space.
480 reserve(static_cast<unsigned>(this->size() + NumToInsert));
482 // Uninvalidate the iterator.
483 I = this->begin()+InsertElt;
485 // If there are more elements between the insertion point and the end of the
486 // range than there are being inserted, we can use a simple approach to
487 // insertion. Since we already reserved space, we know that this won't
488 // reallocate the vector.
489 if (size_t(this->end()-I) >= NumToInsert) {
490 T *OldEnd = this->end();
491 append(this->end()-NumToInsert, this->end());
493 // Copy the existing elements that get replaced.
494 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
496 std::copy(From, To, I);
500 // Otherwise, we're inserting more elements than exist already, and we're
501 // not inserting at the end.
503 // Copy over the elements that we're about to overwrite.
504 T *OldEnd = this->end();
505 this->setEnd(this->end() + NumToInsert);
506 size_t NumOverwritten = OldEnd-I;
507 this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
509 // Replace the overwritten part.
510 for (; NumOverwritten > 0; --NumOverwritten) {
515 // Insert the non-overwritten middle part.
516 this->uninitialized_copy(From, To, OldEnd);
520 const SmallVectorImpl
521 &operator=(const SmallVectorImpl &RHS);
523 bool operator==(const SmallVectorImpl &RHS) const {
524 if (this->size() != RHS.size()) return false;
525 return std::equal(this->begin(), this->end(), RHS.begin());
527 bool operator!=(const SmallVectorImpl &RHS) const {
528 return !(*this == RHS);
531 bool operator<(const SmallVectorImpl &RHS) const {
532 return std::lexicographical_compare(this->begin(), this->end(),
533 RHS.begin(), RHS.end());
536 /// set_size - Set the array size to \arg N, which the current array must have
537 /// enough capacity for.
539 /// This does not construct or destroy any elements in the vector.
541 /// Clients can use this in conjunction with capacity() to write past the end
542 /// of the buffer when they know that more elements are available, and only
543 /// update the size later. This avoids the cost of value initializing elements
544 /// which will only be overwritten.
545 void set_size(unsigned N) {
546 assert(N <= this->capacity());
547 this->setEnd(this->begin() + N);
551 static void construct_range(T *S, T *E, const T &Elt) {
558 template <typename T>
559 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
560 if (this == &RHS) return;
562 // We can only avoid copying elements if neither vector is small.
563 if (!this->isSmall() && !RHS.isSmall()) {
564 std::swap(this->BeginX, RHS.BeginX);
565 std::swap(this->EndX, RHS.EndX);
566 std::swap(this->CapacityX, RHS.CapacityX);
569 if (RHS.size() > this->capacity())
570 this->grow(RHS.size());
571 if (this->size() > RHS.capacity())
572 RHS.grow(this->size());
574 // Swap the shared elements.
575 size_t NumShared = this->size();
576 if (NumShared > RHS.size()) NumShared = RHS.size();
577 for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
578 std::swap((*this)[i], RHS[i]);
580 // Copy over the extra elts.
581 if (this->size() > RHS.size()) {
582 size_t EltDiff = this->size() - RHS.size();
583 this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
584 RHS.setEnd(RHS.end()+EltDiff);
585 this->destroy_range(this->begin()+NumShared, this->end());
586 this->setEnd(this->begin()+NumShared);
587 } else if (RHS.size() > this->size()) {
588 size_t EltDiff = RHS.size() - this->size();
589 this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
590 this->setEnd(this->end() + EltDiff);
591 this->destroy_range(RHS.begin()+NumShared, RHS.end());
592 RHS.setEnd(RHS.begin()+NumShared);
596 template <typename T>
597 const SmallVectorImpl<T> &SmallVectorImpl<T>::
598 operator=(const SmallVectorImpl<T> &RHS) {
599 // Avoid self-assignment.
600 if (this == &RHS) return *this;
602 // If we already have sufficient space, assign the common elements, then
603 // destroy any excess.
604 size_t RHSSize = RHS.size();
605 size_t CurSize = this->size();
606 if (CurSize >= RHSSize) {
607 // Assign common elements.
610 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
612 NewEnd = this->begin();
614 // Destroy excess elements.
615 this->destroy_range(NewEnd, this->end());
618 this->setEnd(NewEnd);
622 // If we have to grow to have enough elements, destroy the current elements.
623 // This allows us to avoid copying them during the grow.
624 if (this->capacity() < RHSSize) {
625 // Destroy current elements.
626 this->destroy_range(this->begin(), this->end());
627 this->setEnd(this->begin());
630 } else if (CurSize) {
631 // Otherwise, use assignment for the already-constructed elements.
632 std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
635 // Copy construct the new elements in place.
636 this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
637 this->begin()+CurSize);
640 this->setEnd(this->begin()+RHSSize);
645 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
646 /// for the case when the array is small. It contains some number of elements
647 /// in-place, which allows it to avoid heap allocation when the actual number of
648 /// elements is below that threshold. This allows normal "small" cases to be
649 /// fast without losing generality for large inputs.
651 /// Note that this does not attempt to be exception safe.
653 template <typename T, unsigned N>
654 class SmallVector : public SmallVectorImpl<T> {
655 /// InlineElts - These are 'N-1' elements that are stored inline in the body
656 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
657 typedef typename SmallVectorImpl<T>::U U;
659 // MinUs - The number of U's require to cover N T's.
660 MinUs = (static_cast<unsigned int>(sizeof(T))*N +
661 static_cast<unsigned int>(sizeof(U)) - 1) /
662 static_cast<unsigned int>(sizeof(U)),
664 // NumInlineEltsElts - The number of elements actually in this array. There
665 // is already one in the parent class, and we have to round up to avoid
666 // having a zero-element array.
667 NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
669 // NumTsAvailable - The number of T's we actually have space for, which may
670 // be more than N due to rounding.
671 NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
672 static_cast<unsigned int>(sizeof(T))
674 U InlineElts[NumInlineEltsElts];
676 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
679 explicit SmallVector(unsigned Size, const T &Value = T())
680 : SmallVectorImpl<T>(NumTsAvailable) {
683 this->push_back(Value);
686 template<typename ItTy>
687 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
691 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
693 SmallVectorImpl<T>::operator=(RHS);
696 const SmallVector &operator=(const SmallVector &RHS) {
697 SmallVectorImpl<T>::operator=(RHS);
703 /// Specialize SmallVector at N=0. This specialization guarantees
704 /// that it can be instantiated at an incomplete T if none of its
705 /// members are required.
706 template <typename T>
707 class SmallVector<T,0> : public SmallVectorImpl<T> {
709 SmallVector() : SmallVectorImpl<T>(0) {}
711 explicit SmallVector(unsigned Size, const T &Value = T())
712 : SmallVectorImpl<T>(0) {
715 this->push_back(Value);
718 template<typename ItTy>
719 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(0) {
723 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(0) {
724 SmallVectorImpl<T>::operator=(RHS);
727 SmallVector &operator=(const SmallVectorImpl<T> &RHS) {
728 return SmallVectorImpl<T>::operator=(RHS);
733 } // End llvm namespace
736 /// Implement std::swap in terms of SmallVector swap.
739 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
743 /// Implement std::swap in terms of SmallVector swap.
744 template<typename T, unsigned N>
746 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {