Repository navigation
Cpp 07 casting
Relevant source files
The following files were used as context for generating this wiki page:
In a pass you constantly hold a Value * or Instruction * and need to ask "is this actually a load?". Standard C++ answers with dynamic_cast, but LLVM is built with C++ RTTI turned off. Instead, every class in a hierarchy stores a small kind number, and three templates use it: isa<>, cast<> and dyn_cast<>. You will write these more than almost anything else.
This page covers the three casting operators and their null-tolerant variants, how classof makes them work, how to add LLVM-style RTTI to your own classes, and how IR classes do it. Class hierarchies in general are on Classes and RAII.
| Office | LLVM-style RTTI |
|---|---|
| Everyone wears a badge with their job printed on it | Each object stores a kind (ValueID) |
| "Are you a nurse?" — look at the badge | isa<Nurse>(P) |
| "You're a nurse, take this patient" — wrong if not |
cast<Nurse>(P) (asserts) |
| "If you're a nurse, take this patient; otherwise no one" |
dyn_cast<Nurse>(P) (returns null) |
| Call | Returns | If the type is wrong | Use when |
|---|---|---|---|
isa<T>(V) |
bool |
false |
You only need to test |
cast<T>(V) |
T * |
Assertion failure in debug builds | You know it's a T |
dyn_cast<T>(V) |
T * or nullptr
|
nullptr |
It might be a T |
isa_and_nonnull<T>(V) |
bool |
false, also false if V is null |
V may be null |
dyn_cast_if_present<T>(V) |
T * or nullptr
|
nullptr, also if V is null |
V may be null |
isa, cast and dyn_cast themselves must not be given a null pointer.
// illustrative: the everyday pattern in a pass
for (Instruction &I : instructions(F)) {
if (auto *LI = dyn_cast<LoadInst>(&I)) { // "if it is a load..."
Value *Ptr = LI->getPointerOperand();
...
} else if (isa<StoreInst>(I)) {
...
}
}Sources: llvm/include/llvm/Support/Casting.h:547, llvm/include/llvm/Support/Casting.h:559-577, llvm/include/llvm/Support/Casting.h:643-655
isa<T>(V) simply calls the static function T::classof(V). Each class answers by looking at the kind stored in the object.
flowchart LR
C["isa<AllocaInst>(V)"] --> CO["AllocaInst::classof(V)"]
CO --> Q1{"isa<Instruction>(V)?"}
Q1 -->|"no"| F["false"]
Q1 -->|"yes"| Q2{"getOpcode() == Alloca?"}
Q2 -->|"yes"| T["true"]
Q2 -->|"no"| F
Here is the real code from AllocaInst:
// Methods for support type inquiry through isa, cast, and dyn_cast:
static bool classof(const Instruction *I) {
return (I->getOpcode() == Instruction::Alloca);
}
static bool classof(const Value *V) {
return isa<Instruction>(V) && classof(cast<Instruction>(V));
}The kind lives in Value: an enum ValueTy lists every value kind, and getValueID() returns it. Checking a kind is one load and a compare, much cheaper than dynamic_cast, and it needs no vtable.
Sources: llvm/include/llvm/IR/Instructions.h:165-171, llvm/include/llvm/IR/Value.h:524, llvm/include/llvm/IR/Value.h:543
The recipe from How to set up LLVM-style RTTI:
- Put an enum of kinds in the base class, one entry per concrete class.
- Store the kind in the base; the constructor takes it.
- Give each derived class
static bool classof(const Base *)that checks the kind.
// example: casting
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
class Shape {
public:
enum ShapeKind { SK_Circle, SK_Square };
ShapeKind getKind() const { return Kind; }
protected:
explicit Shape(ShapeKind K) : Kind(K) {}
private:
const ShapeKind Kind;
};
class Circle : public Shape {
public:
explicit Circle(int R) : Shape(SK_Circle), Radius(R) {}
int Radius;
static bool classof(const Shape *S) { return S->getKind() == SK_Circle; }
};
class Square : public Shape {
public:
explicit Square(int S) : Shape(SK_Square), Side(S) {}
int Side;
static bool classof(const Shape *S) { return S->getKind() == SK_Square; }
};
void describe(const Shape *S) {
if (const auto *C = dyn_cast<Circle>(S))
outs() << "circle radius " << C->Radius << "\n";
else
outs() << "square side " << cast<Square>(S)->Side << "\n";
}
int main() {
Circle C(3);
Square Q(4);
const Shape *All[] = {&C, &Q};
for (const Shape *S : All)
describe(S);
outs() << "isa circle: " << isa<Circle>(All[0]) << " " << isa<Circle>(All[1]) << "\n";
const Shape *None = nullptr;
outs() << "nonnull: " << isa_and_nonnull<Circle>(None) << "\n";
}circle radius 3
square side 4
isa circle: 1 0
nonnull: 0
For a class with subclasses of its own, classof checks a range of kinds (K >= SK_FirstX && K <= SK_LastX); this is exactly how Value.h handles groups such as constants.
dynamic_cast |
dyn_cast |
|
|---|---|---|
| Needs C++ RTTI and virtual functions | Yes | No |
| Cost | Walks type info at run time | One compare on a stored kind |
| Works on classes you add | Automatically | After you write classof
|
| Available in LLVM builds | No (RTTI off) | Yes |
Sources: cppreference: dynamic_cast, Wikipedia: Run-time type information
- Using
castwhen you aren't sure: release builds don't check, so a wrongcastis undefined behaviour. - Testing with
isaand then callingcastagain: write onedyn_castinstead. - Passing null to
isa/cast/dyn_cast: use the_and_nonnull/_if_presentforms. - Forgetting
classofin a new subclass: compile errors mentionclassof.
-
isatests,castconverts and asserts,dyn_castconverts or returns null. - They work through static
classoffunctions checking a kind stored in the object, with no C++ RTTI. - Add LLVM-style RTTI to your own hierarchy with a kind enum and
classof.
- 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