Add bound checks in SmallVector
[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.h"
18 #include "llvm/Support/type_traits.h"
19 #include <algorithm>
20 #include <cstring>
21 #include <memory>
22 #include <cassert>
23
24 #ifdef _MSC_VER
25 namespace std {
26 #if _MSC_VER <= 1310
27   // Work around flawed VC++ implementation of std::uninitialized_copy.  Define
28   // additional overloads so that elements with pointer types are recognized as
29   // scalars and not objects, causing bizarre type conversion errors.
30   template<class T1, class T2>
31   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
32     _Scalar_ptr_iterator_tag _Cat;
33     return _Cat;
34   }
35
36   template<class T1, class T2>
37   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
38     _Scalar_ptr_iterator_tag _Cat;
39     return _Cat;
40   }
41 #else
42 // FIXME: It is not clear if the problem is fixed in VS 2005.  What is clear
43 // is that the above hack won't work if it wasn't fixed.
44 #endif
45 }
46 #endif
47
48 namespace llvm {
49
50 /// SmallVectorImpl - This class consists of common code factored out of the
51 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
52 /// template parameter.
53 template <typename T>
54 class SmallVectorImpl {
55 protected:
56   T *Begin, *End, *Capacity;
57   
58   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
59   // don't want it to be automatically run, so we need to represent the space as
60   // something else.  An array of char would work great, but might not be
61   // aligned sufficiently.  Instead, we either use GCC extensions, or some
62   // number of union instances for the space, which guarantee maximal alignment.
63 protected:
64 #ifdef __GNUC__
65   typedef char U;
66   U FirstEl __attribute__((aligned));
67 #else
68   union U {
69     double D;
70     long double LD;
71     long long L;
72     void *P;
73   } FirstEl;
74 #endif
75   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
76 public:
77   // Default ctor - Initialize to empty.
78   SmallVectorImpl(unsigned N)
79     : Begin(reinterpret_cast<T*>(&FirstEl)), 
80       End(reinterpret_cast<T*>(&FirstEl)), 
81       Capacity(reinterpret_cast<T*>(&FirstEl)+N) {
82   }
83   
84   ~SmallVectorImpl() {
85     // Destroy the constructed elements in the vector.
86     destroy_range(Begin, End);
87
88     // If this wasn't grown from the inline copy, deallocate the old space.
89     if (!isSmall())
90       operator delete(Begin);
91   }
92   
93   typedef size_t size_type;
94   typedef T value_type;
95   typedef T* iterator;
96   typedef const T* const_iterator;
97   
98   typedef std::reverse_iterator<const_iterator>  const_reverse_iterator;
99   typedef std::reverse_iterator<iterator>  reverse_iterator;
100   
101   typedef T& reference;
102   typedef const T& const_reference;
103
104   bool empty() const { return Begin == End; }
105   size_type size() const { return End-Begin; }
106
107   // forward iterator creation methods.
108   iterator begin() { return Begin; }
109   const_iterator begin() const { return Begin; }
110   iterator end() { return End; }
111   const_iterator end() const { return End; }
112   
113   // reverse iterator creation methods.
114   reverse_iterator rbegin()            { return reverse_iterator(end()); }
115   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
116   reverse_iterator rend()              { return reverse_iterator(begin()); }
117   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
118   
119   
120   /* These asserts could be "Begin + idx < End", but there are lots of places
121      in llvm where we use &v[v.size()] instead of v.end(). */
122   reference operator[](unsigned idx) {
123     assert (Begin + idx <= End);
124     return Begin[idx];
125   }
126   const_reference operator[](unsigned idx) const {
127     assert (Begin + idx <= End);
128     return Begin[idx];
129   }
130   
131   reference front() {
132     return begin()[0];
133   }
134   const_reference front() const {
135     return begin()[0];
136   }
137   
138   reference back() {
139     return end()[-1];
140   }
141   const_reference back() const {
142     return end()[-1];
143   }
144   
145   void push_back(const_reference Elt) {
146     if (End < Capacity) {
147   Retry:
148       new (End) T(Elt);
149       ++End;
150       return;
151     }
152     grow();
153     goto Retry;
154   }
155   
156   void pop_back() {
157     --End;
158     End->~T();
159   }
160   
161   void clear() {
162     destroy_range(Begin, End);
163     End = Begin;
164   }
165   
166   void resize(unsigned N) {
167     if (N < size()) {
168       destroy_range(Begin+N, End);
169       End = Begin+N;
170     } else if (N > size()) {
171       if (unsigned(Capacity-Begin) < N)
172         grow(N);
173       construct_range(End, Begin+N, T());
174       End = Begin+N;
175     }
176   }
177   
178   void resize(unsigned N, const T &NV) {
179     if (N < size()) {
180       destroy_range(Begin+N, End);
181       End = Begin+N;
182     } else if (N > size()) {
183       if (unsigned(Capacity-Begin) < N)
184         grow(N);
185       construct_range(End, Begin+N, NV);
186       End = Begin+N;
187     }
188   }
189   
190   void reserve(unsigned N) {
191     if (unsigned(Capacity-Begin) < N)
192       grow(N);
193   }
194   
195   void swap(SmallVectorImpl &RHS);
196   
197   /// append - Add the specified range to the end of the SmallVector.
198   ///
199   template<typename in_iter>
200   void append(in_iter in_start, in_iter in_end) {
201     size_type NumInputs = std::distance(in_start, in_end);
202     // Grow allocated space if needed.
203     if (End+NumInputs > Capacity)
204       grow(size()+NumInputs);
205
206     // Copy the new elements over.
207     std::uninitialized_copy(in_start, in_end, End);
208     End += NumInputs;
209   }
210   
211   void assign(unsigned NumElts, const T &Elt) {
212     clear();
213     if (unsigned(Capacity-Begin) < NumElts)
214       grow(NumElts);
215     End = Begin+NumElts;
216     construct_range(Begin, End, Elt);
217   }
218   
219   iterator erase(iterator I) {
220     iterator N = I;
221     // Shift all elts down one.
222     std::copy(I+1, End, I);
223     // Drop the last elt.
224     pop_back();
225     return(N);
226   }
227   
228   iterator erase(iterator S, iterator E) {
229     iterator N = S;
230     // Shift all elts down.
231     iterator I = std::copy(E, End, S);
232     // Drop the last elts.
233     destroy_range(I, End);
234     End = I;
235     return(N);
236   }
237   
238   iterator insert(iterator I, const T &Elt) {
239     if (I == End) {  // Important special case for empty vector.
240       push_back(Elt);
241       return end()-1;
242     }
243     
244     if (End < Capacity) {
245   Retry:
246       new (End) T(back());
247       ++End;
248       // Push everything else over.
249       std::copy_backward(I, End-1, End);
250       *I = Elt;
251       return I;
252     }
253     size_t EltNo = I-Begin;
254     grow();
255     I = Begin+EltNo;
256     goto Retry;
257   }
258   
259   template<typename ItTy>
260   iterator insert(iterator I, ItTy From, ItTy To) {
261     if (I == End) {  // Important special case for empty vector.
262       append(From, To);
263       return end()-1;
264     }
265     
266     size_t NumToInsert = std::distance(From, To);
267     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
268     size_t InsertElt = I-begin();
269     
270     // Ensure there is enough space.
271     reserve(static_cast<unsigned>(size() + NumToInsert));
272     
273     // Uninvalidate the iterator.
274     I = begin()+InsertElt;
275     
276     // If we already have this many elements in the collection, append the
277     // dest elements at the end, then copy over the appropriate elements.  Since
278     // we already reserved space, we know that this won't reallocate the vector.
279     if (size() >= NumToInsert) {
280       T *OldEnd = End;
281       append(End-NumToInsert, End);
282       
283       // Copy the existing elements that get replaced.
284       std::copy(I, OldEnd-NumToInsert, I+NumToInsert);
285       
286       std::copy(From, To, I);
287       return I;
288     }
289
290     // Otherwise, we're inserting more elements than exist already, and we're
291     // not inserting at the end.
292     
293     // Copy over the elements that we're about to overwrite.
294     T *OldEnd = End;
295     End += NumToInsert;
296     size_t NumOverwritten = OldEnd-I;
297     std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
298     
299     // Replace the overwritten part.
300     std::copy(From, From+NumOverwritten, I);
301     
302     // Insert the non-overwritten middle part.
303     std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
304     return I;
305   }
306   
307   const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
308   
309   bool operator==(const SmallVectorImpl &RHS) const {
310     if (size() != RHS.size()) return false;
311     for (T *This = Begin, *That = RHS.Begin, *E = Begin+size(); 
312          This != E; ++This, ++That)
313       if (*This != *That)
314         return false;
315     return true;
316   }
317   bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
318
319   bool operator<(const SmallVectorImpl &RHS) const {
320     return std::lexicographical_compare(begin(), end(),
321                                         RHS.begin(), RHS.end());
322   }
323   
324 private:
325   /// isSmall - Return true if this is a smallvector which has not had dynamic
326   /// memory allocated for it.
327   bool isSmall() const {
328     return static_cast<const void*>(Begin) == 
329            static_cast<const void*>(&FirstEl);
330   }
331
332   /// grow - double the size of the allocated memory, guaranteeing space for at
333   /// least one more element or MinSize if specified.
334   void grow(size_type MinSize = 0);
335
336   void construct_range(T *S, T *E, const T &Elt) {
337     for (; S != E; ++S)
338       new (S) T(Elt);
339   }
340   
341   void destroy_range(T *S, T *E) {
342     while (S != E) {
343       --E;
344       E->~T();
345     }
346   }
347 };
348
349 // Define this out-of-line to dissuade the C++ compiler from inlining it.
350 template <typename T>
351 void SmallVectorImpl<T>::grow(size_t MinSize) {
352   size_t CurCapacity = Capacity-Begin;
353   size_t CurSize = size();
354   size_t NewCapacity = 2*CurCapacity;
355   if (NewCapacity < MinSize)
356     NewCapacity = MinSize;
357   T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
358   
359   // Copy the elements over.
360   if (is_class<T>::value)
361     std::uninitialized_copy(Begin, End, NewElts);
362   else
363     // Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
364     memcpy(NewElts, Begin, CurSize * sizeof(T));
365   
366   // Destroy the original elements.
367   destroy_range(Begin, End);
368   
369   // If this wasn't grown from the inline copy, deallocate the old space.
370   if (!isSmall())
371     operator delete(Begin);
372   
373   Begin = NewElts;
374   End = NewElts+CurSize;
375   Capacity = Begin+NewCapacity;
376 }
377
378 template <typename T>
379 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
380   if (this == &RHS) return;
381   
382   // We can only avoid copying elements if neither vector is small.
383   if (!isSmall() && !RHS.isSmall()) {
384     std::swap(Begin, RHS.Begin);
385     std::swap(End, RHS.End);
386     std::swap(Capacity, RHS.Capacity);
387     return;
388   }
389   if (Begin+RHS.size() > Capacity)
390     grow(RHS.size());
391   if (RHS.begin()+size() > RHS.Capacity)
392     RHS.grow(size());
393   
394   // Swap the shared elements.
395   size_t NumShared = size();
396   if (NumShared > RHS.size()) NumShared = RHS.size();
397   for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
398     std::swap(Begin[i], RHS[i]);
399   
400   // Copy over the extra elts.
401   if (size() > RHS.size()) {
402     size_t EltDiff = size() - RHS.size();
403     std::uninitialized_copy(Begin+NumShared, End, RHS.End);
404     RHS.End += EltDiff;
405     destroy_range(Begin+NumShared, End);
406     End = Begin+NumShared;
407   } else if (RHS.size() > size()) {
408     size_t EltDiff = RHS.size() - size();
409     std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
410     End += EltDiff;
411     destroy_range(RHS.Begin+NumShared, RHS.End);
412     RHS.End = RHS.Begin+NumShared;
413   }
414 }
415   
416 template <typename T>
417 const SmallVectorImpl<T> &
418 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
419   // Avoid self-assignment.
420   if (this == &RHS) return *this;
421   
422   // If we already have sufficient space, assign the common elements, then
423   // destroy any excess.
424   unsigned RHSSize = unsigned(RHS.size());
425   unsigned CurSize = unsigned(size());
426   if (CurSize >= RHSSize) {
427     // Assign common elements.
428     iterator NewEnd;
429     if (RHSSize)
430       NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
431     else
432       NewEnd = Begin;
433     
434     // Destroy excess elements.
435     destroy_range(NewEnd, End);
436     
437     // Trim.
438     End = NewEnd;
439     return *this;
440   }
441   
442   // If we have to grow to have enough elements, destroy the current elements.
443   // This allows us to avoid copying them during the grow.
444   if (unsigned(Capacity-Begin) < RHSSize) {
445     // Destroy current elements.
446     destroy_range(Begin, End);
447     End = Begin;
448     CurSize = 0;
449     grow(RHSSize);
450   } else if (CurSize) {
451     // Otherwise, use assignment for the already-constructed elements.
452     std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
453   }
454   
455   // Copy construct the new elements in place.
456   std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
457   
458   // Set end.
459   End = Begin+RHSSize;
460   return *this;
461 }
462   
463 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
464 /// for the case when the array is small.  It contains some number of elements
465 /// in-place, which allows it to avoid heap allocation when the actual number of
466 /// elements is below that threshold.  This allows normal "small" cases to be
467 /// fast without losing generality for large inputs.
468 ///
469 /// Note that this does not attempt to be exception safe.
470 ///
471 template <typename T, unsigned N>
472 class SmallVector : public SmallVectorImpl<T> {
473   /// InlineElts - These are 'N-1' elements that are stored inline in the body
474   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
475   typedef typename SmallVectorImpl<T>::U U;
476   enum {
477     // MinUs - The number of U's require to cover N T's.
478     MinUs = (static_cast<unsigned int>(sizeof(T))*N +
479              static_cast<unsigned int>(sizeof(U)) - 1) / 
480             static_cast<unsigned int>(sizeof(U)),
481     
482     // NumInlineEltsElts - The number of elements actually in this array.  There
483     // is already one in the parent class, and we have to round up to avoid
484     // having a zero-element array.
485     NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
486     
487     // NumTsAvailable - The number of T's we actually have space for, which may
488     // be more than N due to rounding.
489     NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
490                      static_cast<unsigned int>(sizeof(T))
491   };
492   U InlineElts[NumInlineEltsElts];
493 public:  
494   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
495   }
496   
497   explicit SmallVector(unsigned Size, const T &Value = T())
498     : SmallVectorImpl<T>(NumTsAvailable) {
499     this->reserve(Size);
500     while (Size--)
501       push_back(Value);
502   }
503   
504   template<typename ItTy>
505   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
506     append(S, E);
507   }
508   
509   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
510     if (!RHS.empty())
511       operator=(RHS);
512   }
513
514   const SmallVector &operator=(const SmallVector &RHS) {
515     SmallVectorImpl<T>::operator=(RHS);
516     return *this;
517   }
518   
519 };
520
521 } // End llvm namespace
522
523 namespace std {
524   /// Implement std::swap in terms of SmallVector swap.
525   template<typename T>
526   inline void
527   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
528     LHS.swap(RHS);
529   }
530   
531   /// Implement std::swap in terms of SmallVector swap.
532   template<typename T, unsigned N>
533   inline void
534   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
535     LHS.swap(RHS);
536   }
537 }
538
539 #endif