ceec33d1852621cfd773b7c5fc51a5d565e1e68b
[oota-llvm.git] / include / llvm / Support / ErrorOr.h
1 //===- llvm/Support/ErrorOr.h - Error Smart Pointer -----------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 ///
12 /// Provides ErrorOr<T> smart pointer.
13 ///
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_SUPPORT_ERROR_OR_H
17 #define LLVM_SUPPORT_ERROR_OR_H
18
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/Support/AlignOf.h"
21 #include "llvm/Support/system_error.h"
22 #include "llvm/Support/type_traits.h"
23
24 #include <cassert>
25 #if LLVM_HAS_CXX11_TYPETRAITS
26 #include <type_traits>
27 #endif
28
29 namespace llvm {
30 struct ErrorHolderBase {
31   error_code Error;
32   uint16_t RefCount;
33   bool HasUserData;
34
35   ErrorHolderBase() : RefCount(1) {}
36
37   void aquire() {
38     ++RefCount;
39   }
40
41   void release() {
42     if (--RefCount == 0)
43       delete this;
44   }
45
46 protected:
47   virtual ~ErrorHolderBase() {}
48 };
49
50 template<class T>
51 struct ErrorHolder : ErrorHolderBase {
52 #if LLVM_HAS_RVALUE_REFERENCES
53   ErrorHolder(T &&UD) : UserData(llvm_move(UD)) {}
54 #else
55   ErrorHolder(T &UD) : UserData(UD) {}
56 #endif
57   T UserData;
58 };
59
60 template<class Tp> struct ErrorOrUserDataTraits : llvm::false_type {};
61
62 #if LLVM_HAS_CXX11_TYPETRAITS && LLVM_HAS_RVALUE_REFERENCES
63 template<class T, class V>
64 typename std::enable_if< std::is_constructible<T, V>::value
65                        , typename std::remove_reference<V>::type>::type &&
66  moveIfMoveConstructible(V &Val) {
67   return std::move(Val);
68 }
69
70 template<class T, class V>
71 typename std::enable_if< !std::is_constructible<T, V>::value
72                        , typename std::remove_reference<V>::type>::type &
73 moveIfMoveConstructible(V &Val) {
74   return Val;
75 }
76 #else
77 template<class T, class V>
78 V &moveIfMoveConstructible(V &Val) {
79   return Val;
80 }
81 #endif
82
83 /// \brief Stores a reference that can be changed.
84 template <typename T>
85 class ReferenceStorage {
86   T *Storage;
87
88 public:
89   ReferenceStorage(T &Ref) : Storage(&Ref) {}
90
91   operator T &() const { return *Storage; }
92   T &get() const { return *Storage; }
93 };
94
95 /// \brief Represents either an error or a value T.
96 ///
97 /// ErrorOr<T> is a pointer-like class that represents the result of an
98 /// operation. The result is either an error, or a value of type T. This is
99 /// designed to emulate the usage of returning a pointer where nullptr indicates
100 /// failure. However instead of just knowing that the operation failed, we also
101 /// have an error_code and optional user data that describes why it failed.
102 ///
103 /// It is used like the following.
104 /// \code
105 ///   ErrorOr<Buffer> getBuffer();
106 ///   void handleError(error_code ec);
107 ///
108 ///   auto buffer = getBuffer();
109 ///   if (!buffer)
110 ///     handleError(buffer);
111 ///   buffer->write("adena");
112 /// \endcode
113 ///
114 /// ErrorOr<T> also supports user defined data for specific error_codes. To use
115 /// this feature you must first add a template specialization of
116 /// ErrorOrUserDataTraits derived from std::true_type for your type in the lld
117 /// namespace. This specialization must have a static error_code error()
118 /// function that returns the error_code this data is used with.
119 ///
120 /// getError<UserData>() may be called to get either the stored user data, or
121 /// a default constructed UserData if none was stored.
122 ///
123 /// Example:
124 /// \code
125 ///   struct InvalidArgError {
126 ///     InvalidArgError() {}
127 ///     InvalidArgError(std::string S) : ArgName(S) {}
128 ///     std::string ArgName;
129 ///   };
130 ///
131 ///   namespace llvm {
132 ///   template<>
133 ///   struct ErrorOrUserDataTraits<InvalidArgError> : std::true_type {
134 ///     static error_code error() {
135 ///       return make_error_code(errc::invalid_argument);
136 ///     }
137 ///   };
138 ///   } // end namespace llvm
139 ///
140 ///   using namespace llvm;
141 ///
142 ///   ErrorOr<int> foo() {
143 ///     return InvalidArgError("adena");
144 ///   }
145 ///
146 ///   int main() {
147 ///     auto a = foo();
148 ///     if (!a && error_code(a) == errc::invalid_argument)
149 ///       llvm::errs() << a.getError<InvalidArgError>().ArgName << "\n";
150 ///   }
151 /// \endcode
152 ///
153 /// An implicit conversion to bool provides a way to check if there was an
154 /// error. The unary * and -> operators provide pointer like access to the
155 /// value. Accessing the value when there is an error has undefined behavior.
156 ///
157 /// When T is a reference type the behaivor is slightly different. The reference
158 /// is held in a std::reference_wrapper<std::remove_reference<T>::type>, and
159 /// there is special handling to make operator -> work as if T was not a
160 /// reference.
161 ///
162 /// T cannot be a rvalue reference.
163 template<class T>
164 class ErrorOr {
165   template <class OtherT> friend class ErrorOr;
166   static const bool isRef = is_reference<T>::value;
167   typedef ReferenceStorage<typename remove_reference<T>::type> wrap;
168
169 public:
170   typedef typename
171     conditional< isRef
172                , wrap
173                , T
174                >::type storage_type;
175
176 private:
177   typedef typename remove_reference<T>::type &reference;
178   typedef typename remove_reference<T>::type *pointer;
179
180 public:
181   ErrorOr() : IsValid(false) {}
182
183   ErrorOr(llvm::error_code EC) : HasError(true), IsValid(true) {
184     Error = new ErrorHolderBase;
185     Error->Error = EC;
186     Error->HasUserData = false;
187   }
188
189   template<class UserDataT>
190   ErrorOr(UserDataT UD, typename
191           enable_if_c<ErrorOrUserDataTraits<UserDataT>::value>::type* = 0)
192     : HasError(true), IsValid(true) {
193     Error = new ErrorHolder<UserDataT>(llvm_move(UD));
194     Error->Error = ErrorOrUserDataTraits<UserDataT>::error();
195     Error->HasUserData = true;
196   }
197
198   ErrorOr(T Val) : HasError(false), IsValid(true) {
199     new (get()) storage_type(moveIfMoveConstructible<storage_type>(Val));
200   }
201
202   ErrorOr(const ErrorOr &Other) : IsValid(false) {
203     copyConstruct(Other);
204   }
205
206   template <class OtherT>
207   ErrorOr(const ErrorOr<OtherT> &Other) : IsValid(false) {
208     copyConstruct(Other);
209   }
210
211   ErrorOr &operator =(const ErrorOr &Other) {
212     copyAssign(Other);
213     return *this;
214   }
215
216   template <class OtherT>
217   ErrorOr &operator =(const ErrorOr<OtherT> &Other) {
218     copyAssign(Other);
219     return *this;
220   }
221
222 #if LLVM_HAS_RVALUE_REFERENCES
223   ErrorOr(ErrorOr &&Other) : IsValid(false) {
224     moveConstruct(std::move(Other));
225   }
226
227   template <class OtherT>
228   ErrorOr(ErrorOr<OtherT> &&Other) : IsValid(false) {
229     moveConstruct(std::move(Other));
230   }
231
232   ErrorOr &operator =(ErrorOr &&Other) {
233     moveAssign(std::move(Other));
234     return *this;
235   }
236
237   template <class OtherT>
238   ErrorOr &operator =(ErrorOr<OtherT> &&Other) {
239     moveAssign(std::move(Other));
240     return *this;
241   }
242 #endif
243
244   ~ErrorOr() {
245     if (!IsValid)
246       return;
247     if (HasError)
248       Error->release();
249     else
250       get()->~storage_type();
251   }
252
253   template<class ET>
254   ET getError() const {
255     assert(IsValid && "Cannot get the error of a default constructed ErrorOr!");
256     assert(HasError && "Cannot get an error if none exists!");
257     assert(ErrorOrUserDataTraits<ET>::error() == Error->Error &&
258            "Incorrect user error data type for error!");
259     if (!Error->HasUserData)
260       return ET();
261     return reinterpret_cast<const ErrorHolder<ET>*>(Error)->UserData;
262   }
263
264   typedef void (*unspecified_bool_type)();
265   static void unspecified_bool_true() {}
266
267   /// \brief Return false if there is an error.
268   operator unspecified_bool_type() const {
269     assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
270     return HasError ? 0 : unspecified_bool_true;
271   }
272
273   operator llvm::error_code() const {
274     assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
275     return HasError ? Error->Error : llvm::error_code::success();
276   }
277
278   pointer operator ->() {
279     return toPointer(get());
280   }
281
282   reference operator *() {
283     return *get();
284   }
285
286 private:
287   template <class OtherT>
288   void copyConstruct(const ErrorOr<OtherT> &Other) {
289     // Construct an invalid ErrorOr if other is invalid.
290     if (!Other.IsValid)
291       return;
292     IsValid = true;
293     if (!Other.HasError) {
294       // Get the other value.
295       HasError = false;
296       new (get()) storage_type(*Other.get());
297     } else {
298       // Get other's error.
299       Error = Other.Error;
300       HasError = true;
301       Error->aquire();
302     }
303   }
304
305   template <class T1>
306   static bool compareThisIfSameType(const T1 &a, const T1 &b) {
307     return &a == &b;
308   }
309
310   template <class T1, class T2>
311   static bool compareThisIfSameType(const T1 &a, const T2 &b) {
312     return false;
313   }
314
315   template <class OtherT>
316   void copyAssign(const ErrorOr<OtherT> &Other) {
317     if (compareThisIfSameType(*this, Other))
318       return;
319
320     this->~ErrorOr();
321     new (this) ErrorOr(Other);
322   }
323
324 #if LLVM_HAS_RVALUE_REFERENCES
325   template <class OtherT>
326   void moveConstruct(ErrorOr<OtherT> &&Other) {
327     // Construct an invalid ErrorOr if other is invalid.
328     if (!Other.IsValid)
329       return;
330     IsValid = true;
331     if (!Other.HasError) {
332       // Get the other value.
333       HasError = false;
334       new (get()) storage_type(std::move(*Other.get()));
335       // Tell other not to do any destruction.
336       Other.IsValid = false;
337     } else {
338       // Get other's error.
339       Error = Other.Error;
340       HasError = true;
341       // Tell other not to do any destruction.
342       Other.IsValid = false;
343     }
344   }
345
346   template <class OtherT>
347   void moveAssign(ErrorOr<OtherT> &&Other) {
348     if (compareThisIfSameType(*this, Other))
349       return;
350
351     this->~ErrorOr();
352     new (this) ErrorOr(std::move(Other));
353   }
354 #endif
355
356   pointer toPointer(pointer Val) {
357     return Val;
358   }
359
360   pointer toPointer(wrap *Val) {
361     return &Val->get();
362   }
363
364   storage_type *get() {
365     assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
366     assert(!HasError && "Cannot get value when an error exists!");
367     return reinterpret_cast<storage_type*>(TStorage.buffer);
368   }
369
370   const storage_type *get() const {
371     assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
372     assert(!HasError && "Cannot get value when an error exists!");
373     return reinterpret_cast<const storage_type*>(TStorage.buffer);
374   }
375
376   union {
377     AlignedCharArrayUnion<storage_type> TStorage;
378     ErrorHolderBase *Error;
379   };
380   bool HasError : 1;
381   bool IsValid : 1;
382 };
383
384 // ErrorOr specialization for void.
385 template <>
386 class ErrorOr<void> {
387 public:
388   ErrorOr() : Error(0, 0) {}
389
390   ErrorOr(llvm::error_code EC) : Error(0, 0) {
391     if (EC == errc::success) {
392       Error.setInt(1);
393       return;
394     }
395     ErrorHolderBase *E = new ErrorHolderBase;
396     E->Error = EC;
397     E->HasUserData = false;
398     Error.setPointer(E);
399   }
400
401   template<class UserDataT>
402   ErrorOr(UserDataT UD, typename
403           enable_if_c<ErrorOrUserDataTraits<UserDataT>::value>::type* = 0)
404       : Error(0, 0) {
405     ErrorHolderBase *E = new ErrorHolder<UserDataT>(llvm_move(UD));
406     E->Error = ErrorOrUserDataTraits<UserDataT>::error();
407     E->HasUserData = true;
408     Error.setPointer(E);
409   }
410
411   ErrorOr(const ErrorOr &Other) : Error(0, 0) {
412     Error = Other.Error;
413     if (Other.Error.getPointer()->Error) {
414       Error.getPointer()->aquire();
415     }
416   }
417
418   ErrorOr &operator =(const ErrorOr &Other) {
419     if (this == &Other)
420       return *this;
421
422     this->~ErrorOr();
423     new (this) ErrorOr(Other);
424
425     return *this;
426   }
427
428 #if LLVM_HAS_RVALUE_REFERENCES
429   ErrorOr(ErrorOr &&Other) : Error(0) {
430     // Get other's error.
431     Error = Other.Error;
432     // Tell other not to do any destruction.
433     Other.Error.setPointer(0);
434   }
435
436   ErrorOr &operator =(ErrorOr &&Other) {
437     if (this == &Other)
438       return *this;
439
440     this->~ErrorOr();
441     new (this) ErrorOr(std::move(Other));
442
443     return *this;
444   }
445 #endif
446
447   ~ErrorOr() {
448     if (Error.getPointer())
449       Error.getPointer()->release();
450   }
451
452   template<class ET>
453   ET getError() const {
454     assert(ErrorOrUserDataTraits<ET>::error() == *this &&
455            "Incorrect user error data type for error!");
456     if (!Error.getPointer()->HasUserData)
457       return ET();
458     return reinterpret_cast<const ErrorHolder<ET> *>(
459         Error.getPointer())->UserData;
460   }
461
462   typedef void (*unspecified_bool_type)();
463   static void unspecified_bool_true() {}
464
465   /// \brief Return false if there is an error.
466   operator unspecified_bool_type() const {
467     return Error.getInt() ? unspecified_bool_true : 0;
468   }
469
470   operator llvm::error_code() const {
471     return Error.getInt() ? make_error_code(errc::success)
472                           : Error.getPointer()->Error;
473   }
474
475 private:
476   // If the bit is 1, the error is success.
477   llvm::PointerIntPair<ErrorHolderBase *, 1> Error;
478 };
479
480 template<class T, class E>
481 typename enable_if_c<is_error_code_enum<E>::value ||
482                      is_error_condition_enum<E>::value, bool>::type
483 operator ==(ErrorOr<T> &Err, E Code) {
484   return error_code(Err) == Code;
485 }
486 } // end namespace llvm
487
488 #endif