[Support][ErrorOr] Add optimized specialization of ErrorOr<void>.
[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   static const bool isRef = is_reference<T>::value;
166   typedef ReferenceStorage<typename remove_reference<T>::type> wrap;
167
168 public:
169   typedef typename
170     conditional< isRef
171                , wrap
172                , T
173                >::type storage_type;
174
175 private:
176   typedef typename remove_reference<T>::type &reference;
177   typedef typename remove_reference<T>::type *pointer;
178
179 public:
180   ErrorOr() : IsValid(false) {}
181
182   ErrorOr(llvm::error_code EC) : HasError(true), IsValid(true) {
183     Error = new ErrorHolderBase;
184     Error->Error = EC;
185     Error->HasUserData = false;
186   }
187
188   template<class UserDataT>
189   ErrorOr(UserDataT UD, typename
190           enable_if_c<ErrorOrUserDataTraits<UserDataT>::value>::type* = 0)
191     : HasError(true), IsValid(true) {
192     Error = new ErrorHolder<UserDataT>(llvm_move(UD));
193     Error->Error = ErrorOrUserDataTraits<UserDataT>::error();
194     Error->HasUserData = true;
195   }
196
197   ErrorOr(T Val) : HasError(false), IsValid(true) {
198     new (get()) storage_type(moveIfMoveConstructible<storage_type>(Val));
199   }
200
201   ErrorOr(const ErrorOr &Other) : IsValid(false) {
202     // Construct an invalid ErrorOr if other is invalid.
203     if (!Other.IsValid)
204       return;
205     if (!Other.HasError) {
206       // Get the other value.
207       new (get()) storage_type(*Other.get());
208       HasError = false;
209     } else {
210       // Get other's error.
211       Error = Other.Error;
212       HasError = true;
213       Error->aquire();
214     }
215
216     IsValid = true;
217   }
218
219   ErrorOr &operator =(const ErrorOr &Other) {
220     if (this == &Other)
221       return *this;
222
223     this->~ErrorOr();
224     new (this) ErrorOr(Other);
225
226     return *this;
227   }
228
229 #if LLVM_HAS_RVALUE_REFERENCES
230   ErrorOr(ErrorOr &&Other) : IsValid(false) {
231     // Construct an invalid ErrorOr if other is invalid.
232     if (!Other.IsValid)
233       return;
234     if (!Other.HasError) {
235       // Get the other value.
236       IsValid = true;
237       new (get()) storage_type(std::move(*Other.get()));
238       HasError = false;
239       // Tell other not to do any destruction.
240       Other.IsValid = false;
241     } else {
242       // Get other's error.
243       Error = Other.Error;
244       HasError = true;
245       // Tell other not to do any destruction.
246       Other.IsValid = false;
247     }
248
249     IsValid = true;
250   }
251
252   ErrorOr &operator =(ErrorOr &&Other) {
253     if (this == &Other)
254       return *this;
255
256     this->~ErrorOr();
257     new (this) ErrorOr(std::move(Other));
258
259     return *this;
260   }
261 #endif
262
263   ~ErrorOr() {
264     if (!IsValid)
265       return;
266     if (HasError)
267       Error->release();
268     else
269       get()->~storage_type();
270   }
271
272   template<class ET>
273   ET getError() const {
274     assert(IsValid && "Cannot get the error of a default constructed ErrorOr!");
275     assert(HasError && "Cannot get an error if none exists!");
276     assert(ErrorOrUserDataTraits<ET>::error() == Error->Error &&
277            "Incorrect user error data type for error!");
278     if (!Error->HasUserData)
279       return ET();
280     return reinterpret_cast<const ErrorHolder<ET>*>(Error)->UserData;
281   }
282
283   typedef void (*unspecified_bool_type)();
284   static void unspecified_bool_true() {}
285
286   /// \brief Return false if there is an error.
287   operator unspecified_bool_type() const {
288     assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
289     return HasError ? 0 : unspecified_bool_true;
290   }
291
292   operator llvm::error_code() const {
293     assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
294     return HasError ? Error->Error : llvm::error_code::success();
295   }
296
297   pointer operator ->() {
298     return toPointer(get());
299   }
300
301   reference operator *() {
302     return *get();
303   }
304
305 private:
306   pointer toPointer(pointer Val) {
307     return Val;
308   }
309
310   pointer toPointer(wrap *Val) {
311     return &Val->get();
312   }
313
314 protected:
315   storage_type *get() {
316     assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
317     assert(!HasError && "Cannot get value when an error exists!");
318     return reinterpret_cast<storage_type*>(TStorage.buffer);
319   }
320
321   const storage_type *get() const {
322     assert(IsValid && "Can't do anything on a default constructed ErrorOr!");
323     assert(!HasError && "Cannot get value when an error exists!");
324     return reinterpret_cast<const storage_type*>(TStorage.buffer);
325   }
326
327   union {
328     AlignedCharArrayUnion<storage_type> TStorage;
329     ErrorHolderBase *Error;
330   };
331   bool HasError : 1;
332   bool IsValid : 1;
333 };
334
335 // ErrorOr specialization for void.
336 template <>
337 class ErrorOr<void> {
338 public:
339   ErrorOr() : Error(nullptr, 0) {}
340
341   ErrorOr(llvm::error_code EC) : Error(nullptr, 0) {
342     if (EC == errc::success) {
343       Error.setInt(1);
344       return;
345     }
346     ErrorHolderBase *E = new ErrorHolderBase;
347     E->Error = EC;
348     E->HasUserData = false;
349     Error.setPointer(E);
350   }
351
352   template<class UserDataT>
353   ErrorOr(UserDataT UD, typename
354           enable_if_c<ErrorOrUserDataTraits<UserDataT>::value>::type* = 0)
355       : Error(nullptr, 0) {
356     ErrorHolderBase *E = new ErrorHolder<UserDataT>(llvm_move(UD));
357     E->Error = ErrorOrUserDataTraits<UserDataT>::error();
358     E->HasUserData = true;
359     Error.setPointer(E);
360   }
361
362   ErrorOr(const ErrorOr &Other) : Error(nullptr, 0) {
363     Error = Other.Error;
364     if (Other.Error.getPointer()->Error) {
365       Error.getPointer()->aquire();
366     }
367   }
368
369   ErrorOr &operator =(const ErrorOr &Other) {
370     if (this == &Other)
371       return *this;
372
373     this->~ErrorOr();
374     new (this) ErrorOr(Other);
375
376     return *this;
377   }
378
379 #if LLVM_HAS_RVALUE_REFERENCES
380   ErrorOr(ErrorOr &&Other) : Error(nullptr) {
381     // Get other's error.
382     Error = Other.Error;
383     // Tell other not to do any destruction.
384     Other.Error.setPointer(nullptr);
385   }
386
387   ErrorOr &operator =(ErrorOr &&Other) {
388     if (this == &Other)
389       return *this;
390
391     this->~ErrorOr();
392     new (this) ErrorOr(std::move(Other));
393
394     return *this;
395   }
396 #endif
397
398   ~ErrorOr() {
399     if (Error.getPointer())
400       Error.getPointer()->release();
401   }
402
403   template<class ET>
404   ET getError() const {
405     assert(ErrorOrUserDataTraits<ET>::error() == *this &&
406            "Incorrect user error data type for error!");
407     if (!Error.getPointer()->HasUserData)
408       return ET();
409     return reinterpret_cast<const ErrorHolder<ET> *>(
410         Error.getPointer())->UserData;
411   }
412
413   typedef void (*unspecified_bool_type)();
414   static void unspecified_bool_true() {}
415
416   /// \brief Return false if there is an error.
417   operator unspecified_bool_type() const {
418     return Error.getInt() ? unspecified_bool_true : 0;
419   }
420
421   operator llvm::error_code() const {
422     return Error.getInt() ? make_error_code(errc::success)
423                           : Error.getPointer()->Error;
424   }
425
426 private:
427   // If the bit is 1, the error is success.
428   llvm::PointerIntPair<ErrorHolderBase *, 1> Error;
429 };
430
431 template<class T, class E>
432 typename enable_if_c<is_error_code_enum<E>::value ||
433                      is_error_condition_enum<E>::value, bool>::type
434 operator ==(ErrorOr<T> &Err, E Code) {
435   return error_code(Err) == Code;
436 }
437 } // end namespace llvm
438
439 #endif