Add an ArrayRef upcasting constructor from ArrayRef<U*> -> ArrayRef<T*> where T is...
[oota-llvm.git] / include / llvm / ADT / ArrayRef.h
1 //===--- ArrayRef.h - Array Reference Wrapper -------------------*- 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 #ifndef LLVM_ADT_ARRAYREF_H
11 #define LLVM_ADT_ARRAYREF_H
12
13 #include "llvm/ADT/None.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include <vector>
17
18 namespace llvm {
19
20   /// ArrayRef - Represent a constant reference to an array (0 or more elements
21   /// consecutively in memory), i.e. a start pointer and a length.  It allows
22   /// various APIs to take consecutive elements easily and conveniently.
23   ///
24   /// This class does not own the underlying data, it is expected to be used in
25   /// situations where the data resides in some other buffer, whose lifetime
26   /// extends past that of the ArrayRef. For this reason, it is not in general
27   /// safe to store an ArrayRef.
28   ///
29   /// This is intended to be trivially copyable, so it should be passed by
30   /// value.
31   template<typename T>
32   class ArrayRef {
33   public:
34     typedef const T *iterator;
35     typedef const T *const_iterator;
36     typedef size_t size_type;
37
38     typedef std::reverse_iterator<iterator> reverse_iterator;
39
40   private:
41     /// The start of the array, in an external buffer.
42     const T *Data;
43
44     /// The number of elements.
45     size_type Length;
46
47     /// \brief A dummy "optional" type that is only created by implicit
48     /// conversion from a reference to T.
49     ///
50     /// This type must *only* be used in a function argument or as a copy of
51     /// a function argument, as otherwise it will hold a pointer to a temporary
52     /// past that temporaries' lifetime.
53     struct TRefOrNothing {
54       const T *TPtr;
55
56       TRefOrNothing() : TPtr(nullptr) {}
57       TRefOrNothing(const T &TRef) : TPtr(&TRef) {}
58     };
59
60   public:
61     /// @name Constructors
62     /// @{
63
64     /// Construct an empty ArrayRef.
65     /*implicit*/ ArrayRef() : Data(nullptr), Length(0) {}
66
67     /// Construct an empty ArrayRef from None.
68     /*implicit*/ ArrayRef(NoneType) : Data(nullptr), Length(0) {}
69
70     /// Construct an ArrayRef from a single element.
71     /*implicit*/ ArrayRef(const T &OneElt)
72       : Data(&OneElt), Length(1) {}
73
74     /// Construct an ArrayRef from a pointer and length.
75     /*implicit*/ ArrayRef(const T *data, size_t length)
76       : Data(data), Length(length) {}
77
78     /// Construct an ArrayRef from a range.
79     ArrayRef(const T *begin, const T *end)
80       : Data(begin), Length(end - begin) {}
81
82     /// Construct an ArrayRef from a SmallVector. This is templated in order to
83     /// avoid instantiating SmallVectorTemplateCommon<T> whenever we
84     /// copy-construct an ArrayRef.
85     template<typename U>
86     /*implicit*/ ArrayRef(const SmallVectorTemplateCommon<T, U> &Vec)
87       : Data(Vec.data()), Length(Vec.size()) {
88     }
89
90     /// Construct an ArrayRef from a std::vector.
91     template<typename A>
92     /*implicit*/ ArrayRef(const std::vector<T, A> &Vec)
93       : Data(Vec.data()), Length(Vec.size()) {}
94
95     /// Construct an ArrayRef from a C array.
96     template <size_t N>
97     /*implicit*/ LLVM_CONSTEXPR ArrayRef(const T (&Arr)[N])
98       : Data(Arr), Length(N) {}
99
100 #if LLVM_HAS_INITIALIZER_LISTS
101     /// Construct an ArrayRef from a std::initializer_list.
102     /*implicit*/ ArrayRef(const std::initializer_list<T> &Vec)
103     : Data(Vec.begin() == Vec.end() ? (T*)0 : Vec.begin()),
104       Length(Vec.size()) {}
105 #endif
106
107     /// Construct an ArrayRef<const T*> from ArrayRef<T*>. This uses SFINAE to
108     /// ensure that only ArrayRefs of pointers can be converted.
109     template <typename U>
110     ArrayRef(const ArrayRef<U *> &A,
111              typename std::enable_if<
112                  std::is_convertible<U *const *, T const *>::value>::type* = 0)
113       : Data(A.data()), Length(A.size()) {}
114
115     /// Construct an ArrayRef<T*> from an ArrayRef<U*> where T is a super class
116     /// of U. This uses SFINAE to ensure that only ArrayRefs with this property
117     /// can be converted. This is an upcasting constructor.
118     template <typename U>
119     ArrayRef(const ArrayRef<U> &A,
120              typename std::enable_if<std::is_base_of<
121                  typename std::remove_pointer<T>::type,
122                  typename std::remove_pointer<U>::type>::value>::type * = 0)
123         : Data(reinterpret_cast<T const *>(A.data())), Length(A.size()) {}
124
125     /// @}
126     /// @name Simple Operations
127     /// @{
128
129     iterator begin() const { return Data; }
130     iterator end() const { return Data + Length; }
131
132     reverse_iterator rbegin() const { return reverse_iterator(end()); }
133     reverse_iterator rend() const { return reverse_iterator(begin()); }
134
135     /// empty - Check if the array is empty.
136     bool empty() const { return Length == 0; }
137
138     const T *data() const { return Data; }
139
140     /// size - Get the array size.
141     size_t size() const { return Length; }
142
143     /// front - Get the first element.
144     const T &front() const {
145       assert(!empty());
146       return Data[0];
147     }
148
149     /// back - Get the last element.
150     const T &back() const {
151       assert(!empty());
152       return Data[Length-1];
153     }
154
155     // copy - Allocate copy in Allocator and return ArrayRef<T> to it.
156     template <typename Allocator> ArrayRef<T> copy(Allocator &A) {
157       T *Buff = A.template Allocate<T>(Length);
158       std::copy(begin(), end(), Buff);
159       return ArrayRef<T>(Buff, Length);
160     }
161
162     /// equals - Check for element-wise equality.
163     bool equals(ArrayRef RHS) const {
164       if (Length != RHS.Length)
165         return false;
166       // Don't use std::equal(), since it asserts in MSVC on nullptr iterators.
167       for (auto L = begin(), LE = end(), R = RHS.begin(); L != LE; ++L, ++R)
168         // Match std::equal() in using == (instead of !=) to minimize API
169         // requirements of ArrayRef'ed types.
170         if (!(*L == *R))
171           return false;
172       return true;
173     }
174
175     /// slice(n) - Chop off the first N elements of the array.
176     ArrayRef<T> slice(unsigned N) const {
177       assert(N <= size() && "Invalid specifier");
178       return ArrayRef<T>(data()+N, size()-N);
179     }
180
181     /// slice(n, m) - Chop off the first N elements of the array, and keep M
182     /// elements in the array.
183     ArrayRef<T> slice(unsigned N, unsigned M) const {
184       assert(N+M <= size() && "Invalid specifier");
185       return ArrayRef<T>(data()+N, M);
186     }
187
188     // \brief Drop the last \p N elements of the array.
189     ArrayRef<T> drop_back(unsigned N = 1) const {
190       assert(size() >= N && "Dropping more elements than exist");
191       return slice(0, size() - N);
192     }
193
194     /// @}
195     /// @name Operator Overloads
196     /// @{
197     const T &operator[](size_t Index) const {
198       assert(Index < Length && "Invalid index!");
199       return Data[Index];
200     }
201
202     /// @}
203     /// @name Expensive Operations
204     /// @{
205     std::vector<T> vec() const {
206       return std::vector<T>(Data, Data+Length);
207     }
208
209     /// @}
210     /// @name Conversion operators
211     /// @{
212     operator std::vector<T>() const {
213       return std::vector<T>(Data, Data+Length);
214     }
215
216     /// @}
217     /// @{
218     /// @name Convenience methods
219
220     /// @brief Predicate for testing that the array equals the exact sequence of
221     /// arguments.
222     ///
223     /// Will return false if the size is not equal to the exact number of
224     /// arguments given or if the array elements don't equal the argument
225     /// elements in order. Currently supports up to 16 arguments, but can
226     /// easily be extended.
227     bool equals(TRefOrNothing Arg0 = TRefOrNothing(),
228                 TRefOrNothing Arg1 = TRefOrNothing(),
229                 TRefOrNothing Arg2 = TRefOrNothing(),
230                 TRefOrNothing Arg3 = TRefOrNothing(),
231                 TRefOrNothing Arg4 = TRefOrNothing(),
232                 TRefOrNothing Arg5 = TRefOrNothing(),
233                 TRefOrNothing Arg6 = TRefOrNothing(),
234                 TRefOrNothing Arg7 = TRefOrNothing(),
235                 TRefOrNothing Arg8 = TRefOrNothing(),
236                 TRefOrNothing Arg9 = TRefOrNothing(),
237                 TRefOrNothing Arg10 = TRefOrNothing(),
238                 TRefOrNothing Arg11 = TRefOrNothing(),
239                 TRefOrNothing Arg12 = TRefOrNothing(),
240                 TRefOrNothing Arg13 = TRefOrNothing(),
241                 TRefOrNothing Arg14 = TRefOrNothing(),
242                 TRefOrNothing Arg15 = TRefOrNothing()) {
243       TRefOrNothing Args[] = {Arg0,  Arg1,  Arg2,  Arg3, Arg4,  Arg5,
244                               Arg6,  Arg7,  Arg8,  Arg9, Arg10, Arg11,
245                               Arg12, Arg13, Arg14, Arg15};
246       if (size() > array_lengthof(Args))
247         return false;
248
249       for (unsigned i = 0, e = size(); i != e; ++i)
250         if (Args[i].TPtr == nullptr || (*this)[i] != *Args[i].TPtr)
251           return false;
252
253       // Either the size is exactly as many args, or the next arg must be null.
254       return size() == array_lengthof(Args) || Args[size()].TPtr == nullptr;
255     }
256
257     /// @}
258   };
259
260   /// MutableArrayRef - Represent a mutable reference to an array (0 or more
261   /// elements consecutively in memory), i.e. a start pointer and a length.  It
262   /// allows various APIs to take and modify consecutive elements easily and
263   /// conveniently.
264   ///
265   /// This class does not own the underlying data, it is expected to be used in
266   /// situations where the data resides in some other buffer, whose lifetime
267   /// extends past that of the MutableArrayRef. For this reason, it is not in
268   /// general safe to store a MutableArrayRef.
269   ///
270   /// This is intended to be trivially copyable, so it should be passed by
271   /// value.
272   template<typename T>
273   class MutableArrayRef : public ArrayRef<T> {
274   public:
275     typedef T *iterator;
276
277     typedef std::reverse_iterator<iterator> reverse_iterator;
278
279     /// Construct an empty MutableArrayRef.
280     /*implicit*/ MutableArrayRef() : ArrayRef<T>() {}
281
282     /// Construct an empty MutableArrayRef from None.
283     /*implicit*/ MutableArrayRef(NoneType) : ArrayRef<T>() {}
284
285     /// Construct an MutableArrayRef from a single element.
286     /*implicit*/ MutableArrayRef(T &OneElt) : ArrayRef<T>(OneElt) {}
287
288     /// Construct an MutableArrayRef from a pointer and length.
289     /*implicit*/ MutableArrayRef(T *data, size_t length)
290       : ArrayRef<T>(data, length) {}
291
292     /// Construct an MutableArrayRef from a range.
293     MutableArrayRef(T *begin, T *end) : ArrayRef<T>(begin, end) {}
294
295     /// Construct an MutableArrayRef from a SmallVector.
296     /*implicit*/ MutableArrayRef(SmallVectorImpl<T> &Vec)
297     : ArrayRef<T>(Vec) {}
298
299     /// Construct a MutableArrayRef from a std::vector.
300     /*implicit*/ MutableArrayRef(std::vector<T> &Vec)
301     : ArrayRef<T>(Vec) {}
302
303     /// Construct an MutableArrayRef from a C array.
304     template <size_t N>
305     /*implicit*/ LLVM_CONSTEXPR MutableArrayRef(T (&Arr)[N])
306       : ArrayRef<T>(Arr) {}
307
308     T *data() const { return const_cast<T*>(ArrayRef<T>::data()); }
309
310     iterator begin() const { return data(); }
311     iterator end() const { return data() + this->size(); }
312
313     reverse_iterator rbegin() const { return reverse_iterator(end()); }
314     reverse_iterator rend() const { return reverse_iterator(begin()); }
315
316     /// front - Get the first element.
317     T &front() const {
318       assert(!this->empty());
319       return data()[0];
320     }
321
322     /// back - Get the last element.
323     T &back() const {
324       assert(!this->empty());
325       return data()[this->size()-1];
326     }
327
328     /// slice(n) - Chop off the first N elements of the array.
329     MutableArrayRef<T> slice(unsigned N) const {
330       assert(N <= this->size() && "Invalid specifier");
331       return MutableArrayRef<T>(data()+N, this->size()-N);
332     }
333
334     /// slice(n, m) - Chop off the first N elements of the array, and keep M
335     /// elements in the array.
336     MutableArrayRef<T> slice(unsigned N, unsigned M) const {
337       assert(N+M <= this->size() && "Invalid specifier");
338       return MutableArrayRef<T>(data()+N, M);
339     }
340
341     /// @}
342     /// @name Operator Overloads
343     /// @{
344     T &operator[](size_t Index) const {
345       assert(Index < this->size() && "Invalid index!");
346       return data()[Index];
347     }
348   };
349
350   /// @name ArrayRef Convenience constructors
351   /// @{
352
353   /// Construct an ArrayRef from a single element.
354   template<typename T>
355   ArrayRef<T> makeArrayRef(const T &OneElt) {
356     return OneElt;
357   }
358
359   /// Construct an ArrayRef from a pointer and length.
360   template<typename T>
361   ArrayRef<T> makeArrayRef(const T *data, size_t length) {
362     return ArrayRef<T>(data, length);
363   }
364
365   /// Construct an ArrayRef from a range.
366   template<typename T>
367   ArrayRef<T> makeArrayRef(const T *begin, const T *end) {
368     return ArrayRef<T>(begin, end);
369   }
370
371   /// Construct an ArrayRef from a SmallVector.
372   template <typename T>
373   ArrayRef<T> makeArrayRef(const SmallVectorImpl<T> &Vec) {
374     return Vec;
375   }
376
377   /// Construct an ArrayRef from a SmallVector.
378   template <typename T, unsigned N>
379   ArrayRef<T> makeArrayRef(const SmallVector<T, N> &Vec) {
380     return Vec;
381   }
382
383   /// Construct an ArrayRef from a std::vector.
384   template<typename T>
385   ArrayRef<T> makeArrayRef(const std::vector<T> &Vec) {
386     return Vec;
387   }
388
389   /// Construct an ArrayRef from a C array.
390   template<typename T, size_t N>
391   ArrayRef<T> makeArrayRef(const T (&Arr)[N]) {
392     return ArrayRef<T>(Arr);
393   }
394
395   /// @}
396   /// @name ArrayRef Comparison Operators
397   /// @{
398
399   template<typename T>
400   inline bool operator==(ArrayRef<T> LHS, ArrayRef<T> RHS) {
401     return LHS.equals(RHS);
402   }
403
404   template<typename T>
405   inline bool operator!=(ArrayRef<T> LHS, ArrayRef<T> RHS) {
406     return !(LHS == RHS);
407   }
408
409   /// @}
410
411   // ArrayRefs can be treated like a POD type.
412   template <typename T> struct isPodLike;
413   template <typename T> struct isPodLike<ArrayRef<T> > {
414     static const bool value = true;
415   };
416 }
417
418 #endif