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"
26 // Work around flawed VC++ implementation of std::uninitialized_copy. Define
27 // additional overloads so that elements with pointer types are recognized as
28 // scalars and not objects, causing bizarre type conversion errors.
29 template<class T1, class T2>
30 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
31 _Scalar_ptr_iterator_tag _Cat;
35 template<class T1, class T2>
36 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
37 _Scalar_ptr_iterator_tag _Cat;
41 // FIXME: It is not clear if the problem is fixed in VS 2005. What is clear
42 // is that the above hack won't work if it wasn't fixed.
49 /// SmallVectorBase - This is all the non-templated stuff common to all
51 class SmallVectorBase {
53 void *BeginX, *EndX, *CapacityX;
55 // Allocate raw space for N elements of type T. If T has a ctor or dtor, we
56 // don't want it to be automatically run, so we need to represent the space as
57 // something else. An array of char would work great, but might not be
58 // aligned sufficiently. Instead, we either use GCC extensions, or some
59 // number of union instances for the space, which guarantee maximal alignment.
62 U FirstEl __attribute__((aligned));
71 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
74 SmallVectorBase(size_t Size)
75 : BeginX(&FirstEl), EndX(&FirstEl), CapacityX((char*)&FirstEl+Size) {}
77 /// isSmall - Return true if this is a smallvector which has not had dynamic
78 /// memory allocated for it.
79 bool isSmall() const {
80 return BeginX == static_cast<const void*>(&FirstEl);
84 bool empty() const { return BeginX == EndX; }
88 class SmallVectorTemplateCommon : public SmallVectorBase {
89 void setEnd(T *P) { this->EndX = P; }
91 SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {}
93 ~SmallVectorTemplateCommon() {
94 // Destroy the constructed elements in the vector.
95 destroy_range(begin(), end());
97 // If this wasn't grown from the inline copy, deallocate the old space.
99 operator delete(begin());
102 typedef size_t size_type;
103 typedef ptrdiff_t difference_type;
104 typedef T value_type;
106 typedef const T *const_iterator;
108 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
109 typedef std::reverse_iterator<iterator> reverse_iterator;
111 typedef T &reference;
112 typedef const T &const_reference;
114 typedef const T *const_pointer;
116 // forward iterator creation methods.
117 iterator begin() { return (iterator)this->BeginX; }
118 const_iterator begin() const { return (const_iterator)this->BeginX; }
119 iterator end() { return (iterator)this->EndX; }
120 const_iterator end() const { return (const_iterator)this->EndX; }
122 iterator capacity_ptr() { return (iterator)this->CapacityX; }
123 const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
126 // reverse iterator creation methods.
127 reverse_iterator rbegin() { return reverse_iterator(end()); }
128 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
129 reverse_iterator rend() { return reverse_iterator(begin()); }
130 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
132 size_type size() const { return end()-begin(); }
133 size_type max_size() const { return size_type(-1) / sizeof(T); }
135 /// capacity - Return the total number of elements in the currently allocated
137 size_t capacity() const { return capacity_ptr() - begin(); }
139 /// data - Return a pointer to the vector's buffer, even if empty().
140 pointer data() { return pointer(begin()); }
141 /// data - Return a pointer to the vector's buffer, even if empty().
142 const_pointer data() const { return const_pointer(begin()); }
144 reference operator[](unsigned idx) {
145 assert(begin() + idx < end());
148 const_reference operator[](unsigned idx) const {
149 assert(begin() + idx < end());
156 const_reference front() const {
163 const_reference back() const {
167 void push_back(const_reference Elt) {
168 if (this->EndX < this->CapacityX) {
190 destroy_range(begin(), end());
191 this->EndX = this->BeginX;
194 void resize(unsigned N) {
196 destroy_range(begin()+N, end());
198 } else if (N > size()) {
201 construct_range(end(), begin()+N, T());
206 void resize(unsigned N, const T &NV) {
208 destroy_range(begin()+N, end());
210 } else if (N > size()) {
213 construct_range(end(), begin()+N, NV);
218 void reserve(unsigned N) {
223 void swap(SmallVectorTemplateCommon &RHS);
225 /// append - Add the specified range to the end of the SmallVector.
227 template<typename in_iter>
228 void append(in_iter in_start, in_iter in_end) {
229 size_type NumInputs = std::distance(in_start, in_end);
230 // Grow allocated space if needed.
231 if (NumInputs > size_type(capacity_ptr()-end()))
232 grow(size()+NumInputs);
234 // Copy the new elements over.
235 // TODO: NEED To compile time dispatch on whether in_iter is a random access
236 // iterator to use the fast uninitialized_copy.
237 std::uninitialized_copy(in_start, in_end, end());
238 setEnd(end() + NumInputs);
241 /// append - Add the specified range to the end of the SmallVector.
243 void append(size_type NumInputs, const T &Elt) {
244 // Grow allocated space if needed.
245 if (NumInputs > size_type(capacity_ptr()-end()))
246 grow(size()+NumInputs);
248 // Copy the new elements over.
249 std::uninitialized_fill_n(end(), NumInputs, Elt);
250 setEnd(end() + NumInputs);
253 void assign(unsigned NumElts, const T &Elt) {
255 if (capacity() < NumElts)
257 setEnd(begin()+NumElts);
258 construct_range(begin(), end(), Elt);
261 iterator erase(iterator I) {
263 // Shift all elts down one.
264 std::copy(I+1, end(), I);
265 // Drop the last elt.
270 iterator erase(iterator S, iterator E) {
272 // Shift all elts down.
273 iterator I = std::copy(E, end(), S);
274 // Drop the last elts.
275 destroy_range(I, end());
280 iterator insert(iterator I, const T &Elt) {
281 if (I == end()) { // Important special case for empty vector.
286 if (this->EndX < this->CapacityX) {
288 new (end()) T(back());
290 // Push everything else over.
291 std::copy_backward(I, end()-1, end());
295 size_t EltNo = I-begin();
301 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
302 if (I == end()) { // Important special case for empty vector.
303 append(NumToInsert, Elt);
307 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
308 size_t InsertElt = I-begin();
310 // Ensure there is enough space.
311 reserve(static_cast<unsigned>(size() + NumToInsert));
313 // Uninvalidate the iterator.
314 I = begin()+InsertElt;
316 // If there are more elements between the insertion point and the end of the
317 // range than there are being inserted, we can use a simple approach to
318 // insertion. Since we already reserved space, we know that this won't
319 // reallocate the vector.
320 if (size_t(end()-I) >= NumToInsert) {
322 append(end()-NumToInsert, end());
324 // Copy the existing elements that get replaced.
325 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
327 std::fill_n(I, NumToInsert, Elt);
331 // Otherwise, we're inserting more elements than exist already, and we're
332 // not inserting at the end.
334 // Copy over the elements that we're about to overwrite.
336 setEnd(end() + NumToInsert);
337 size_t NumOverwritten = OldEnd-I;
338 uninitialized_copy(I, OldEnd, end()-NumOverwritten);
340 // Replace the overwritten part.
341 std::fill_n(I, NumOverwritten, Elt);
343 // Insert the non-overwritten middle part.
344 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
348 template<typename ItTy>
349 iterator insert(iterator I, ItTy From, ItTy To) {
350 if (I == end()) { // Important special case for empty vector.
355 size_t NumToInsert = std::distance(From, To);
356 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
357 size_t InsertElt = I-begin();
359 // Ensure there is enough space.
360 reserve(static_cast<unsigned>(size() + NumToInsert));
362 // Uninvalidate the iterator.
363 I = begin()+InsertElt;
365 // If there are more elements between the insertion point and the end of the
366 // range than there are being inserted, we can use a simple approach to
367 // insertion. Since we already reserved space, we know that this won't
368 // reallocate the vector.
369 if (size_t(end()-I) >= NumToInsert) {
371 append(end()-NumToInsert, end());
373 // Copy the existing elements that get replaced.
374 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
376 std::copy(From, To, I);
380 // Otherwise, we're inserting more elements than exist already, and we're
381 // not inserting at the end.
383 // Copy over the elements that we're about to overwrite.
385 setEnd(end() + NumToInsert);
386 size_t NumOverwritten = OldEnd-I;
387 uninitialized_copy(I, OldEnd, end()-NumOverwritten);
389 // Replace the overwritten part.
390 std::copy(From, From+NumOverwritten, I);
392 // Insert the non-overwritten middle part.
393 uninitialized_copy(From+NumOverwritten, To, OldEnd);
397 const SmallVectorTemplateCommon
398 &operator=(const SmallVectorTemplateCommon &RHS);
400 bool operator==(const SmallVectorTemplateCommon &RHS) const {
401 if (size() != RHS.size()) return false;
402 return std::equal(begin(), end(), RHS.begin());
404 bool operator!=(const SmallVectorTemplateCommon &RHS) const {
405 return !(*this == RHS);
408 bool operator<(const SmallVectorTemplateCommon &RHS) const {
409 return std::lexicographical_compare(begin(), end(),
410 RHS.begin(), RHS.end());
413 /// set_size - Set the array size to \arg N, which the current array must have
414 /// enough capacity for.
416 /// This does not construct or destroy any elements in the vector.
418 /// Clients can use this in conjunction with capacity() to write past the end
419 /// of the buffer when they know that more elements are available, and only
420 /// update the size later. This avoids the cost of value initializing elements
421 /// which will only be overwritten.
422 void set_size(unsigned N) {
423 assert(N <= capacity());
428 /// grow - double the size of the allocated memory, guaranteeing space for at
429 /// least one more element or MinSize if specified.
430 void grow(size_type MinSize = 0);
432 static void construct_range(T *S, T *E, const T &Elt) {
437 static void destroy_range(T *S, T *E) {
438 // No need to do a destroy loop for POD's.
439 if (isPodLike<T>::value) return;
447 /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
448 /// starting with "Dest", constructing elements into it as needed.
449 template<typename It1, typename It2>
450 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
451 // Use memcpy for PODs: std::uninitialized_copy optimizes to memmove.
452 if (isPodLike<T>::value)
453 memcpy(&*Dest, &*I, (E-I)*sizeof(T));
455 std::uninitialized_copy(I, E, Dest);
460 // Define this out-of-line to dissuade the C++ compiler from inlining it.
461 template <typename T>
462 void SmallVectorTemplateCommon<T>::grow(size_t MinSize) {
463 size_t CurCapacity = capacity();
464 size_t CurSize = size();
465 size_t NewCapacity = 2*CurCapacity;
466 if (NewCapacity < MinSize)
467 NewCapacity = MinSize;
468 T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
470 // Copy the elements over.
471 uninitialized_copy(begin(), end(), NewElts);
473 // Destroy the original elements.
474 destroy_range(begin(), end());
476 // If this wasn't grown from the inline copy, deallocate the old space.
477 if (!this->isSmall())
478 operator delete(begin());
480 setEnd(NewElts+CurSize);
481 this->BeginX = NewElts;
482 this->CapacityX = begin()+NewCapacity;
485 template <typename T>
486 void SmallVectorTemplateCommon<T>::swap(SmallVectorTemplateCommon<T> &RHS) {
487 if (this == &RHS) return;
489 // We can only avoid copying elements if neither vector is small.
490 if (!this->isSmall() && !RHS.isSmall()) {
491 std::swap(this->BeginX, RHS.BeginX);
492 std::swap(this->EndX, RHS.EndX);
493 std::swap(this->CapacityX, RHS.CapacityX);
496 if (RHS.size() > capacity())
498 if (size() > RHS.capacity())
501 // Swap the shared elements.
502 size_t NumShared = size();
503 if (NumShared > RHS.size()) NumShared = RHS.size();
504 for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
505 std::swap((*this)[i], RHS[i]);
507 // Copy over the extra elts.
508 if (size() > RHS.size()) {
509 size_t EltDiff = size() - RHS.size();
510 uninitialized_copy(begin()+NumShared, end(), RHS.end());
511 RHS.setEnd(RHS.end()+EltDiff);
512 destroy_range(begin()+NumShared, end());
513 setEnd(begin()+NumShared);
514 } else if (RHS.size() > size()) {
515 size_t EltDiff = RHS.size() - size();
516 uninitialized_copy(RHS.begin()+NumShared, RHS.end(), end());
517 setEnd(end() + EltDiff);
518 destroy_range(RHS.begin()+NumShared, RHS.end());
519 RHS.setEnd(RHS.begin()+NumShared);
523 template <typename T>
524 const SmallVectorTemplateCommon<T> &
525 SmallVectorTemplateCommon<T>::
526 operator=(const SmallVectorTemplateCommon<T> &RHS) {
527 // Avoid self-assignment.
528 if (this == &RHS) return *this;
530 // If we already have sufficient space, assign the common elements, then
531 // destroy any excess.
532 size_t RHSSize = RHS.size();
533 size_t CurSize = size();
534 if (CurSize >= RHSSize) {
535 // Assign common elements.
538 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, begin());
542 // Destroy excess elements.
543 destroy_range(NewEnd, end());
550 // If we have to grow to have enough elements, destroy the current elements.
551 // This allows us to avoid copying them during the grow.
552 if (capacity() < RHSSize) {
553 // Destroy current elements.
554 destroy_range(begin(), end());
558 } else if (CurSize) {
559 // Otherwise, use assignment for the already-constructed elements.
560 std::copy(RHS.begin(), RHS.begin()+CurSize, begin());
563 // Copy construct the new elements in place.
564 uninitialized_copy(RHS.begin()+CurSize, RHS.end(), begin()+CurSize);
567 setEnd(begin()+RHSSize);
572 template <typename T, bool isPodLike>
573 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
575 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
579 template <typename T>
580 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
582 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
587 /// SmallVectorImpl - This class consists of common code factored out of the
588 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
589 /// template parameter.
590 template <typename T>
591 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
593 // Default ctor - Initialize to empty.
594 explicit SmallVectorImpl(unsigned N)
595 : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
599 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
600 /// for the case when the array is small. It contains some number of elements
601 /// in-place, which allows it to avoid heap allocation when the actual number of
602 /// elements is below that threshold. This allows normal "small" cases to be
603 /// fast without losing generality for large inputs.
605 /// Note that this does not attempt to be exception safe.
607 template <typename T, unsigned N>
608 class SmallVector : public SmallVectorImpl<T> {
609 /// InlineElts - These are 'N-1' elements that are stored inline in the body
610 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
611 typedef typename SmallVectorImpl<T>::U U;
613 // MinUs - The number of U's require to cover N T's.
614 MinUs = (static_cast<unsigned int>(sizeof(T))*N +
615 static_cast<unsigned int>(sizeof(U)) - 1) /
616 static_cast<unsigned int>(sizeof(U)),
618 // NumInlineEltsElts - The number of elements actually in this array. There
619 // is already one in the parent class, and we have to round up to avoid
620 // having a zero-element array.
621 NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
623 // NumTsAvailable - The number of T's we actually have space for, which may
624 // be more than N due to rounding.
625 NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
626 static_cast<unsigned int>(sizeof(T))
628 U InlineElts[NumInlineEltsElts];
630 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
633 explicit SmallVector(unsigned Size, const T &Value = T())
634 : SmallVectorImpl<T>(NumTsAvailable) {
637 this->push_back(Value);
640 template<typename ItTy>
641 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
645 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
647 SmallVectorImpl<T>::operator=(RHS);
650 const SmallVector &operator=(const SmallVector &RHS) {
651 SmallVectorImpl<T>::operator=(RHS);
657 } // End llvm namespace
660 /// Implement std::swap in terms of SmallVector swap.
663 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
667 /// Implement std::swap in terms of SmallVector swap.
668 template<typename T, unsigned N>
670 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {