Repository navigation
Cpp 08 errors
Relevant source files
The following files were used as context for generating this wiki page:
LLVM is compiled without C++ exceptions, so functions that can fail return their error as a value: llvm::Error when there is nothing else to return, llvm::Expected<T> when there is. For programmer mistakes ("this can never happen") LLVM uses assert and llvm_unreachable instead. For printing it uses raw_ostream rather than iostream. This page shows all three.
This page covers recoverable errors (Error, Expected<T>, createStringError, toString, handleAllErrors, cantFail), programmer errors (assert, llvm_unreachable, report_fatal_error) and output (outs(), errs(), dbgs(), raw_string_ostream).
| Delivery | LLVM |
|---|---|
| You get either the parcel or a "sorry, we missed you" card |
Expected<T>: either a T or an Error
|
| You must read the card; you can't just throw it away | An Error must be checked or LLVM aborts in debug builds |
| The van falling off a bridge | A bug: assert / llvm_unreachable crash immediately |
flowchart TD
F["Something went wrong"] --> Q{"Could correct input cause it?<br/>(bad file, invalid IR, user typo)"}
Q -->|"yes: recoverable"| E["Return Error / Expected<T><br/>caller decides what to do"]
Q -->|"no: a bug in our code"| A["assert(cond && \"msg\")<br/>or llvm_unreachable(\"msg\")"]
// example: errors
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
Expected<int> parseCount(StringRef S) {
int V;
if (S.getAsInteger(10, V)) // returns true on failure
return createStringError("not a number: '" + S + "'");
if (V < 0)
return createStringError("negative count: " + Twine(V));
return V; // success: implicit Expected<int>
}
Error checkAll(ArrayRef<StringRef> Inputs) {
for (StringRef In : Inputs) {
Expected<int> N = parseCount(In);
if (!N)
return N.takeError(); // pass the error up
}
return Error::success();
}
int main() {
for (StringRef In : {"12", "abc", "-4"}) {
Expected<int> N = parseCount(In);
if (N)
outs() << "ok " << *N << "\n";
else
outs() << "error: " << toString(N.takeError()) << "\n";
}
if (Error E = checkAll({"1", "2", "x"}))
outs() << "checkAll failed: " << toString(std::move(E)) << "\n";
int Sure = cantFail(parseCount("7")); // "this cannot fail"
outs() << "sure " << Sure << "\n";
}ok 12
error: not a number: 'abc'
error: negative count: -4
checkAll failed: not a number: 'x'
sure 7
| Tool | Meaning |
|---|---|
Expected<T> |
Holds a T or an error; if (N) tests success, *N reads the value |
N.takeError() |
Take the error out (to return it or handle it) |
Error::success() |
"No error" |
if (Error E = f()) |
An Error is true when it holds a failure |
createStringError(Twine) |
Make a simple error with a message |
toString(Error) |
Consume the error and get its message |
handleAllErrors(E, handlers...) |
Dispatch on error type |
logAllUnhandledErrors(E, errs(), "prefix: ") |
Print and consume |
cantFail(X) |
Assert X succeeded and unwrap it |
flowchart LR
C["Expected<int> N = parseCount(s)"] --> T{"if (N)"}
T -->|"true"| V["use *N"]
T -->|"false"| E["N.takeError()"]
E --> H1["return it upward"]
E --> H2["toString / log it"]
The checked rule. Every Error must be looked at before it is destroyed, and every Expected checked before use. In builds with LLVM's ABI-breaking checks (debug builds by default) forgetting this aborts with "Program aborted due to an unhandled Error". This catches ignored failures early.
Sources: llvm/include/llvm/Support/Error.h:159, llvm/include/llvm/Support/Error.h:485, llvm/include/llvm/Support/Error.h:769, llvm/include/llvm/Support/Error.h:1013, llvm/include/llvm/Support/Error.h:1088, llvm/include/llvm/Support/Error.h:1339
// illustrative
assert(Idx < Ops.size() && "operand index out of range"); // message as a string literal
switch (Kind) {
case SK_Circle: return area(cast<Circle>(S));
case SK_Square: return area(cast<Square>(S));
}
llvm_unreachable("unknown shape kind"); // after a fully covered switch| Tool | When it fires | In release builds |
|---|---|---|
assert(cond && "msg") |
cond is false |
Removed (NDEBUG) |
llvm_unreachable("msg") |
Control reaches it | Becomes an optimisation hint; reaching it is UB |
report_fatal_error("msg") |
Always | Always prints and exits; for unrecoverable user-facing problems in tools |
Many LLVM developers build with -DLLVM_ENABLE_ASSERTIONS=ON while developing so these checks run; release compilers usually ship without them.
Sources: llvm/include/llvm/Support/ErrorHandling.h:164-171
// example: output
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Format.h"
#include <string>
using namespace llvm;
int main() {
outs() << "count " << 42 << ", hex " << format_hex(255, 6) << "\n";
std::string Buf;
raw_string_ostream OS(Buf); // write into a std::string
OS << "inst" << 3;
outs() << "built '" << OS.str() << "'\n";
outs().indent(4) << "indented\n";
}count 42, hex 0x00ff
built 'inst3'
indented
| Stream | Goes to | Use |
|---|---|---|
outs() |
stdout | Normal tool output |
errs() |
stderr, unbuffered | Warnings, errors |
dbgs() |
stderr, only with -debug
|
Debug traces inside LLVM_DEBUG(...)
|
raw_string_ostream |
A std::string
|
Building text |
raw_fd_ostream |
A file | Writing output files |
Every IR object can print itself: errs() << *I << "\n"; prints an instruction, F.print(errs()) a function, and I->dump() (in assertion builds) prints to stderr from a debugger.
// illustrative: debug output that only appears with -debug-only=my-pass
#define DEBUG_TYPE "my-pass"
LLVM_DEBUG(dbgs() << "visiting " << *I << "\n");Sources: llvm/include/llvm/Support/raw_ostream.h:53, llvm/include/llvm/Support/raw_ostream.h:613-620, llvm/include/llvm/Support/raw_ostream.h:664
- Ignoring an
ErrororExpectedreturn: aborts in debug builds. - Reading
*Nwithout checkingif (N)first. - Side effects inside
assert(...): they disappear in release builds. - Using
std::coutin LLVM library code; useraw_ostream.
- Recoverable failures return
Error/Expected<T>, which must always be checked. - Bugs are caught with
assert(cond && "msg")andllvm_unreachable. - Print with
outs(),errs(),dbgs(); every IR object can be streamed with<<.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look