LLVM 22.0.0git
Error.h
Go to the documentation of this file.
1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines an API used to report recoverable errors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_ERROR_H
14#define LLVM_SUPPORT_ERROR_H
15
16#include "llvm-c/Error.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/Config/abi-breaking.h"
20#include "llvm/Support/Debug.h"
23#include "llvm/Support/Format.h"
25#include <cassert>
26#include <cstdint>
27#include <cstdlib>
28#include <functional>
29#include <memory>
30#include <new>
31#include <optional>
32#include <string>
33#include <system_error>
34#include <type_traits>
35#include <utility>
36#include <vector>
37
38namespace llvm {
39
40class ErrorSuccess;
41
42/// Base class for error info classes. Do not extend this directly: Extend
43/// the ErrorInfo template subclass instead.
45public:
46 virtual ~ErrorInfoBase() = default;
47
48 /// Print an error message to an output stream.
49 virtual void log(raw_ostream &OS) const = 0;
50
51 /// Return the error message as a string.
52 virtual std::string message() const {
53 std::string Msg;
55 log(OS);
56 return Msg;
57 }
58
59 /// Convert this error to a std::error_code.
60 ///
61 /// This is a temporary crutch to enable interaction with code still
62 /// using std::error_code. It will be removed in the future.
63 virtual std::error_code convertToErrorCode() const = 0;
64
65 // Returns the class ID for this type.
66 static const void *classID() { return &ID; }
67
68 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
69 virtual const void *dynamicClassID() const = 0;
70
71 // Check whether this instance is a subclass of the class identified by
72 // ClassID.
73 virtual bool isA(const void *const ClassID) const {
74 return ClassID == classID();
75 }
76
77 // Check whether this instance is a subclass of ErrorInfoT.
78 template <typename ErrorInfoT> bool isA() const {
79 return isA(ErrorInfoT::classID());
80 }
81
82private:
83 virtual void anchor();
84
85 static char ID;
86};
87
88/// Lightweight error class with error context and mandatory checking.
89///
90/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
91/// are represented by setting the pointer to a ErrorInfoBase subclass
92/// instance containing information describing the failure. Success is
93/// represented by a null pointer value.
94///
95/// Instances of Error also contains a 'Checked' flag, which must be set
96/// before the destructor is called, otherwise the destructor will trigger a
97/// runtime error. This enforces at runtime the requirement that all Error
98/// instances be checked or returned to the caller.
99///
100/// There are two ways to set the checked flag, depending on what state the
101/// Error instance is in. For Error instances indicating success, it
102/// is sufficient to invoke the boolean conversion operator. E.g.:
103///
104/// @code{.cpp}
105/// Error foo(<...>);
106///
107/// if (auto E = foo(<...>))
108/// return E; // <- Return E if it is in the error state.
109/// // We have verified that E was in the success state. It can now be safely
110/// // destroyed.
111/// @endcode
112///
113/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
114/// without testing the return value will raise a runtime error, even if foo
115/// returns success.
116///
117/// For Error instances representing failure, you must use either the
118/// handleErrors or handleAllErrors function with a typed handler. E.g.:
119///
120/// @code{.cpp}
121/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
122/// // Custom error info.
123/// };
124///
125/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
126///
127/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
128/// auto NewE =
129/// handleErrors(std::move(E),
130/// [](const MyErrorInfo &M) {
131/// // Deal with the error.
132/// },
133/// [](std::unique_ptr<OtherError> M) -> Error {
134/// if (canHandle(*M)) {
135/// // handle error.
136/// return Error::success();
137/// }
138/// // Couldn't handle this error instance. Pass it up the stack.
139/// return Error(std::move(M));
140/// });
141/// // Note - The error passed to handleErrors will be marked as checked. If
142/// // there is no matched handler, a new error with the same payload is
143/// // created and returned.
144/// // The handlers take the error checked by handleErrors as an argument,
145/// // which can be used to retrieve more information. If a new error is
146/// // created by a handler, it will be passed back to the caller of
147/// // handleErrors and needs to be checked or return up to the stack.
148/// // Otherwise, the passed-in error is considered consumed.
149/// @endcode
150///
151/// The handleAllErrors function is identical to handleErrors, except
152/// that it has a void return type, and requires all errors to be handled and
153/// no new errors be returned. It prevents errors (assuming they can all be
154/// handled) from having to be bubbled all the way to the top-level.
155///
156/// *All* Error instances must be checked before destruction, even if
157/// they're moved-assigned or constructed from Success values that have already
158/// been checked. This enforces checking through all levels of the call stack.
159class [[nodiscard]] Error {
160 // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
161 // to add to the error list. It can't rely on handleErrors for this, since
162 // handleErrors does not support ErrorList handlers.
163 friend class ErrorList;
164
165 // handleErrors needs to be able to set the Checked flag.
166 template <typename... HandlerTs>
167 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
168 // visitErrors needs direct access to the payload.
169 template <typename HandlerT>
170 friend void visitErrors(const Error &E, HandlerT H);
171
172 // Expected<T> needs to be able to steal the payload when constructed from an
173 // error.
174 template <typename T> friend class Expected;
175
176 // wrap needs to be able to steal the payload.
177 friend LLVMErrorRef wrap(Error);
178
179protected:
180 /// Create a success value. Prefer using 'Error::success()' for readability
182 setPtr(nullptr);
183 setChecked(false);
184 }
185
186public:
187 /// Create a success value.
188 static ErrorSuccess success();
189
190 // Errors are not copy-constructable.
191 Error(const Error &Other) = delete;
192
193 /// Move-construct an error value. The newly constructed error is considered
194 /// unchecked, even if the source error had been checked. The original error
195 /// becomes a checked Success value, regardless of its original state.
197 setChecked(true);
198 *this = std::move(Other);
199 }
200
201 /// Create an error value. Prefer using the 'make_error' function, but
202 /// this constructor can be useful when "re-throwing" errors from handlers.
203 Error(std::unique_ptr<ErrorInfoBase> Payload) {
204 setPtr(Payload.release());
205 setChecked(false);
206 }
207
208 // Errors are not copy-assignable.
209 Error &operator=(const Error &Other) = delete;
210
211 /// Move-assign an error value. The current error must represent success, you
212 /// you cannot overwrite an unhandled error. The current error is then
213 /// considered unchecked. The source error becomes a checked success value,
214 /// regardless of its original state.
216 // Don't allow overwriting of unchecked values.
217 assertIsChecked();
218 setPtr(Other.getPtr());
219
220 // This Error is unchecked, even if the source error was checked.
221 setChecked(false);
222
223 // Null out Other's payload and set its checked bit.
224 Other.setPtr(nullptr);
225 Other.setChecked(true);
226
227 return *this;
228 }
229
230 /// Destroy a Error. Fails with a call to abort() if the error is
231 /// unchecked.
233 assertIsChecked();
234 delete getPtr();
235 }
236
237 /// Bool conversion. Returns true if this Error is in a failure state,
238 /// and false if it is in an accept state. If the error is in a Success state
239 /// it will be considered checked.
240 explicit operator bool() {
241 setChecked(getPtr() == nullptr);
242 return getPtr() != nullptr;
243 }
244
245 /// Check whether one error is a subclass of another.
246 template <typename ErrT> bool isA() const {
247 return getPtr() && getPtr()->isA(ErrT::classID());
248 }
249
250 /// Returns the dynamic class id of this error, or null if this is a success
251 /// value.
252 const void* dynamicClassID() const {
253 if (!getPtr())
254 return nullptr;
255 return getPtr()->dynamicClassID();
256 }
257
258private:
259#if LLVM_ENABLE_ABI_BREAKING_CHECKS
260 // assertIsChecked() happens very frequently, but under normal circumstances
261 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
262 // of debug prints can cause the function to be too large for inlining. So
263 // it's important that we define this function out of line so that it can't be
264 // inlined.
265 [[noreturn]] LLVM_ABI void fatalUncheckedError() const;
266#endif
267
268 void assertIsChecked() {
269#if LLVM_ENABLE_ABI_BREAKING_CHECKS
270 if (LLVM_UNLIKELY(!getChecked() || getPtr()))
271 fatalUncheckedError();
272#endif
273 }
274
275 ErrorInfoBase *getPtr() const {
276#if LLVM_ENABLE_ABI_BREAKING_CHECKS
277 return reinterpret_cast<ErrorInfoBase*>(
278 reinterpret_cast<uintptr_t>(Payload) &
279 ~static_cast<uintptr_t>(0x1));
280#else
281 return Payload;
282#endif
283 }
284
285 void setPtr(ErrorInfoBase *EI) {
286#if LLVM_ENABLE_ABI_BREAKING_CHECKS
287 Payload = reinterpret_cast<ErrorInfoBase*>(
288 (reinterpret_cast<uintptr_t>(EI) &
289 ~static_cast<uintptr_t>(0x1)) |
290 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
291#else
292 Payload = EI;
293#endif
294 }
295
296 bool getChecked() const {
297#if LLVM_ENABLE_ABI_BREAKING_CHECKS
298 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
299#else
300 return true;
301#endif
302 }
303
304 void setChecked(bool V) {
305#if LLVM_ENABLE_ABI_BREAKING_CHECKS
306 Payload = reinterpret_cast<ErrorInfoBase*>(
307 (reinterpret_cast<uintptr_t>(Payload) &
308 ~static_cast<uintptr_t>(0x1)) |
309 (V ? 0 : 1));
310#endif
311 }
312
313 std::unique_ptr<ErrorInfoBase> takePayload() {
314 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
315 setPtr(nullptr);
316 setChecked(true);
317 return Tmp;
318 }
319
321 if (auto *P = E.getPtr())
322 P->log(OS);
323 else
324 OS << "success";
325 return OS;
326 }
327
328 ErrorInfoBase *Payload = nullptr;
329};
330
331/// Subclass of Error for the sole purpose of identifying the success path in
332/// the type system. This allows to catch invalid conversion to Expected<T> at
333/// compile time.
334class ErrorSuccess final : public Error {};
335
337
338/// Make a Error instance representing failure using the given error info
339/// type.
340template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
341 return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
342}
343
344/// Base class for user error types. Users should declare their error types
345/// like:
346///
347/// class MyError : public ErrorInfo<MyError> {
348/// ....
349/// };
350///
351/// This class provides an implementation of the ErrorInfoBase::kind
352/// method, which is used by the Error RTTI system.
353template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
354class ErrorInfo : public ParentErrT {
355public:
356 using ParentErrT::ParentErrT; // inherit constructors
357
358 static const void *classID() { return &ThisErrT::ID; }
359
360 const void *dynamicClassID() const override { return &ThisErrT::ID; }
361
362 bool isA(const void *const ClassID) const override {
363 return ClassID == classID() || ParentErrT::isA(ClassID);
364 }
365};
366
367/// Special ErrorInfo subclass representing a list of ErrorInfos.
368/// Instances of this class are constructed by joinError.
369class LLVM_ABI ErrorList final : public ErrorInfo<ErrorList> {
370 // handleErrors needs to be able to iterate the payload list of an
371 // ErrorList.
372 template <typename... HandlerTs>
373 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
374 // visitErrors needs to be able to iterate the payload list of an
375 // ErrorList.
376 template <typename HandlerT>
377 friend void visitErrors(const Error &E, HandlerT H);
378
379 // joinErrors is implemented in terms of join.
380 friend Error joinErrors(Error, Error);
381
382public:
383 void log(raw_ostream &OS) const override {
384 OS << "Multiple errors:\n";
385 for (const auto &ErrPayload : Payloads) {
386 ErrPayload->log(OS);
387 OS << "\n";
388 }
389 }
390
391 std::error_code convertToErrorCode() const override;
392
393 // Used by ErrorInfo::classID.
394 static char ID;
395
396private:
397 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
398 std::unique_ptr<ErrorInfoBase> Payload2) {
399 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
400 "ErrorList constructor payloads should be singleton errors");
401 Payloads.push_back(std::move(Payload1));
402 Payloads.push_back(std::move(Payload2));
403 }
404
405 // Explicitly non-copyable.
406 ErrorList(ErrorList const &) = delete;
407 ErrorList &operator=(ErrorList const &) = delete;
408
409 static Error join(Error E1, Error E2) {
410 if (!E1)
411 return E2;
412 if (!E2)
413 return E1;
414 if (E1.isA<ErrorList>()) {
415 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
416 if (E2.isA<ErrorList>()) {
417 auto E2Payload = E2.takePayload();
418 auto &E2List = static_cast<ErrorList &>(*E2Payload);
419 for (auto &Payload : E2List.Payloads)
420 E1List.Payloads.push_back(std::move(Payload));
421 } else {
422 E1List.Payloads.push_back(E2.takePayload());
423 }
424
425 return E1;
426 }
427 if (E2.isA<ErrorList>()) {
428 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
429 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
430 return E2;
431 }
432 return Error(std::unique_ptr<ErrorList>(
433 new ErrorList(E1.takePayload(), E2.takePayload())));
434 }
435
436 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
437};
438
439/// Concatenate errors. The resulting Error is unchecked, and contains the
440/// ErrorInfo(s), if any, contained in E1, followed by the
441/// ErrorInfo(s), if any, contained in E2.
442inline Error joinErrors(Error E1, Error E2) {
443 return ErrorList::join(std::move(E1), std::move(E2));
444}
445
446/// Tagged union holding either a T or a Error.
447///
448/// This class parallels ErrorOr, but replaces error_code with Error. Since
449/// Error cannot be copied, this class replaces getError() with
450/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
451/// error class type.
452///
453/// Example usage of 'Expected<T>' as a function return type:
454///
455/// @code{.cpp}
456/// Expected<int> myDivide(int A, int B) {
457/// if (B == 0) {
458/// // return an Error
459/// return createStringError(inconvertibleErrorCode(),
460/// "B must not be zero!");
461/// }
462/// // return an integer
463/// return A / B;
464/// }
465/// @endcode
466///
467/// Checking the results of to a function returning 'Expected<T>':
468/// @code{.cpp}
469/// if (auto E = Result.takeError()) {
470/// // We must consume the error. Typically one of:
471/// // - return the error to our caller
472/// // - toString(), when logging
473/// // - consumeError(), to silently swallow the error
474/// // - handleErrors(), to distinguish error types
475/// errs() << "Problem with division " << toString(std::move(E)) << "\n";
476/// return;
477/// }
478/// // use the result
479/// outs() << "The answer is " << *Result << "\n";
480/// @endcode
481///
482/// For unit-testing a function returning an 'Expected<T>', see the
483/// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
484
485template <class T> class [[nodiscard]] Expected {
486 template <class T1> friend class ExpectedAsOutParameter;
487 template <class OtherT> friend class Expected;
488
489 static constexpr bool isRef = std::is_reference_v<T>;
490
491 using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
492
493 using error_type = std::unique_ptr<ErrorInfoBase>;
494
495public:
496 using storage_type = std::conditional_t<isRef, wrap, T>;
497 using value_type = T;
498
499private:
500 using reference = std::remove_reference_t<T> &;
501 using const_reference = const std::remove_reference_t<T> &;
502 using pointer = std::remove_reference_t<T> *;
503 using const_pointer = const std::remove_reference_t<T> *;
504
505public:
506 /// Create an Expected<T> error value from the given Error.
508 : HasError(true)
509#if LLVM_ENABLE_ABI_BREAKING_CHECKS
510 // Expected is unchecked upon construction in Debug builds.
511 , Unchecked(true)
512#endif
513 {
514 assert(Err && "Cannot create Expected<T> from Error success value.");
515 new (getErrorStorage()) error_type(Err.takePayload());
516 }
517
518 /// Forbid to convert from Error::success() implicitly, this avoids having
519 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
520 /// but triggers the assertion above.
522
523 /// Create an Expected<T> success value from the given OtherT value, which
524 /// must be convertible to T.
525 template <typename OtherT>
526 Expected(OtherT &&Val,
527 std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
528 : HasError(false)
529#if LLVM_ENABLE_ABI_BREAKING_CHECKS
530 // Expected is unchecked upon construction in Debug builds.
531 ,
533#endif
534 {
535 new (getStorage()) storage_type(std::forward<OtherT>(Val));
536 }
537
538 /// Move construct an Expected<T> value.
539 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
540
541 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
542 /// must be convertible to T.
543 template <class OtherT>
545 std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr) {
546 moveConstruct(std::move(Other));
547 }
548
549 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
550 /// isn't convertible to T.
551 template <class OtherT>
552 explicit Expected(
554 std::enable_if_t<!std::is_convertible_v<OtherT, T>> * = nullptr) {
555 moveConstruct(std::move(Other));
556 }
557
558 /// Move-assign from another Expected<T>.
560 moveAssign(std::move(Other));
561 return *this;
562 }
563
564 /// Destroy an Expected<T>.
566 assertIsChecked();
567 if (!HasError)
568 getStorage()->~storage_type();
569 else
570 getErrorStorage()->~error_type();
571 }
572
573 /// Return false if there is an error.
574 explicit operator bool() {
575#if LLVM_ENABLE_ABI_BREAKING_CHECKS
576 Unchecked = HasError;
577#endif
578 return !HasError;
579 }
580
581 /// Returns a reference to the stored T value.
582 reference get() {
583 assertIsChecked();
584 return *getStorage();
585 }
586
587 /// Returns a const reference to the stored T value.
588 const_reference get() const {
589 assertIsChecked();
590 return const_cast<Expected<T> *>(this)->get();
591 }
592
593 /// Returns \a takeError() after moving the held T (if any) into \p V.
594 template <class OtherT>
596 OtherT &Value,
597 std::enable_if_t<std::is_assignable_v<OtherT &, T &&>> * = nullptr) && {
598 if (*this)
599 Value = std::move(get());
600 return takeError();
601 }
602
603 /// Check that this Expected<T> is an error of type ErrT.
604 template <typename ErrT> bool errorIsA() const {
605 return HasError && (*getErrorStorage())->template isA<ErrT>();
606 }
607
608 /// Take ownership of the stored error.
609 /// After calling this the Expected<T> is in an indeterminate state that can
610 /// only be safely destructed. No further calls (beside the destructor) should
611 /// be made on the Expected<T> value.
613#if LLVM_ENABLE_ABI_BREAKING_CHECKS
614 Unchecked = false;
615#endif
616 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
617 }
618
619 /// Returns a pointer to the stored T value.
620 pointer operator->() {
621 assertIsChecked();
622 return toPointer(getStorage());
623 }
624
625 /// Returns a const pointer to the stored T value.
626 const_pointer operator->() const {
627 assertIsChecked();
628 return toPointer(getStorage());
629 }
630
631 /// Returns a reference to the stored T value.
632 reference operator*() {
633 assertIsChecked();
634 return *getStorage();
635 }
636
637 /// Returns a const reference to the stored T value.
638 const_reference operator*() const {
639 assertIsChecked();
640 return *getStorage();
641 }
642
643private:
644 template <class T1>
645 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
646 return &a == &b;
647 }
648
649 template <class T1, class T2>
650 static bool compareThisIfSameType(const T1 &, const T2 &) {
651 return false;
652 }
653
654 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
655 HasError = Other.HasError;
656#if LLVM_ENABLE_ABI_BREAKING_CHECKS
657 Unchecked = true;
658 Other.Unchecked = false;
659#endif
660
661 if (!HasError)
662 new (getStorage()) storage_type(std::move(*Other.getStorage()));
663 else
664 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
665 }
666
667 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
668 assertIsChecked();
669
670 if (compareThisIfSameType(*this, Other))
671 return;
672
673 this->~Expected();
674 new (this) Expected(std::move(Other));
675 }
676
677 pointer toPointer(pointer Val) { return Val; }
678
679 const_pointer toPointer(const_pointer Val) const { return Val; }
680
681 pointer toPointer(wrap *Val) { return &Val->get(); }
682
683 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
684
685 storage_type *getStorage() {
686 assert(!HasError && "Cannot get value when an error exists!");
687 return &TStorage;
688 }
689
690 const storage_type *getStorage() const {
691 assert(!HasError && "Cannot get value when an error exists!");
692 return &TStorage;
693 }
694
695 error_type *getErrorStorage() {
696 assert(HasError && "Cannot get error when a value exists!");
697 return &ErrorStorage;
698 }
699
700 const error_type *getErrorStorage() const {
701 assert(HasError && "Cannot get error when a value exists!");
702 return &ErrorStorage;
703 }
704
705 // Used by ExpectedAsOutParameter to reset the checked flag.
706 void setUnchecked() {
707#if LLVM_ENABLE_ABI_BREAKING_CHECKS
708 Unchecked = true;
709#endif
710 }
711
712#if LLVM_ENABLE_ABI_BREAKING_CHECKS
713 [[noreturn]] LLVM_ATTRIBUTE_NOINLINE void fatalUncheckedExpected() const {
714 dbgs() << "Expected<T> must be checked before access or destruction.\n";
715 if (HasError) {
716 dbgs() << "Unchecked Expected<T> contained error:\n";
717 (*getErrorStorage())->log(dbgs());
718 } else {
719 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
720 "values in success mode must still be checked prior to being "
721 "destroyed).\n";
722 }
723 abort();
724 }
725#endif
726
727 void assertIsChecked() const {
728#if LLVM_ENABLE_ABI_BREAKING_CHECKS
730 fatalUncheckedExpected();
731#endif
732 }
733
734 union {
736 error_type ErrorStorage;
737 };
738 bool HasError : 1;
739#if LLVM_ENABLE_ABI_BREAKING_CHECKS
740 bool Unchecked : 1;
741#endif
742};
743
744/// @deprecated Use reportFatalInternalError() or reportFatalUsageError()
745/// instead.
746[[noreturn]] LLVM_ABI void report_fatal_error(Error Err,
747 bool gen_crash_diag = true);
748
749/// Report a fatal error that indicates a bug in LLVM.
750/// See ErrorHandling.h for details.
751[[noreturn]] LLVM_ABI void reportFatalInternalError(Error Err);
752/// Report a fatal error that does not indicate a bug in LLVM.
753/// See ErrorHandling.h for details.
754[[noreturn]] LLVM_ABI void reportFatalUsageError(Error Err);
755
756/// Report a fatal error if Err is a failure value.
757///
758/// This function can be used to wrap calls to fallible functions ONLY when it
759/// is known that the Error will always be a success value. E.g.
760///
761/// @code{.cpp}
762/// // foo only attempts the fallible operation if DoFallibleOperation is
763/// // true. If DoFallibleOperation is false then foo always returns
764/// // Error::success().
765/// Error foo(bool DoFallibleOperation);
766///
767/// cantFail(foo(false));
768/// @endcode
769inline void cantFail(Error Err, const char *Msg = nullptr) {
770 if (Err) {
771 if (!Msg)
772 Msg = "Failure value returned from cantFail wrapped call";
773#ifndef NDEBUG
774 std::string Str;
776 OS << Msg << "\n" << Err;
777 Msg = Str.c_str();
778#endif
779 llvm_unreachable(Msg);
780 }
781}
782
783/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
784/// returns the contained value.
785///
786/// This function can be used to wrap calls to fallible functions ONLY when it
787/// is known that the Error will always be a success value. E.g.
788///
789/// @code{.cpp}
790/// // foo only attempts the fallible operation if DoFallibleOperation is
791/// // true. If DoFallibleOperation is false then foo always returns an int.
792/// Expected<int> foo(bool DoFallibleOperation);
793///
794/// int X = cantFail(foo(false));
795/// @endcode
796template <typename T>
797T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
798 if (ValOrErr)
799 return std::move(*ValOrErr);
800 else {
801 if (!Msg)
802 Msg = "Failure value returned from cantFail wrapped call";
803#ifndef NDEBUG
804 std::string Str;
806 auto E = ValOrErr.takeError();
807 OS << Msg << "\n" << E;
808 Msg = Str.c_str();
809#endif
810 llvm_unreachable(Msg);
811 }
812}
813
814/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
815/// returns the contained reference.
816///
817/// This function can be used to wrap calls to fallible functions ONLY when it
818/// is known that the Error will always be a success value. E.g.
819///
820/// @code{.cpp}
821/// // foo only attempts the fallible operation if DoFallibleOperation is
822/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
823/// Expected<Bar&> foo(bool DoFallibleOperation);
824///
825/// Bar &X = cantFail(foo(false));
826/// @endcode
827template <typename T>
828T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
829 if (ValOrErr)
830 return *ValOrErr;
831 else {
832 if (!Msg)
833 Msg = "Failure value returned from cantFail wrapped call";
834#ifndef NDEBUG
835 std::string Str;
837 auto E = ValOrErr.takeError();
838 OS << Msg << "\n" << E;
839 Msg = Str.c_str();
840#endif
841 llvm_unreachable(Msg);
842 }
843}
844
845/// Helper for testing applicability of, and applying, handlers for
846/// ErrorInfo types.
847template <typename HandlerT>
849 : public ErrorHandlerTraits<
850 decltype(&std::remove_reference_t<HandlerT>::operator())> {};
851
852// Specialization functions of the form 'Error (const ErrT&)'.
853template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
854public:
855 static bool appliesTo(const ErrorInfoBase &E) {
856 return E.template isA<ErrT>();
857 }
858
859 template <typename HandlerT>
860 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
861 assert(appliesTo(*E) && "Applying incorrect handler");
862 return H(static_cast<ErrT &>(*E));
863 }
864};
865
866// Specialization functions of the form 'void (const ErrT&)'.
867template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
868public:
869 static bool appliesTo(const ErrorInfoBase &E) {
870 return E.template isA<ErrT>();
871 }
872
873 template <typename HandlerT>
874 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
875 assert(appliesTo(*E) && "Applying incorrect handler");
876 H(static_cast<ErrT &>(*E));
877 return Error::success();
878 }
879};
880
881/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
882template <typename ErrT>
883class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
884public:
885 static bool appliesTo(const ErrorInfoBase &E) {
886 return E.template isA<ErrT>();
887 }
888
889 template <typename HandlerT>
890 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
891 assert(appliesTo(*E) && "Applying incorrect handler");
892 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
893 return H(std::move(SubE));
894 }
895};
896
897/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
898template <typename ErrT>
899class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
900public:
901 static bool appliesTo(const ErrorInfoBase &E) {
902 return E.template isA<ErrT>();
903 }
904
905 template <typename HandlerT>
906 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
907 assert(appliesTo(*E) && "Applying incorrect handler");
908 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
909 H(std::move(SubE));
910 return Error::success();
911 }
912};
913
914// Specialization for member functions of the form 'RetT (const ErrT&)'.
915template <typename C, typename RetT, typename ErrT>
916class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
917 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
918
919// Specialization for member functions of the form 'RetT (const ErrT&) const'.
920template <typename C, typename RetT, typename ErrT>
921class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
922 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
923
924// Specialization for member functions of the form 'RetT (const ErrT&)'.
925template <typename C, typename RetT, typename ErrT>
926class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
927 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
928
929// Specialization for member functions of the form 'RetT (const ErrT&) const'.
930template <typename C, typename RetT, typename ErrT>
931class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
932 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
933
934/// Specialization for member functions of the form
935/// 'RetT (std::unique_ptr<ErrT>)'.
936template <typename C, typename RetT, typename ErrT>
937class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
938 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
939
940/// Specialization for member functions of the form
941/// 'RetT (std::unique_ptr<ErrT>) const'.
942template <typename C, typename RetT, typename ErrT>
943class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
944 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
945
946inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
947 return Error(std::move(Payload));
948}
949
950template <typename HandlerT, typename... HandlerTs>
951Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
952 HandlerT &&Handler, HandlerTs &&... Handlers) {
954 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
955 std::move(Payload));
956 return handleErrorImpl(std::move(Payload),
957 std::forward<HandlerTs>(Handlers)...);
958}
959
960/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
961/// unhandled errors (or Errors returned by handlers) are re-concatenated and
962/// returned.
963/// Because this function returns an error, its result must also be checked
964/// or returned. If you intend to handle all errors use handleAllErrors
965/// (which returns void, and will abort() on unhandled errors) instead.
966template <typename... HandlerTs>
967Error handleErrors(Error E, HandlerTs &&... Hs) {
968 if (!E)
969 return Error::success();
970
971 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
972
973 if (Payload->isA<ErrorList>()) {
974 ErrorList &List = static_cast<ErrorList &>(*Payload);
975 Error R;
976 for (auto &P : List.Payloads)
977 R = ErrorList::join(
978 std::move(R),
979 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
980 return R;
981 }
982
983 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
984}
985
986/// Behaves the same as handleErrors, except that by contract all errors
987/// *must* be handled by the given handlers (i.e. there must be no remaining
988/// errors after running the handlers, or llvm_unreachable is called).
989template <typename... HandlerTs>
990void handleAllErrors(Error E, HandlerTs &&... Handlers) {
991 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
992}
993
994/// Check that E is a non-error, then drop it.
995/// If E is an error, llvm_unreachable will be called.
996inline void handleAllErrors(Error E) {
997 cantFail(std::move(E));
998}
999
1000/// Visit all the ErrorInfo(s) contained in E by passing them to the respective
1001/// handler, without consuming the error.
1002template <typename HandlerT> void visitErrors(const Error &E, HandlerT H) {
1003 const ErrorInfoBase *Payload = E.getPtr();
1004 if (!Payload)
1005 return;
1006
1007 if (Payload->isA<ErrorList>()) {
1008 const ErrorList &List = static_cast<const ErrorList &>(*Payload);
1009 for (const auto &P : List.Payloads)
1010 H(*P);
1011 return;
1012 }
1013
1014 return H(*Payload);
1015}
1016
1017/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
1018///
1019/// If the incoming value is a success value it is returned unmodified. If it
1020/// is a failure value then it the contained error is passed to handleErrors.
1021/// If handleErrors is able to handle the error then the RecoveryPath functor
1022/// is called to supply the final result. If handleErrors is not able to
1023/// handle all errors then the unhandled errors are returned.
1024///
1025/// This utility enables the follow pattern:
1026///
1027/// @code{.cpp}
1028/// enum FooStrategy { Aggressive, Conservative };
1029/// Expected<Foo> foo(FooStrategy S);
1030///
1031/// auto ResultOrErr =
1032/// handleExpected(
1033/// foo(Aggressive),
1034/// []() { return foo(Conservative); },
1035/// [](AggressiveStrategyError&) {
1036/// // Implicitly conusme this - we'll recover by using a conservative
1037/// // strategy.
1038/// });
1039///
1040/// @endcode
1041template <typename T, typename RecoveryFtor, typename... HandlerTs>
1042Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
1043 HandlerTs &&... Handlers) {
1044 if (ValOrErr)
1045 return ValOrErr;
1046
1047 if (auto Err = handleErrors(ValOrErr.takeError(),
1048 std::forward<HandlerTs>(Handlers)...))
1049 return std::move(Err);
1050
1051 return RecoveryPath();
1052}
1053
1054/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
1055/// will be printed before the first one is logged. A newline will be printed
1056/// after each error.
1057///
1058/// This function is compatible with the helpers from Support/WithColor.h. You
1059/// can pass any of them as the OS. Please consider using them instead of
1060/// including 'error: ' in the ErrorBanner.
1061///
1062/// This is useful in the base level of your program to allow clean termination
1063/// (allowing clean deallocation of resources, etc.), while reporting error
1064/// information to the user.
1065LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS,
1066 Twine ErrorBanner = {});
1067
1068/// Write all error messages (if any) in E to a string. The newline character
1069/// is used to separate error messages.
1070LLVM_ABI std::string toString(Error E);
1071
1072/// Like toString(), but does not consume the error. This can be used to print
1073/// a warning while retaining the original error object.
1074LLVM_ABI std::string toStringWithoutConsuming(const Error &E);
1075
1076/// Consume a Error without doing anything. This method should be used
1077/// only where an error can be considered a reasonable and expected return
1078/// value.
1079///
1080/// Uses of this method are potentially indicative of design problems: If it's
1081/// legitimate to do nothing while processing an "error", the error-producer
1082/// might be more clearly refactored to return an std::optional<T>.
1083inline void consumeError(Error Err) {
1084 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1085}
1086
1087/// Convert an Expected to an Optional without doing anything. This method
1088/// should be used only where an error can be considered a reasonable and
1089/// expected return value.
1090///
1091/// Uses of this method are potentially indicative of problems: perhaps the
1092/// error should be propagated further, or the error-producer should just
1093/// return an Optional in the first place.
1094template <typename T> std::optional<T> expectedToOptional(Expected<T> &&E) {
1095 if (E)
1096 return std::move(*E);
1097 consumeError(E.takeError());
1098 return std::nullopt;
1099}
1100
1101template <typename T> std::optional<T> expectedToStdOptional(Expected<T> &&E) {
1102 if (E)
1103 return std::move(*E);
1104 consumeError(E.takeError());
1105 return std::nullopt;
1106}
1107
1108/// Helper for converting an Error to a bool.
1109///
1110/// This method returns true if Err is in an error state, or false if it is
1111/// in a success state. Puts Err in a checked state in both cases (unlike
1112/// Error::operator bool(), which only does this for success states).
1113inline bool errorToBool(Error Err) {
1114 bool IsError = static_cast<bool>(Err);
1115 if (IsError)
1116 consumeError(std::move(Err));
1117 return IsError;
1118}
1119
1120/// Helper for Errors used as out-parameters.
1121///
1122/// This helper is for use with the Error-as-out-parameter idiom, where an error
1123/// is passed to a function or method by reference, rather than being returned.
1124/// In such cases it is helpful to set the checked bit on entry to the function
1125/// so that the error can be written to (unchecked Errors abort on assignment)
1126/// and clear the checked bit on exit so that clients cannot accidentally forget
1127/// to check the result. This helper performs these actions automatically using
1128/// RAII:
1129///
1130/// @code{.cpp}
1131/// Result foo(Error &Err) {
1132/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1133/// // <body of foo>
1134/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1135/// }
1136/// @endcode
1137///
1138/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1139/// used with optional Errors (Error pointers that are allowed to be null). If
1140/// ErrorAsOutParameter took an Error reference, an instance would have to be
1141/// created inside every condition that verified that Error was non-null. By
1142/// taking an Error pointer we can just create one instance at the top of the
1143/// function.
1145public:
1146
1147 ErrorAsOutParameter(Error *Err) : Err(Err) {
1148 // Raise the checked bit if Err is success.
1149 if (Err)
1150 (void)!!*Err;
1151 }
1152
1153 ErrorAsOutParameter(Error &Err) : Err(&Err) {
1154 (void)!!Err;
1155 }
1156
1158 // Clear the checked bit.
1159 if (Err && !*Err)
1160 *Err = Error::success();
1161 }
1162
1163private:
1164 Error *Err;
1165};
1166
1167/// Helper for Expected<T>s used as out-parameters.
1168///
1169/// See ErrorAsOutParameter.
1170template <typename T>
1172public:
1174 : ValOrErr(ValOrErr) {
1175 if (ValOrErr)
1176 (void)!!*ValOrErr;
1177 }
1178
1180 if (ValOrErr)
1181 ValOrErr->setUnchecked();
1182 }
1183
1184private:
1185 Expected<T> *ValOrErr;
1186};
1187
1188/// This class wraps a std::error_code in a Error.
1189///
1190/// This is useful if you're writing an interface that returns a Error
1191/// (or Expected) and you want to call code that still returns
1192/// std::error_codes.
1193class LLVM_ABI ECError : public ErrorInfo<ECError> {
1194 LLVM_ABI friend Error errorCodeToError(std::error_code);
1195
1196 void anchor() override;
1197
1198public:
1199 void setErrorCode(std::error_code EC) { this->EC = EC; }
1200 std::error_code convertToErrorCode() const override { return EC; }
1201 void log(raw_ostream &OS) const override { OS << EC.message(); }
1202
1203 // Used by ErrorInfo::classID.
1204 static char ID;
1205
1206protected:
1207 ECError() = default;
1208 ECError(std::error_code EC) : EC(EC) {}
1209
1210 std::error_code EC;
1211};
1212
1213/// The value returned by this function can be returned from convertToErrorCode
1214/// for Error values where no sensible translation to std::error_code exists.
1215/// It should only be used in this situation, and should never be used where a
1216/// sensible conversion to std::error_code is available, as attempts to convert
1217/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1218/// error to try to convert such a value).
1219LLVM_ABI std::error_code inconvertibleErrorCode();
1220
1221/// Helper for converting an std::error_code to a Error.
1222LLVM_ABI Error errorCodeToError(std::error_code EC);
1223
1224/// Helper for converting an ECError to a std::error_code.
1225///
1226/// This method requires that Err be Error() or an ECError, otherwise it
1227/// will trigger a call to abort().
1228LLVM_ABI std::error_code errorToErrorCode(Error Err);
1229
1230/// Helper to get errno as an std::error_code.
1231///
1232/// errno should always be represented using the generic category as that's what
1233/// both libc++ and libstdc++ do. On POSIX systems you can also represent them
1234/// using the system category, however this makes them compare differently for
1235/// values outside of those used by `std::errc` if one is generic and the other
1236/// is system.
1237///
1238/// See the libc++ and libstdc++ implementations of `default_error_condition` on
1239/// the system category for more details on what the difference is.
1240inline std::error_code errnoAsErrorCode() {
1241 return std::error_code(errno, std::generic_category());
1242}
1243
1244/// Convert an ErrorOr<T> to an Expected<T>.
1245template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1246 if (auto EC = EO.getError())
1247 return errorCodeToError(EC);
1248 return std::move(*EO);
1249}
1250
1251/// Convert an Expected<T> to an ErrorOr<T>.
1252template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1253 if (auto Err = E.takeError())
1254 return errorToErrorCode(std::move(Err));
1255 return std::move(*E);
1256}
1257
1258/// This class wraps a string in an Error.
1259///
1260/// StringError is useful in cases where the client is not expected to be able
1261/// to consume the specific error message programmatically (for example, if the
1262/// error message is to be presented to the user).
1263///
1264/// StringError can also be used when additional information is to be printed
1265/// along with a error_code message. Depending on the constructor called, this
1266/// class can either display:
1267/// 1. the error_code message (ECError behavior)
1268/// 2. a string
1269/// 3. the error_code message and a string
1270///
1271/// These behaviors are useful when subtyping is required; for example, when a
1272/// specific library needs an explicit error type. In the example below,
1273/// PDBError is derived from StringError:
1274///
1275/// @code{.cpp}
1276/// Expected<int> foo() {
1277/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1278/// "Additional information");
1279/// }
1280/// @endcode
1281///
1282class LLVM_ABI StringError : public ErrorInfo<StringError> {
1283public:
1284 static char ID;
1285
1286 StringError(std::string &&S, std::error_code EC, bool PrintMsgOnly);
1287 /// Prints EC + S and converts to EC.
1288 StringError(std::error_code EC, const Twine &S = Twine());
1289 /// Prints S and converts to EC.
1290 StringError(const Twine &S, std::error_code EC);
1291
1292 void log(raw_ostream &OS) const override;
1293 std::error_code convertToErrorCode() const override;
1294
1295 const std::string &getMessage() const { return Msg; }
1296
1297private:
1298 std::string Msg;
1299 std::error_code EC;
1300 const bool PrintMsgOnly = false;
1301};
1302
1303/// Create formatted StringError object.
1304template <typename... Ts>
1305inline Error createStringError(std::error_code EC, char const *Fmt,
1306 const Ts &... Vals) {
1307 std::string Buffer;
1308 raw_string_ostream(Buffer) << format(Fmt, Vals...);
1309 return make_error<StringError>(Buffer, EC);
1310}
1311
1312LLVM_ABI Error createStringError(std::string &&Msg, std::error_code EC);
1313
1314inline Error createStringError(std::error_code EC, const char *S) {
1315 return createStringError(std::string(S), EC);
1316}
1317
1318inline Error createStringError(std::error_code EC, const Twine &S) {
1319 return createStringError(S.str(), EC);
1320}
1321
1322/// Create a StringError with an inconvertible error code.
1325}
1326
1327template <typename... Ts>
1328inline Error createStringError(char const *Fmt, const Ts &...Vals) {
1329 return createStringError(llvm::inconvertibleErrorCode(), Fmt, Vals...);
1330}
1331
1332template <typename... Ts>
1333inline Error createStringError(std::errc EC, char const *Fmt,
1334 const Ts &... Vals) {
1335 return createStringError(std::make_error_code(EC), Fmt, Vals...);
1336}
1337
1338/// This class wraps a filename and another Error.
1339///
1340/// In some cases, an error needs to live along a 'source' name, in order to
1341/// show more detailed information to the user.
1342class LLVM_ABI FileError final : public ErrorInfo<FileError> {
1343
1344 friend Error createFileError(const Twine &, Error);
1345 friend Error createFileError(const Twine &, size_t, Error);
1346
1347public:
1348 void log(raw_ostream &OS) const override {
1349 assert(Err && "Trying to log after takeError().");
1350 OS << "'" << FileName << "': ";
1351 if (Line)
1352 OS << "line " << *Line << ": ";
1353 Err->log(OS);
1354 }
1355
1356 std::string messageWithoutFileInfo() const {
1357 std::string Msg;
1359 Err->log(OS);
1360 return Msg;
1361 }
1362
1363 StringRef getFileName() const { return FileName; }
1364
1365 Error takeError() { return Error(std::move(Err)); }
1366
1367 std::error_code convertToErrorCode() const override;
1368
1369 // Used by ErrorInfo::classID.
1370 static char ID;
1371
1372private:
1373 FileError(const Twine &F, std::optional<size_t> LineNum,
1374 std::unique_ptr<ErrorInfoBase> E) {
1375 assert(E && "Cannot create FileError from Error success value.");
1376 FileName = F.str();
1377 Err = std::move(E);
1378 Line = std::move(LineNum);
1379 }
1380
1381 static Error build(const Twine &F, std::optional<size_t> Line, Error E) {
1382 std::unique_ptr<ErrorInfoBase> Payload;
1383 handleAllErrors(std::move(E),
1384 [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1385 Payload = std::move(EIB);
1386 return Error::success();
1387 });
1388 return Error(
1389 std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1390 }
1391
1392 std::string FileName;
1393 std::optional<size_t> Line;
1394 std::unique_ptr<ErrorInfoBase> Err;
1395};
1396
1397/// Concatenate a source file path and/or name with an Error. The resulting
1398/// Error is unchecked.
1400 return FileError::build(F, std::optional<size_t>(), std::move(E));
1401}
1402
1403/// Concatenate a source file path and/or name with line number and an Error.
1404/// The resulting Error is unchecked.
1405inline Error createFileError(const Twine &F, size_t Line, Error E) {
1406 return FileError::build(F, std::optional<size_t>(Line), std::move(E));
1407}
1408
1409/// Concatenate a source file path and/or name with a std::error_code
1410/// to form an Error object.
1411inline Error createFileError(const Twine &F, std::error_code EC) {
1412 return createFileError(F, errorCodeToError(EC));
1413}
1414
1415/// Concatenate a source file path and/or name with line number and
1416/// std::error_code to form an Error object.
1417inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1418 return createFileError(F, Line, errorCodeToError(EC));
1419}
1420
1421/// Create a StringError with the specified error code and prepend the file path
1422/// to it.
1423inline Error createFileError(const Twine &F, std::error_code EC,
1424 const Twine &S) {
1425 Error E = createStringError(EC, S);
1426 return createFileError(F, std::move(E));
1427}
1428
1429/// Create a StringError with the specified error code and prepend the file path
1430/// to it.
1431template <typename... Ts>
1432inline Error createFileError(const Twine &F, std::error_code EC,
1433 char const *Fmt, const Ts &...Vals) {
1434 Error E = createStringError(EC, Fmt, Vals...);
1435 return createFileError(F, std::move(E));
1436}
1437
1439
1440/// Helper for check-and-exit error handling.
1441///
1442/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1443///
1445public:
1446 /// Create an error on exit helper.
1447 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1448 : Banner(std::move(Banner)),
1449 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1450
1451 /// Set the banner string for any errors caught by operator().
1452 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1453
1454 /// Set the exit-code mapper function.
1455 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1456 this->GetExitCode = std::move(GetExitCode);
1457 }
1458
1459 /// Check Err. If it's in a failure state log the error(s) and exit.
1460 void operator()(Error Err) const { checkError(std::move(Err)); }
1461
1462 /// Check E. If it's in a success state then return the contained value. If
1463 /// it's in a failure state log the error(s) and exit.
1464 template <typename T> T operator()(Expected<T> &&E) const {
1465 checkError(E.takeError());
1466 return std::move(*E);
1467 }
1468
1469 /// Check E. If it's in a success state then return the contained reference. If
1470 /// it's in a failure state log the error(s) and exit.
1471 template <typename T> T& operator()(Expected<T&> &&E) const {
1472 checkError(E.takeError());
1473 return *E;
1474 }
1475
1476private:
1477 void checkError(Error Err) const {
1478 if (Err) {
1479 int ExitCode = GetExitCode(Err);
1480 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1481 exit(ExitCode);
1482 }
1483 }
1484
1485 std::string Banner;
1486 std::function<int(const Error &)> GetExitCode;
1487};
1488
1489/// Conversion from Error to LLVMErrorRef for C error bindings.
1491 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1492}
1493
1494/// Conversion from LLVMErrorRef to Error for C error bindings.
1495inline Error unwrap(LLVMErrorRef ErrRef) {
1496 return Error(std::unique_ptr<ErrorInfoBase>(
1497 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1498}
1499
1500} // end namespace llvm
1501
1502#endif // LLVM_SUPPORT_ERROR_H
@ Unchecked
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:336
#define LLVM_ABI
Definition: Compiler.h:213
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
Definition: Compiler.h:346
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1328
Provides ErrorOr<T> smart pointer.
static LLVMTargetMachineRef wrap(const TargetMachine *P)
#define F(x, y, z)
Definition: MD5.cpp:55
#define H(x, y, z)
Definition: MD5.cpp:57
static const char * getPtr(const MachOObjectFile &O, size_t Offset, size_t MachOFilesetEntryOffset=0)
#define T
#define T1
#define P(N)
if(PassOpts->AAPipeline)
raw_pwrite_stream & OS
This class wraps a std::error_code in a Error.
Definition: Error.h:1193
ECError()=default
std::error_code EC
Definition: Error.h:1210
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: Error.h:1200
ECError(std::error_code EC)
Definition: Error.h:1208
void setErrorCode(std::error_code EC)
Definition: Error.h:1199
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Error.h:1201
static char ID
Definition: Error.h:1204
Helper for Errors used as out-parameters.
Definition: Error.h:1144
ErrorAsOutParameter(Error *Err)
Definition: Error.h:1147
ErrorAsOutParameter(Error &Err)
Definition: Error.h:1153
static bool appliesTo(const ErrorInfoBase &E)
Definition: Error.h:855
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Definition: Error.h:860
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Definition: Error.h:890
static bool appliesTo(const ErrorInfoBase &E)
Definition: Error.h:885
static bool appliesTo(const ErrorInfoBase &E)
Definition: Error.h:869
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Definition: Error.h:874
static bool appliesTo(const ErrorInfoBase &E)
Definition: Error.h:901
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Definition: Error.h:906
Helper for testing applicability of, and applying, handlers for ErrorInfo types.
Definition: Error.h:850
Base class for error info classes.
Definition: Error.h:44
virtual ~ErrorInfoBase()=default
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:52
static const void * classID()
Definition: Error.h:66
bool isA() const
Definition: Error.h:78
virtual const void * dynamicClassID() const =0
virtual bool isA(const void *const ClassID) const
Definition: Error.h:73
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
Base class for user error types.
Definition: Error.h:354
bool isA(const void *const ClassID) const override
Definition: Error.h:362
const void * dynamicClassID() const override
Definition: Error.h:360
static const void * classID()
Definition: Error.h:358
Special ErrorInfo subclass representing a list of ErrorInfos.
Definition: Error.h:369
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Error.h:383
static char ID
Definition: Error.h:394
Represents either an error or a value T.
Definition: ErrorOr.h:56
Subclass of Error for the sole purpose of identifying the success path in the type system.
Definition: Error.h:334
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
Error(Error &&Other)
Move-construct an error value.
Definition: Error.h:196
~Error()
Destroy a Error.
Definition: Error.h:232
const void * dynamicClassID() const
Returns the dynamic class id of this error, or null if this is a success value.
Definition: Error.h:252
friend raw_ostream & operator<<(raw_ostream &OS, const Error &E)
Definition: Error.h:320
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
Error(std::unique_ptr< ErrorInfoBase > Payload)
Create an error value.
Definition: Error.h:203
Error & operator=(const Error &Other)=delete
Error()
Create a success value. Prefer using 'Error::success()' for readability.
Definition: Error.h:181
Error(const Error &Other)=delete
Error & operator=(Error &&Other)
Move-assign an error value.
Definition: Error.h:215
bool isA() const
Check whether one error is a subclass of another.
Definition: Error.h:246
Helper for check-and-exit error handling.
Definition: Error.h:1444
void setBanner(std::string Banner)
Set the banner string for any errors caught by operator().
Definition: Error.h:1452
ExitOnError(std::string Banner="", int DefaultErrorExitCode=1)
Create an error on exit helper.
Definition: Error.h:1447
T operator()(Expected< T > &&E) const
Check E.
Definition: Error.h:1464
T & operator()(Expected< T & > &&E) const
Check E.
Definition: Error.h:1471
void operator()(Error Err) const
Check Err. If it's in a failure state log the error(s) and exit.
Definition: Error.h:1460
void setExitCodeMapper(std::function< int(const Error &)> GetExitCode)
Set the exit-code mapper function.
Definition: Error.h:1455
Helper for Expected<T>s used as out-parameters.
Definition: Error.h:1171
ExpectedAsOutParameter(Expected< T > *ValOrErr)
Definition: Error.h:1173
Tagged union holding either a T or a Error.
Definition: Error.h:485
const_reference operator*() const
Returns a const reference to the stored T value.
Definition: Error.h:638
Expected(Expected< OtherT > &&Other, std::enable_if_t<!std::is_convertible_v< OtherT, T > > *=nullptr)
Move construct an Expected<T> value from an Expected<OtherT>, where OtherT isn't convertible to T.
Definition: Error.h:552
Error moveInto(OtherT &Value, std::enable_if_t< std::is_assignable_v< OtherT &, T && > > *=nullptr) &&
Returns takeError() after moving the held T (if any) into V.
Definition: Error.h:595
pointer operator->()
Returns a pointer to the stored T value.
Definition: Error.h:620
reference operator*()
Returns a reference to the stored T value.
Definition: Error.h:632
Expected(OtherT &&Val, std::enable_if_t< std::is_convertible_v< OtherT, T > > *=nullptr)
Create an Expected<T> success value from the given OtherT value, which must be convertible to T.
Definition: Error.h:526
~Expected()
Destroy an Expected<T>.
Definition: Error.h:565
const_reference get() const
Returns a const reference to the stored T value.
Definition: Error.h:588
bool errorIsA() const
Check that this Expected<T> is an error of type ErrT.
Definition: Error.h:604
Expected(ErrorSuccess)=delete
Forbid to convert from Error::success() implicitly, this avoids having Expected<T> foo() { return Err...
Expected(Error &&Err)
Create an Expected<T> error value from the given Error.
Definition: Error.h:507
Error takeError()
Take ownership of the stored error.
Definition: Error.h:612
const_pointer operator->() const
Returns a const pointer to the stored T value.
Definition: Error.h:626
Expected & operator=(Expected &&Other)
Move-assign from another Expected<T>.
Definition: Error.h:559
reference get()
Returns a reference to the stored T value.
Definition: Error.h:582
storage_type TStorage
Definition: Error.h:735
std::conditional_t< isRef, wrap, T > storage_type
Definition: Error.h:496
error_type ErrorStorage
Definition: Error.h:736
Expected(Expected &&Other)
Move construct an Expected<T> value.
Definition: Error.h:539
Expected(Expected< OtherT > &&Other, std::enable_if_t< std::is_convertible_v< OtherT, T > > *=nullptr)
Move construct an Expected<T> value from an Expected<OtherT>, where OtherT must be convertible to T.
Definition: Error.h:544
This class wraps a filename and another Error.
Definition: Error.h:1342
Error takeError()
Definition: Error.h:1365
static char ID
Definition: Error.h:1370
std::string messageWithoutFileInfo() const
Definition: Error.h:1356
StringRef getFileName() const
Definition: Error.h:1363
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: Error.h:1348
This class wraps a string in an Error.
Definition: Error.h:1282
const std::string & getMessage() const
Definition: Error.h:1295
static char ID
Definition: Error.h:1284
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
LLVM Value Representation.
Definition: Value.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
struct LLVMOpaqueError * LLVMErrorRef
Opaque reference to an error instance.
Definition: Error.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition: Error.h:1113
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:65
void visitErrors(const Error &E, HandlerT H)
Visit all the ErrorInfo(s) contained in E by passing them to the respective handler,...
Definition: Error.h:1002
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition: Error.h:1399
std::optional< T > expectedToStdOptional(Expected< T > &&E)
Definition: Error.h:1101
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:990
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition: Error.h:967
ErrorOr< T > expectedToErrorOr(Expected< T > &&E)
Convert an Expected<T> to an ErrorOr<T>.
Definition: Error.h:1252
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1305
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition: Error.cpp:177
std::optional< T > expectedToOptional(Expected< T > &&E)
Convert an Expected to an Optional without doing anything.
Definition: Error.h:1094
LLVM_ABI std::string toStringWithoutConsuming(const Error &E)
Like toString(), but does not consume the error.
Definition: Error.cpp:85
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:442
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
Expected< T > handleExpected(Expected< T > ValOrErr, RecoveryFtor &&RecoveryPath, HandlerTs &&... Handlers)
Handle any errors (if present) in an Expected<T>, then try a recovery path.
Definition: Error.h:1042
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:126
Error handleErrorImpl(std::unique_ptr< ErrorInfoBase > Payload)
Definition: Error.h:946
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition: Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:769
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:351
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition: Error.h:1245
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:346
const char * toString(DWARFSectionKind Kind)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition: Error.h:1240
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:55
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:117
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1083
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition: Error.cpp:180
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856