13 #ifndef LLVM_SUPPORT_ERROR_H 14 #define LLVM_SUPPORT_ERROR_H 21 #include "llvm/Config/abi-breaking.h" 37 #include <system_error> 38 #include <type_traits> 70 static const void *
classID() {
return &ID; }
77 virtual bool isA(
const void *
const ClassID)
const {
82 template <
typename ErrorInfoT>
bool isA()
const {
83 return isA(ErrorInfoT::classID());
87 virtual void anchor();
164 template <
typename... HandlerTs>
193 *
this = std::move(Other);
198 Error(std::unique_ptr<ErrorInfoBase> Payload) {
199 setPtr(Payload.release());
204 Error &operator=(
const Error &Other) =
delete;
213 setPtr(Other.getPtr());
219 Other.setPtr(
nullptr);
220 Other.setChecked(
true);
236 setChecked(
getPtr() ==
nullptr);
237 return getPtr() !=
nullptr;
241 template <
typename ErrT>
bool isA()
const {
250 return getPtr()->dynamicClassID();
254 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 261 void fatalUncheckedError()
const;
264 void assertIsChecked() {
265 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 267 fatalUncheckedError();
273 reinterpret_cast<uintptr_t
>(Payload) &
274 ~static_cast<uintptr_t>(0x1));
278 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 280 (
reinterpret_cast<uintptr_t
>(EI) &
281 ~static_cast<uintptr_t>(0x1)) |
282 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
288 bool getChecked()
const {
289 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 290 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
296 void setChecked(
bool V) {
298 (
reinterpret_cast<uintptr_t
>(Payload) &
299 ~static_cast<uintptr_t>(0x1)) |
303 std::unique_ptr<ErrorInfoBase> takePayload() {
304 std::unique_ptr<ErrorInfoBase> Tmp(
getPtr());
311 if (
auto P = E.getPtr())
331 return Error(std::make_unique<ErrT>(std::forward<ArgTs>(
Args)...));
343 template <
typename ThisErrT,
typename ParentErrT = ErrorInfoBase>
346 using ParentErrT::ParentErrT;
352 bool isA(
const void *
const ClassID)
const override {
353 return ClassID ==
classID() || ParentErrT::isA(ClassID);
362 template <
typename... HandlerTs>
370 OS <<
"Multiple errors:\n";
371 for (
auto &ErrPayload : Payloads) {
383 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
384 std::unique_ptr<ErrorInfoBase> Payload2) {
386 "ErrorList constructor payloads should be singleton errors");
387 Payloads.push_back(std::move(Payload1));
388 Payloads.push_back(std::move(Payload2));
397 auto &E1List =
static_cast<ErrorList &
>(*E1.getPtr());
399 auto E2Payload = E2.takePayload();
400 auto &E2List =
static_cast<ErrorList &
>(*E2Payload);
401 for (
auto &Payload : E2List.Payloads)
402 E1List.Payloads.push_back(std::move(Payload));
404 E1List.Payloads.push_back(E2.takePayload());
409 auto &E2List =
static_cast<ErrorList &
>(*E2.getPtr());
410 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
413 return Error(std::unique_ptr<ErrorList>(
414 new ErrorList(E1.takePayload(), E2.takePayload())));
417 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
424 return ErrorList::join(std::move(E1), std::move(E2));
435 template <
class OtherT>
friend class Expected;
437 static const bool isRef = std::is_reference<T>::value;
439 using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
441 using error_type = std::unique_ptr<ErrorInfoBase>;
448 using reference =
typename std::remove_reference<T>::type &;
449 using const_reference =
const typename std::remove_reference<T>::type &;
450 using pointer =
typename std::remove_reference<T>::type *;
451 using const_pointer =
const typename std::remove_reference<T>::type *;
457 #
if LLVM_ENABLE_ABI_BREAKING_CHECKS
462 assert(Err &&
"Cannot create Expected<T> from Error success value.");
463 new (getErrorStorage()) error_type(Err.takePayload());
473 template <
typename OtherT>
475 typename std::enable_if<std::is_convertible<OtherT, T>::value>::
type 478 #
if LLVM_ENABLE_ABI_BREAKING_CHECKS
483 new (getStorage())
storage_type(std::forward<OtherT>(Val));
491 template <
class OtherT>
493 typename std::enable_if<std::is_convertible<OtherT, T>::value>::
type 495 moveConstruct(std::move(
Other));
500 template <
class OtherT>
503 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::
type * =
505 moveConstruct(std::move(
Other));
510 moveAssign(std::move(
Other));
518 getStorage()->~storage_type();
520 getErrorStorage()->~error_type();
525 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 526 Unchecked = HasError;
534 return *getStorage();
538 const_reference
get()
const {
545 return HasError && (*getErrorStorage())->
template isA<ErrT>();
553 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 562 return toPointer(getStorage());
568 return toPointer(getStorage());
574 return *getStorage();
580 return *getStorage();
585 static bool compareThisIfSameType(
const T1 &a,
const T1 &b) {
589 template <
class T1,
class T2>
590 static bool compareThisIfSameType(
const T1 &a,
const T2 &b) {
595 HasError =
Other.HasError;
596 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 598 Other.Unchecked =
false;
604 new (getErrorStorage()) error_type(std::move(*
Other.getErrorStorage()));
610 if (compareThisIfSameType(*
this,
Other))
614 new (
this) Expected(std::move(
Other));
617 pointer toPointer(pointer Val) {
return Val; }
619 const_pointer toPointer(const_pointer Val)
const {
return Val; }
621 pointer toPointer(wrap *Val) {
return &Val->get(); }
623 const_pointer toPointer(
const wrap *Val)
const {
return &Val->get(); }
626 assert(!HasError &&
"Cannot get value when an error exists!");
627 return reinterpret_cast<storage_type *
>(TStorage.buffer);
631 assert(!HasError &&
"Cannot get value when an error exists!");
632 return reinterpret_cast<const storage_type *
>(TStorage.buffer);
635 error_type *getErrorStorage() {
636 assert(HasError &&
"Cannot get error when a value exists!");
637 return reinterpret_cast<error_type *
>(ErrorStorage.buffer);
640 const error_type *getErrorStorage()
const {
641 assert(HasError &&
"Cannot get error when a value exists!");
642 return reinterpret_cast<const error_type *
>(ErrorStorage.buffer);
646 void setUnchecked() {
647 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 652 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 655 void fatalUncheckedExpected()
const {
656 dbgs() <<
"Expected<T> must be checked before access or destruction.\n";
658 dbgs() <<
"Unchecked Expected<T> contained error:\n";
659 (*getErrorStorage())->
log(
dbgs());
661 dbgs() <<
"Expected<T> value was in success state. (Note: Expected<T> " 662 "values in success mode must still be checked prior to being " 668 void assertIsChecked() {
669 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 671 fatalUncheckedExpected();
680 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 688 bool gen_crash_diag =
true);
706 Msg =
"Failure value returned from cantFail wrapped call";
710 OS << Msg <<
"\n" << Err;
711 Msg = OS.
str().c_str();
730 template <
typename T>
733 return std::move(*ValOrErr);
736 Msg =
"Failure value returned from cantFail wrapped call";
741 OS << Msg <<
"\n" <<
E;
742 Msg = OS.
str().c_str();
761 template <
typename T>
767 Msg =
"Failure value returned from cantFail wrapped call";
772 OS << Msg <<
"\n" <<
E;
773 Msg = OS.
str().c_str();
781 template <
typename HandlerT>
784 &std::remove_reference<HandlerT>::type::operator())> {};
790 return E.template isA<ErrT>();
793 template <
typename HandlerT>
795 assert(appliesTo(*E) &&
"Applying incorrect handler");
796 return H(static_cast<ErrT &>(*E));
804 return E.template isA<ErrT>();
807 template <
typename HandlerT>
809 assert(appliesTo(*E) &&
"Applying incorrect handler");
810 H(static_cast<ErrT &>(*E));
816 template <
typename ErrT>
820 return E.template isA<ErrT>();
823 template <
typename HandlerT>
825 assert(appliesTo(*E) &&
"Applying incorrect handler");
826 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
827 return H(std::move(SubE));
832 template <
typename ErrT>
836 return E.template isA<ErrT>();
839 template <
typename HandlerT>
841 assert(appliesTo(*E) &&
"Applying incorrect handler");
842 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
849 template <
typename C,
typename RetT,
typename ErrT>
854 template <
typename C,
typename RetT,
typename ErrT>
859 template <
typename C,
typename RetT,
typename ErrT>
864 template <
typename C,
typename RetT,
typename ErrT>
870 template <
typename C,
typename RetT,
typename ErrT>
876 template <
typename C,
typename RetT,
typename ErrT>
881 return Error(std::move(Payload));
884 template <
typename HandlerT,
typename... HandlerTs>
886 HandlerT &&Handler, HandlerTs &&... Handlers) {
891 std::forward<HandlerTs>(Handlers)...);
900 template <
typename... HandlerTs>
905 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
910 for (
auto &
P : List.Payloads)
917 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
923 template <
typename... HandlerTs>
958 template <
typename T,
typename RecoveryFtor,
typename... HandlerTs>
960 HandlerTs &&... Handlers) {
965 std::forward<HandlerTs>(Handlers)...))
966 return std::move(Err);
968 return RecoveryPath();
1014 return std::move(*E);
1025 bool IsError =
static_cast<bool>(Err);
1076 template <
typename T>
1080 : ValOrErr(ValOrErr) {
1087 ValOrErr->setUnchecked();
1102 virtual void anchor()
override;
1138 if (
auto EC = EO.getError())
1140 return std::move(*EO);
1145 if (
auto Err = E.takeError())
1147 return std::move(*E);
1192 const bool PrintMsgOnly =
false;
1196 template <
typename... Ts>
1198 const Ts &... Vals) {
1201 Stream <<
format(Fmt, Vals...);
1202 return make_error<StringError>(Stream.
str(), EC);
1211 template <
typename... Ts>
1213 const Ts &... Vals) {
1228 assert(Err && !FileName.empty() &&
"Trying to log after takeError().");
1229 OS <<
"'" << FileName <<
"': ";
1230 if (Line.hasValue())
1231 OS <<
"line " << Line.getValue() <<
": ";
1246 std::unique_ptr<ErrorInfoBase> E) {
1247 assert(E &&
"Cannot create FileError from Error success value.");
1249 "The file name provided to FileError must not be empty.");
1252 Line = std::move(LineNum);
1256 std::unique_ptr<ErrorInfoBase> Payload;
1258 [&](std::unique_ptr<ErrorInfoBase> EIB) ->
Error {
1259 Payload = std::move(EIB);
1263 std::unique_ptr<FileError>(
new FileError(F, Line, std::move(Payload))));
1266 std::string FileName;
1268 std::unique_ptr<ErrorInfoBase> Err;
1305 : Banner(
std::move(Banner)),
1306 GetExitCode([=](
const Error &) {
return DefaultErrorExitCode; }) {}
1309 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1313 this->GetExitCode = std::move(GetExitCode);
1322 checkError(E.takeError());
1323 return std::move(*E);
1329 checkError(E.takeError());
1334 void checkError(
Error Err)
const {
1336 int ExitCode = GetExitCode(Err);
1343 std::function<int(const Error &)> GetExitCode;
1348 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1353 return Error(std::unique_ptr<ErrorInfoBase>(
1354 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1359 #endif // LLVM_SUPPORT_ERROR_H reference operator*()
Returns a reference to the stored T value.
static const void * classID()
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
bool errorIsA() const
Check that this Expected<T> is an error of type ErrT.
Represents either an error or a value T.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
const void * dynamicClassID() const
Returns the dynamic class id of this error, or null if this is a success value.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
#define LLVM_UNLIKELY(EXPR)
Subclass of Error for the sole purpose of identifying the success path in the type system...
void push_back(const T &Elt)
AlignedCharArrayUnion< storage_type > TStorage
std::error_code make_error_code(object_error e)
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Helper for check-and-exit error handling.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
static const char * getPtr(const MachOObjectFile &O, size_t Offset)
T & operator()(Expected< T &> &&E) const
Check E.
static bool appliesTo(const ErrorInfoBase &E)
Helper for Expected<T>s used as out-parameters.
virtual std::string message() const
Return the error message as a string.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
ErrorOr< T > expectedToErrorOr(Expected< T > &&E)
Convert an Expected<T> to an ErrorOr<T>.
pointer operator->()
Returns a pointer to the stored T value.
block Block Frequency true
Error takeError()
Take ownership of the stored error.
Expected< T > handleExpected(Expected< T > ValOrErr, RecoveryFtor &&RecoveryPath, HandlerTs &&... Handlers)
Handle any errors (if present) in an Expected<T>, then try a recovery path.
Base class for error info classes.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Expected(Expected< OtherT > &&Other, typename std::enable_if<!std::is_convertible< OtherT, T >::value >::type *=nullptr)
Move construct an Expected<T> value from an Expected<OtherT>, where OtherT isn't convertible to T...
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
This class wraps a filename and another Error.
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Attribute unwrap(LLVMAttributeRef Attr)
Expected(Expected &&Other)
Move construct an Expected<T> value.
Expected(Expected< OtherT > &&Other, typename std::enable_if< std::is_convertible< OtherT, T >::value >::type *=nullptr)
Move construct an Expected<T> value from an Expected<OtherT>, where OtherT must be convertible to T...
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
~Expected()
Destroy an Expected<T>.
Tagged union holding either a T or a Error.
virtual ~ErrorInfoBase()=default
const_reference operator*() const
Returns a const reference to the stored T value.
const void * dynamicClassID() const override
Error & operator=(Error &&Other)
Move-assign an error value.
ErrorAsOutParameter(Error *Err)
virtual const void * dynamicClassID() const =0
struct LLVMOpaqueError * LLVMErrorRef
Opaque reference to an error instance.
Error build(ArrayRef< Module *> Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
ECError(std::error_code EC)
void setExitCodeMapper(std::function< int(const Error &)> GetExitCode)
Set the exit-code mapper function.
const_pointer operator->() const
Returns a const pointer to the stored T value.
Expected(Error Err)
Create an Expected<T> error value from the given Error.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void operator()(Error Err) const
Check Err. If it's in a failure state log the error(s) and exit.
AlignedCharArrayUnion< error_type > ErrorStorage
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
ExitOnError(std::string Banner="", int DefaultErrorExitCode=1)
Create an error on exit helper.
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
void consumeError(Error Err)
Consume a Error without doing anything.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
const std::string & getMessage() const
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Special ErrorInfo subclass representing a list of ErrorInfos.
static const void * classID()
Error(std::unique_ptr< ErrorInfoBase > Payload)
Create an error value.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
static ErrorSuccess success()
Create a success value.
static bool appliesTo(const ErrorInfoBase &E)
friend raw_ostream & operator<<(raw_ostream &OS, const Error &E)
Expected(OtherT &&Val, typename std::enable_if< std::is_convertible< OtherT, T >::value >::type *=nullptr)
Create an Expected<T> success value from the given OtherT value, which must be convertible to T...
static bool appliesTo(const ErrorInfoBase &E)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
#define LLVM_ATTRIBUTE_NORETURN
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
T operator()(Expected< T > &&E) const
Check E.
Expected & operator=(Expected &&Other)
Move-assign from another Expected<T>.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void setBanner(std::string Banner)
Set the banner string for any errors caught by operator().
Base class for user error types.
Helper for Errors used as out-parameters.
Optional< T > expectedToOptional(Expected< T > &&E)
Convert an Expected to an Optional without doing anything.
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Error handleErrorImpl(std::unique_ptr< ErrorInfoBase > Payload)
Error(Error &&Other)
Move-construct an error value.
LLVMAttributeRef wrap(Attribute Attr)
This class wraps a string in an Error.
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Error joinErrors(Error E1, Error E2)
Concatenate errors.
bool isA(const void *const ClassID) const override
bool isA() const
Check whether one error is a subclass of another.
void setErrorCode(std::error_code EC)
typename std::conditional< isRef, wrap, T >::type storage_type
std::string str() const
Return the twine contents as a std::string.
ExpectedAsOutParameter(Expected< T > *ValOrErr)
#define LLVM_NODISCARD
LLVM_NODISCARD - Warn if a type or return value is discarded.
static Error apply(HandlerT &&H, std::unique_ptr< ErrorInfoBase > E)
Provides ErrorOr<T> smart pointer.
Error()
Create a success value. Prefer using 'Error::success()' for readability.
static bool appliesTo(const ErrorInfoBase &E)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Lightweight error class with error context and mandatory checking.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
This class wraps a std::error_code in a Error.
This class implements an extremely fast bulk output stream that can only output to a stream...
Helper for testing applicability of, and applying, handlers for ErrorInfo types.
print Print MemDeps of function
StringRef - Represent a constant reference to a string, i.e.
~ExpectedAsOutParameter()
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
virtual bool isA(const void *const ClassID) const
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...