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 /// SmallVectorImpl - This class consists of common code factored out of the
50 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
51 /// template parameter.
53 class SmallVectorImpl {
55 T *Begin, *End, *Capacity;
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 either use GCC extensions, or some
61 // number of union instances for the space, which guarantee maximal alignment.
65 U FirstEl __attribute__((aligned));
74 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
76 // Default ctor - Initialize to empty.
77 explicit SmallVectorImpl(unsigned N)
78 : Begin(reinterpret_cast<T*>(&FirstEl)),
79 End(reinterpret_cast<T*>(&FirstEl)),
80 Capacity(reinterpret_cast<T*>(&FirstEl)+N) {
84 // Destroy the constructed elements in the vector.
85 destroy_range(Begin, End);
87 // If this wasn't grown from the inline copy, deallocate the old space.
89 operator delete(Begin);
92 typedef size_t size_type;
93 typedef ptrdiff_t difference_type;
96 typedef const T* const_iterator;
98 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
99 typedef std::reverse_iterator<iterator> reverse_iterator;
101 typedef T& reference;
102 typedef const T& const_reference;
104 typedef const T* const_pointer;
106 bool empty() const { return Begin == End; }
107 size_type size() const { return End-Begin; }
108 size_type max_size() const { return size_type(-1) / sizeof(T); }
110 // forward iterator creation methods.
111 iterator begin() { return Begin; }
112 const_iterator begin() const { return Begin; }
113 iterator end() { return End; }
114 const_iterator end() const { return End; }
116 // reverse iterator creation methods.
117 reverse_iterator rbegin() { return reverse_iterator(end()); }
118 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
119 reverse_iterator rend() { return reverse_iterator(begin()); }
120 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
123 reference operator[](unsigned idx) {
124 assert(Begin + idx < End);
127 const_reference operator[](unsigned idx) const {
128 assert(Begin + idx < End);
135 const_reference front() const {
142 const_reference back() const {
146 void push_back(const_reference Elt) {
147 if (End < Capacity) {
169 destroy_range(Begin, End);
173 void resize(unsigned N) {
175 destroy_range(Begin+N, End);
177 } else if (N > size()) {
178 if (unsigned(Capacity-Begin) < N)
180 construct_range(End, Begin+N, T());
185 void resize(unsigned N, const T &NV) {
187 destroy_range(Begin+N, End);
189 } else if (N > size()) {
190 if (unsigned(Capacity-Begin) < N)
192 construct_range(End, Begin+N, NV);
197 void reserve(unsigned N) {
198 if (unsigned(Capacity-Begin) < N)
202 void swap(SmallVectorImpl &RHS);
204 /// append - Add the specified range to the end of the SmallVector.
206 template<typename in_iter>
207 void append(in_iter in_start, in_iter in_end) {
208 size_type NumInputs = std::distance(in_start, in_end);
209 // Grow allocated space if needed.
210 if (NumInputs > size_type(Capacity-End))
211 grow(size()+NumInputs);
213 // Copy the new elements over.
214 std::uninitialized_copy(in_start, in_end, End);
218 /// append - Add the specified range to the end of the SmallVector.
220 void append(size_type NumInputs, const T &Elt) {
221 // Grow allocated space if needed.
222 if (NumInputs > size_type(Capacity-End))
223 grow(size()+NumInputs);
225 // Copy the new elements over.
226 std::uninitialized_fill_n(End, NumInputs, Elt);
230 void assign(unsigned NumElts, const T &Elt) {
232 if (unsigned(Capacity-Begin) < NumElts)
235 construct_range(Begin, End, Elt);
238 iterator erase(iterator I) {
240 // Shift all elts down one.
241 std::copy(I+1, End, I);
242 // Drop the last elt.
247 iterator erase(iterator S, iterator E) {
249 // Shift all elts down.
250 iterator I = std::copy(E, End, S);
251 // Drop the last elts.
252 destroy_range(I, End);
257 iterator insert(iterator I, const T &Elt) {
258 if (I == End) { // Important special case for empty vector.
263 if (End < Capacity) {
267 // Push everything else over.
268 std::copy_backward(I, End-1, End);
272 size_t EltNo = I-Begin;
278 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
279 if (I == End) { // Important special case for empty vector.
280 append(NumToInsert, Elt);
284 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
285 size_t InsertElt = I-begin();
287 // Ensure there is enough space.
288 reserve(static_cast<unsigned>(size() + NumToInsert));
290 // Uninvalidate the iterator.
291 I = begin()+InsertElt;
293 // If there are more elements between the insertion point and the end of the
294 // range than there are being inserted, we can use a simple approach to
295 // insertion. Since we already reserved space, we know that this won't
296 // reallocate the vector.
297 if (size_t(end()-I) >= NumToInsert) {
299 append(End-NumToInsert, End);
301 // Copy the existing elements that get replaced.
302 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
304 std::fill_n(I, NumToInsert, Elt);
308 // Otherwise, we're inserting more elements than exist already, and we're
309 // not inserting at the end.
311 // Copy over the elements that we're about to overwrite.
314 size_t NumOverwritten = OldEnd-I;
315 std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
317 // Replace the overwritten part.
318 std::fill_n(I, NumOverwritten, Elt);
320 // Insert the non-overwritten middle part.
321 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
325 template<typename ItTy>
326 iterator insert(iterator I, ItTy From, ItTy To) {
327 if (I == End) { // Important special case for empty vector.
332 size_t NumToInsert = std::distance(From, To);
333 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
334 size_t InsertElt = I-begin();
336 // Ensure there is enough space.
337 reserve(static_cast<unsigned>(size() + NumToInsert));
339 // Uninvalidate the iterator.
340 I = begin()+InsertElt;
342 // If there are more elements between the insertion point and the end of the
343 // range than there are being inserted, we can use a simple approach to
344 // insertion. Since we already reserved space, we know that this won't
345 // reallocate the vector.
346 if (size_t(end()-I) >= NumToInsert) {
348 append(End-NumToInsert, End);
350 // Copy the existing elements that get replaced.
351 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
353 std::copy(From, To, I);
357 // Otherwise, we're inserting more elements than exist already, and we're
358 // not inserting at the end.
360 // Copy over the elements that we're about to overwrite.
363 size_t NumOverwritten = OldEnd-I;
364 std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
366 // Replace the overwritten part.
367 std::copy(From, From+NumOverwritten, I);
369 // Insert the non-overwritten middle part.
370 std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
374 /// data - Return a pointer to the vector's buffer, even if empty().
376 return pointer(Begin);
379 /// data - Return a pointer to the vector's buffer, even if empty().
380 const_pointer data() const {
381 return const_pointer(Begin);
384 const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
386 bool operator==(const SmallVectorImpl &RHS) const {
387 if (size() != RHS.size()) return false;
388 for (T *This = Begin, *That = RHS.Begin, *E = Begin+size();
389 This != E; ++This, ++That)
394 bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
396 bool operator<(const SmallVectorImpl &RHS) const {
397 return std::lexicographical_compare(begin(), end(),
398 RHS.begin(), RHS.end());
401 /// capacity - Return the total number of elements in the currently allocated
403 size_t capacity() const { return Capacity - Begin; }
405 /// set_size - Set the array size to \arg N, which the current array must have
406 /// enough capacity for.
408 /// This does not construct or destroy any elements in the vector.
410 /// Clients can use this in conjunction with capacity() to write past the end
411 /// of the buffer when they know that more elements are available, and only
412 /// update the size later. This avoids the cost of value initializing elements
413 /// which will only be overwritten.
414 void set_size(unsigned N) {
415 assert(N <= capacity());
420 /// isSmall - Return true if this is a smallvector which has not had dynamic
421 /// memory allocated for it.
422 bool isSmall() const {
423 return static_cast<const void*>(Begin) ==
424 static_cast<const void*>(&FirstEl);
427 /// grow - double the size of the allocated memory, guaranteeing space for at
428 /// least one more element or MinSize if specified.
429 void grow(size_type MinSize = 0);
431 void construct_range(T *S, T *E, const T &Elt) {
436 void destroy_range(T *S, T *E) {
444 // Define this out-of-line to dissuade the C++ compiler from inlining it.
445 template <typename T>
446 void SmallVectorImpl<T>::grow(size_t MinSize) {
447 size_t CurCapacity = Capacity-Begin;
448 size_t CurSize = size();
449 size_t NewCapacity = 2*CurCapacity;
450 if (NewCapacity < MinSize)
451 NewCapacity = MinSize;
452 T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
454 // Copy the elements over.
455 if (is_class<T>::value)
456 std::uninitialized_copy(Begin, End, NewElts);
458 // Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
459 memcpy(NewElts, Begin, CurSize * sizeof(T));
461 // Destroy the original elements.
462 destroy_range(Begin, End);
464 // If this wasn't grown from the inline copy, deallocate the old space.
466 operator delete(Begin);
469 End = NewElts+CurSize;
470 Capacity = Begin+NewCapacity;
473 template <typename T>
474 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
475 if (this == &RHS) return;
477 // We can only avoid copying elements if neither vector is small.
478 if (!isSmall() && !RHS.isSmall()) {
479 std::swap(Begin, RHS.Begin);
480 std::swap(End, RHS.End);
481 std::swap(Capacity, RHS.Capacity);
484 if (RHS.size() > size_type(Capacity-Begin))
486 if (size() > size_type(RHS.Capacity-RHS.begin()))
489 // Swap the shared elements.
490 size_t NumShared = size();
491 if (NumShared > RHS.size()) NumShared = RHS.size();
492 for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
493 std::swap(Begin[i], RHS[i]);
495 // Copy over the extra elts.
496 if (size() > RHS.size()) {
497 size_t EltDiff = size() - RHS.size();
498 std::uninitialized_copy(Begin+NumShared, End, RHS.End);
500 destroy_range(Begin+NumShared, End);
501 End = Begin+NumShared;
502 } else if (RHS.size() > size()) {
503 size_t EltDiff = RHS.size() - size();
504 std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
506 destroy_range(RHS.Begin+NumShared, RHS.End);
507 RHS.End = RHS.Begin+NumShared;
511 template <typename T>
512 const SmallVectorImpl<T> &
513 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
514 // Avoid self-assignment.
515 if (this == &RHS) return *this;
517 // If we already have sufficient space, assign the common elements, then
518 // destroy any excess.
519 unsigned RHSSize = unsigned(RHS.size());
520 unsigned CurSize = unsigned(size());
521 if (CurSize >= RHSSize) {
522 // Assign common elements.
525 NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
529 // Destroy excess elements.
530 destroy_range(NewEnd, End);
537 // If we have to grow to have enough elements, destroy the current elements.
538 // This allows us to avoid copying them during the grow.
539 if (unsigned(Capacity-Begin) < RHSSize) {
540 // Destroy current elements.
541 destroy_range(Begin, End);
545 } else if (CurSize) {
546 // Otherwise, use assignment for the already-constructed elements.
547 std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
550 // Copy construct the new elements in place.
551 std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
558 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
559 /// for the case when the array is small. It contains some number of elements
560 /// in-place, which allows it to avoid heap allocation when the actual number of
561 /// elements is below that threshold. This allows normal "small" cases to be
562 /// fast without losing generality for large inputs.
564 /// Note that this does not attempt to be exception safe.
566 template <typename T, unsigned N>
567 class SmallVector : public SmallVectorImpl<T> {
568 /// InlineElts - These are 'N-1' elements that are stored inline in the body
569 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
570 typedef typename SmallVectorImpl<T>::U U;
572 // MinUs - The number of U's require to cover N T's.
573 MinUs = (static_cast<unsigned int>(sizeof(T))*N +
574 static_cast<unsigned int>(sizeof(U)) - 1) /
575 static_cast<unsigned int>(sizeof(U)),
577 // NumInlineEltsElts - The number of elements actually in this array. There
578 // is already one in the parent class, and we have to round up to avoid
579 // having a zero-element array.
580 NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
582 // NumTsAvailable - The number of T's we actually have space for, which may
583 // be more than N due to rounding.
584 NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
585 static_cast<unsigned int>(sizeof(T))
587 U InlineElts[NumInlineEltsElts];
589 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
592 explicit SmallVector(unsigned Size, const T &Value = T())
593 : SmallVectorImpl<T>(NumTsAvailable) {
596 this->push_back(Value);
599 template<typename ItTy>
600 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
604 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
606 SmallVectorImpl<T>::operator=(RHS);
609 const SmallVector &operator=(const SmallVector &RHS) {
610 SmallVectorImpl<T>::operator=(RHS);
616 } // End llvm namespace
619 /// Implement std::swap in terms of SmallVector swap.
622 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
626 /// Implement std::swap in terms of SmallVector swap.
627 template<typename T, unsigned N>
629 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {