llvm::Error

Lightweight error class with error context and mandatory checking.

Synopsis

Declared in <llvm/Support/Error.h>

class [[nodiscard]] Error;

Description

Instances of this class wrap a ErrorInfoBase pointer. Failure states are represented by setting the pointer to a ErrorInfoBase subclass instance containing information describing the failure. Success is represented by a null pointer value.

Instances of Error also contains a 'Checked' flag, which must be set before the destructor is called, otherwise the destructor will trigger a runtime error. This enforces at runtime the requirement that all Error instances be checked or returned to the caller.

There are two ways to set the checked flag, depending on what state the Error instance is in. For Error instances indicating success, it is sufficient to invoke the boolean conversion operator. E.g.:


Error foo(<...>);

if (auto E = foo(<...>))
  return E; // <- Return E if it is in the error state.
// We have verified that E was in the success state. It can now be safely
// destroyed.

A success value can not be dropped. For example, just calling 'foo(<...>)' without testing the return value will raise a runtime error, even if foo returns success.

For Error instances representing failure, you must use either the handleErrors or handleAllErrors function with a typed handler. E.g.:


class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
  // Custom error info.
};

Error foo(<...>) { return make_error<MyErrorInfo>(...); }

auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
auto NewE =
  handleErrors(std::move(E),
    [](const MyErrorInfo &M) {
      // Deal with the error.
    },
    [](std::unique_ptr<OtherError> M) -> Error {
      if (canHandle(*M)) {
        // handle error.
        return Error::success();
      }
      // Couldn't handle this error instance. Pass it up the stack.
      return Error(std::move(M));
  });
// Note - The error passed to handleErrors will be marked as checked. If
// there is no matched handler, a new error with the same payload is
// created and returned.
// The handlers take the error checked by handleErrors as an argument,
// which can be used to retrieve more information. If a new error is
// created by a handler, it will be passed back to the caller of
// handleErrors and needs to be checked or return up to the stack.
// Otherwise, the passed-in error is considered consumed.

The handleAllErrors function is identical to handleErrors, except that it has a void return type, and requires all errors to be handled and no new errors be returned. It prevents errors (assuming they can all be handled) from having to be bubbled all the way to the top-level.

All Error instances must be checked before destruction, even if they're moved-assigned or constructed from Success values that have already been checked. This enforces checking through all levels of the call stack.

Member Functions

NameDescription
Error [constructor]Constructors
~Error [destructor]Destroy a Error. Fails with a call to abort() if the error is unchecked.
operator= Assignment operators
dynamicClassID Returns the dynamic class id of this error, or null if this is a success value.
isA Check whether one error is a subclass of another.
operator bool Return true if this Error holds a failure value.

Static Member Functions

NameDescription
success Create a success value.

Protected Member Functions

NameDescription
Error [constructor]Create a success value. Prefer using 'Error::success()' for readability

Friends

NameDescription
llvm::operator<<Write a textual representation of error E to stream OS.
llvm::wrapConversion from Error to LLVMErrorRef for C error bindings.
llvm::ExpectedTagged union holding either a T or a Error.
llvm::visitErrorsVisit all the ErrorInfo(s) contained in E by passing them to the respective handler, without consuming the error.
llvm::handleErrorsPass ErrorInfo payloads in E to matching handlers among Handlers.
llvm::ErrorListSpecial ErrorInfo subclass representing a list of ErrorInfos. Instances of this class are constructed by joinError.

Non-Member Functions

NameDescription
EmitImportsFilesEmit into OutputFilename the files module ModulePath will import from.
cantFailReport a fatal error if Err is a failure value.
collectGlobalObjectNameStringsSerialize global-object name strings into a profile-ready blob.
collectPGOFuncNameStringsSerialize referenced PGO function-name variables into Result.
collectVTableStringsSerialize vtable name strings into a profile-ready blob.
consumeErrorConsume a Error without doing anything. This method should be used only where an error can be considered a reasonable and expected return value.
createCtxProfFromYAMLConvert a YAML contextual profile in Profile into bitstream form on Out.
createFileErrorCreate a StringError with the specified error code and prepend the file path to it.
createFileErrorConcatenate a source file path and/or name with line number and std::error_code to form an Error object.
createFileErrorDeleted overload: a successful Error cannot be wrapped as a FileError.
createFileErrorConcatenate a source file path and/or name with a std::error_code to form an Error object.
createFileErrorCreate a StringError with the specified error code and prepend the file path to it.
createFileErrorConcatenate a source file path and/or name with an Error. The resulting Error is unchecked.
createFileErrorConcatenate a source file path and/or name with line number and an Error. The resulting Error is unchecked.
createStringErrorCreate a StringError from error code EC and message Msg.
createStringErrorCreate a StringError with an inconvertible error code and printf-style Fmt.
createStringErrorCreate a StringError from std::errc EC and printf-style Fmt.
createStringErrorCreate a StringError from error code EC and Twine message S.
createStringErrorCreate a StringError with an inconvertible error code.
createStringErrorCreate a StringError from error code EC and message S.
createStringErrorCreate formatted StringError object.
createStringErrorVCreate a StringError from error code EC and formatv-style Fmt.
createStringErrorVCreate a StringError with an inconvertible error code and formatv-style Fmt.
decodeBase64Decode a Base64 string into raw bytes.
errorCodeToErrorHelper for converting an std::error_code to a Error.
errorToBoolHelper for converting an Error to a bool.
errorToErrorCodeHelper for converting an ECError to a std::error_code.
fmt_consumeWrap an Error so formatv takes ownership and consumes it.
handleAllErrorsLike handleErrors, but requires every error to be handled.
handleAllErrorsCheck that E is a non-error, then drop it. If E is an error, llvm_unreachable will be called.
handleErrorImplReturn an Error wrapping unhandled Payload.
handleErrorImplDispatch Payload to the first matching handler among Handler and Handlers.
joinErrorsConcatenate errors from E1 followed by those from E2.
logAllUnhandledErrorsLog all errors in E to OS, optionally prefixed by ErrorBanner.
make_errorMake a Error instance representing failure using the given error info type.
parallelForEachErrorApply Fn to each element of R in parallel and join any returned Errors.
readAndDecodeStringsDecode concatenated PGO name strings and invoke a callback for each name.
readModuleSummaryIndexParse the specified bitcode buffer and merge the index into CombinedIndex.
reportFatalInternalErrorReport a fatal error that indicates a bug in LLVM. See ErrorHandling.h for details.
reportFatalUsageErrorReport a fatal error that does not indicate a bug in LLVM. See ErrorHandling.h for details.
report_fatal_errorReport a fatal error from an Error value.
setupLLVMOptimizationRemarksSet up optimization remarks that output directly to a raw_ostream.
splitModuleTransitiveFromEntryPointsSplits a module into parts by transitive reachability from entry points.
timeTraceProfilerWriteWrite profiling data to a file.
toStringWrite all error messages (if any) in E to a string. The newline character is used to separate error messages.
toStringWithoutConsumingLike toString(), but does not consume the error. This can be used to print a warning while retaining the original error object.
unwrapConversion from LLVMErrorRef to Error for C error bindings.
warnToStderrLog Err to stderr as a warning.
writeMerge split DWARF inputs into Out, optionally writing the package.
writeArchiveWrite an archive to the file named ArcName.
writeArchiveToStreamWrite an archive directly to an output stream.
writeMemProfWrite MemProf profile data to OS in the requested indexed format version.
writeToOutputCreate an output stream for OutputFileName and pass it to Write.
DWARFYAML::emitDebugAbbrevEmit the .debug_abbrev section described by DI to OS.
DWARFYAML::emitDebugAddrEmit the .debug_addr section described by DI to OS.
DWARFYAML::emitDebugArangesEmit the .debug_aranges section described by DI to OS.
DWARFYAML::emitDebugGNUPubnamesEmit the .debug_gnu_pubnames section described by DI to OS.
DWARFYAML::emitDebugGNUPubtypesEmit the .debug_gnu_pubtypes section described by DI to OS.
DWARFYAML::emitDebugInfoEmit the .debug_info section described by DI to OS.
DWARFYAML::emitDebugLineEmit the .debug_line section described by DI to OS.
DWARFYAML::emitDebugLoclistsEmit the .debug_loclists section described by DI to OS.
DWARFYAML::emitDebugNamesEmit the .debug_names section described by DI to OS.
DWARFYAML::emitDebugPubnamesEmit the .debug_pubnames section described by DI to OS.
DWARFYAML::emitDebugPubtypesEmit the .debug_pubtypes section described by DI to OS.
DWARFYAML::emitDebugRangesEmit the .debug_ranges section described by DI to OS.
DWARFYAML::emitDebugRnglistsEmit the .debug_rnglists section described by DI to OS.
DWARFYAML::emitDebugStrEmit the .debug_str section described by DI to OS.
DWARFYAML::emitDebugStrOffsetsEmit the .debug_str_offsets section described by DI to OS.
DWARFYAML::getDWARFEmitterByNameReturn the emitter for the DWARF section named SecName.
RISCV::parseTuneFeatureStringParse the tune feature string with the respective processor. If ProcName is empty, directives are not filtered by processor.
cgdata::warnReport a codegen-data warning derived from error E.
codeview::consumeDecode a numeric leaf value from a string buffer into Num.
codeview::consumeConsume a vector-tail serialization helper from Reader.
codeview::consumeDecode a numeric leaf value from the type stream into Num.
codeview::consumeDecode a null-terminated string.
codeview::consumeDecode an unsigned fixed-length 32-bit integer.
codeview::consumeDecode a signed fixed-length 32-bit integer.
codeview::consumeDecode an unsigned 32-bit integer from a string buffer.
codeview::consumeNo-op consume that always succeeds; base case for variadic consume.
codeview::consumeConsume an arrayref-tail serialization helper from Reader.
codeview::consumeConsume an array serialization helper from Reader.
codeview::consumeConsume a numeric serialization helper from Reader.
codeview::consumeConsume a conditional serialization helper from Reader.
codeview::consumeDecode an object whose layout matches the underlying byte sequence.
codeview::consumeConsume a null-terminated string-array helper from Reader.
codeview::consumeConsume multiple fields from Reader in order.
codeview::consume_numericDecode a numeric leaf value that is known to be a particular type.
codeview::forEachCodeViewRecordInvoke F for each contiguous CodeView record in StreamBuffer.
codeview::mergeIdRecordsMerge one set of id records into another.
codeview::mergeIdRecordsMerge one set of id records into a global id table.
codeview::mergeTypeAndIdRecordsMerge a unified set of type and id records into global tables, splitting them into separate output streams.
codeview::mergeTypeAndIdRecordsMerge a unified set of type and id records, splitting them into separate output streams.
codeview::mergeTypeRecordsMerge one set of type records into another. This method assumes that all records are type records, and there are no Id records present.
codeview::mergeTypeRecordsMerge one set of type records into a global type table.
codeview::visitDebugSubsectionDispatch a single debug subsection record to the appropriate visitor method.
codeview::visitDebugSubsectionsVisit each debug subsection in FragmentRange using the given string table.
codeview::visitDebugSubsectionsVisit each debug subsection in FragmentRange.
codeview::visitDebugSubsectionsVisit each debug subsection in FragmentRange using the given string table and checksums.
codeview::visitMemberRecordVisit a single member record.
codeview::visitMemberRecordVisit a single member record from its leaf kind and raw bytes.
codeview::visitMemberRecordStreamVisit every member record in a field-list byte stream.
codeview::visitTypeRecordVisit a single type record at a known type index.
codeview::visitTypeRecordVisit a single type record without a type index.
codeview::visitTypeStreamVisit every type record in Types in order.
codeview::visitTypeStreamVisit every type record in the range Types.
codeview::visitTypeStreamVisit every type record in the collection Types.
compression::decompressDecompress Input using debug compression type T into Output.
compression::decompressDecompress Input using the debug-info compression format T into Output, which is resized to UncompressedSize bytes.
compression::decompressDecompress Input using compression format F into Output, which is resized to UncompressedSize bytes.
dwarf_linker::finiteLoopCall Iteration until it returns false, or fail if the limit is hit.
ifs::filterIFSSymsFilters symbols from an IFS stub by undefined status and exclude globs.
ifs::overrideIFSTargetOverride the target platform inforation in the text stub.
ifs::validateIFSTargetValidate the target platform inforation in the text stub.
ifs::writeBinaryStubAttempt to write a binary ELF stub.
ifs::writeIFSToOutputStreamAttempts to write an IFS interface file to a raw_ostream.
irsymtab::buildFills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
jitlink::makeAlignmentErrorCreate an alignment error for a fixup at the given location.
jitlink::makeTargetOutOfRangeErrorCreate an out of range error for the given edge in the given block.
jitlink::markAllSymbolsLiveMarks all symbols in a graph live. This can be used as a default, conservative mark-live implementation.
lto::backendRuns a regular LTO backend. The regular LTO backend can also act as the regular LTO phase of ThinLTO, which may need to access the combined index.
lto::finalizeOptimizationRemarksFinalizes and flushes an optimization remarks output file.
lto::thinBackendRuns a ThinLTO backend.
msf::validateSuperBlockValidates that a superblock describes a well-formed MSF file.
objcopy::executeObjcopyOnArchiveApplies the transformations described by Config to each member in archive Ar. Writes a result in a file specified by Config.OutputFilename.
objcopy::executeObjcopyOnBinaryApplies the transformations described by Config to In and writes the result into Out.
object::createErrorCreate a parse_failed StringError with message Err.
object::decodeCrelDecode a CREL relocation blob, invoking handlers for the header and entries.
object::extractCodeObjectExtract code object memory from the given Buffer at Offset and of Size, and copy into OutputFileName.
object::extractCodeObjectExtract code object memory from the given Source object file at Offset and of Size, and copy into OutputFileName.
object::extractOffloadBinariesExtracts embedded device offloading code from a memory Buffer to a list of Binaries.
object::extractOffloadBundleByURIExtracts an Offload Bundle Entry given by URI.
object::extractOffloadBundleFatBinaryExtracts fat binary in binary clang-offload-bundler format from object Obj and return it in Bundles.
object::isNotObjectErrorInvalidFileTypeConsume Err when it is invalid_file_type; otherwise return it.
object::writeImportLibraryWrites a COFF import library containing entries described by the Exports array.
object::writeUniversalBinaryWrite a Mach-O universal binary containing Slices to OutputFileName.
object::writeUniversalBinaryToStreamWrite a Mach-O universal binary containing Slices to Out.
offloading::containerizeImageContainerizes an image within an OffloadBinary image.
offloading::wrapCudaBinaryWraps the input fatbinary image into the module M as global symbols and registers the images with the CUDA runtime.
offloading::wrapHIPBinaryWraps the input bundled image into the module M as global symbols and registers the images with the HIP runtime.
offloading::wrapOpenMPBinariesWraps the input device images into the module M as global symbols and registers the images with the OpenMP Offloading runtime libomptarget.
offloading::wrapSYCLBinariesWraps OffloadBinaries in the given Buffers into the module M as global symbols and registers the images with the SYCL Runtime.
orc::addFunctionPointerRelocationsToCurrentSymbolIntroduce relocations to Sym in its own definition if there are any pointers formed via PC-relative address that do not already have a relocation.
orc::checkMachORelocatableObjectCheck that a buffer contains a MachO object compatible with a triple.
orc::decodeHangupPayloadDecode a Hangup payload produced by encodeHangupPayload.
orc::deregisterEHFrameSectionUnregister frames in the given eh-frame section with libunwind.
orc::enableDebuggerSupportEnable debugger support for the given LLJIT instance.
orc::encodeHangupPayloadEncode an Error as the payload of a Hangup message.
orc::lookupAndApplyBlocking version of lookupAndApply above.
orc::lookupAndApplylookupAndApply with a static lookup in the given JITDylib. Blocking version.
orc::preserveDebugSectionsPreserve DWARF debug sections in G so they are not pruned by JITLink.
orc::registerEHFrameSectionRegister frames in the given eh-frame section with libunwind.
orc::setUpInProcessLCTMReentryViaEPCIUSet up in-process lazy call-through re-entry via the given EPCIU.
orc::setUpOrcPlatformManuallyConfigure the LLJIT instance to use orc runtime support. This overload assumes that the client has manually configured a Platform object.
pdb::iterateModuleSubsectionsVisit each debug subsection of type SubsectionT across filtered modules.
pdb::iterateOneModulePrint a module header for SG and invoke Callback for that module.
pdb::iterateSymbolGroupsVisit each filtered symbol group in Input, invoking Callback.
pdb::loadDataForEXECreate a PDB session by loading debug data for an executable.
pdb::loadDataForPDBCreate a PDB session by loading debug data from a PDB file.
pdb::readSparseBitVectorRead a SparseBitVector from a PDB binary stream.
pdb::writeSparseBitVectorWrite a SparseBitVector to a PDB binary stream.
vfs::convertToOutputErrorReturn Error::success() or use OutputPath to create an OutputError, depending on EC.
vfs::convertToTempFileOutputErrorReturn Error::success() or use TempPath and OutputPath to create a TempFileOutputError, depending on EC.
compression::zlib::decompressDecompress zlib-compressed Input into a caller-provided buffer.
compression::zlib::decompressDecompress zlib-compressed Input into Output.
compression::zstd::decompressDecompress zstd-compressed Input into a caller-provided buffer.
compression::zstd::decompressDecompress zstd-compressed Input into Output.
coverage::accessors::getFuncNameViaRefReturn the PGO name of the function. Used for formats in which the name is a hash.
jitlink::aarch32::applyFixupApply fixup expression for edge to block content.
jitlink::aarch32::applyFixupArmHelper function to apply the fixup for Arm-class relocations.
jitlink::aarch32::applyFixupDataHelper function to apply the fixup for Data-class relocations.
jitlink::aarch32::applyFixupThumbHelper function to apply the fixup for Thumb-class relocations.
jitlink::aarch64::applyFixupApply fixup expression for edge to block content.
jitlink::aarch64::createEmptyPointerSigningFunctionCreate an empty pointer signing function for the link graph.
jitlink::aarch64::lowerPointer64AuthEdgesToSigningFunctionLower Pointer64Authenticated edges into a pointer signing function.
jitlink::hexagon::applyFixupApply fixup expression for edge to block content.
jitlink::ppc64::applyFixupApply fixup expression for edge to block content.
jitlink::ppc64::relocateHalf16Write a 16-bit half16 relocation field for edge kind K.
jitlink::systemz::applyFixupApply fixup expression for edge to block content.
jitlink::systemz::optimizeGOTAndStubAccessesOptimize in-range GOT and stub relocations in the link graph.
jitlink::x86::applyFixupApply fixup expression for edge to block content.
jitlink::x86::optimizeGOTAndStubAccessesOptimize GOT and stub relocations when the edge target is in range.
jitlink::x86_64::applyFixupApply fixup expression for edge to block content.
jitlink::x86_64::optimizeGOTAndStubAccessesOptimize GOT and stub accesses when the ultimate target is in range.
objcopy::coff::executeObjcopyOnBinaryApply the transformations described by Config and COFFConfig to In and writes the result into Out.
objcopy::dxbc::executeObjcopyOnBinaryApply the transformations described by Config and DXContainerConfig to In and writes the result into Out.
objcopy::elf::executeObjcopyOnBinaryApply the transformations described by Config and ELFConfig to In and writes the result into Out.
objcopy::elf::executeObjcopyOnIHexApply the transformations described by Config and ELFConfig to In, which must represent an IHex file, and writes the result into Out.
objcopy::elf::executeObjcopyOnRawBinaryApply the transformations described by Config and ELFConfig to In, which is treated as a raw binary input, and writes the result into Out.
objcopy::macho::executeObjcopyOnBinaryApply the transformations described by Config and MachOConfig to In and writes the result into Out.
objcopy::macho::executeObjcopyOnMachOUniversalBinaryApply the transformations described by Config to In and writes the result into Out.
objcopy::wasm::executeObjcopyOnBinaryApply the transformations described by Config and WasmConfig to In and writes the result into Out.
objcopy::xcoff::executeObjcopyOnBinaryApply the transformations described by Config and XCOFFConfig to In and writes the result into Out.
offloading::amdgpu::getAMDGPUMetaDataFromImageReads AMDGPU specific metadata from the ELF file and propagates the KernelInfoMap.
offloading::intel::containerizeOpenMPSPIRVImageContainerizes an OpenMP SPIR-V image into an OffloadBinary image.
orc::shared::runDeallocActionsRun deallocation actions. Dealloc actions will be run in reverse order (from last element of DAs to first).
sys::fs::readNativeFileToEOFReads from FileHandle until EOF, appending to Buffer in chunks of size ChunkSize.

Derived Classes

NameDescription
ErrorSuccess Subclass of Error that represents success in the type system.
MSVCPError A default-constructible Error suitable for use with MSVC's std::future.

Return Value

NOTE

The return value should not be discarded.