Repository navigation
Cpp 09 ranges
Relevant source files
The following files were used as context for generating this wiki page:
Most of a pass is loops: over the functions in a module, the blocks in a function, the instructions in a block, the users of a value. Modern C++ writes these with range-based for and auto, and LLVM's STLExtras.h adds helpers such as any_of, enumerate and make_early_inc_range. This page shows them, and the classic bug of deleting while iterating.
This page covers iterators, range-based for, auto and auto &, the IR's nested ranges, STLExtras helpers, and iterator invalidation. Containers are on LLVM Data Structures.
| Reading | Iterators |
|---|---|
| A bookmark marking your place | An iterator |
| Moving it to the next page | ++It |
| Reading the page it marks | *It |
| The back cover |
end(): one past the last element |
| Tearing out the page the bookmark is on | Erasing the current element: the bookmark is now invalid |
// example: ranges
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
int main() {
SmallVector<int, 8> V = {4, 8, 15, 16, 23, 42};
for (int X : V) outs() << X << " "; // copy each element
outs() << "\n";
for (int &X : V) X *= 2; // reference: modify in place
for (const auto &X : V) outs() << X << " "; // read-only, any type
outs() << "\n";
outs() << "any > 80: " << any_of(V, [](int X) { return X > 80; })
<< ", all even: " << all_of(V, [](int X) { return X % 2 == 0; }) << "\n";
for (auto [Idx, X] : enumerate(V))
if (Idx < 2) outs() << "#" << Idx << " = " << X << "\n";
SmallVector<int, 8> W = {1, 2, 3, 4, 5, 6};
erase_if(W, [](int X) { return X % 2 == 0; }); // remove evens safely
outs() << "odd:";
for (int X : W) outs() << " " << X;
outs() << "\n";
}4 8 15 16 23 42
8 16 30 32 46 84
any > 80: 1, all even: 1
#0 = 8
#1 = 16
odd: 1 3 5
| Loop variable | Copies? | Can modify? | Use for |
|---|---|---|---|
for (int X : V) |
Yes | Only the copy | Small values |
for (auto &X : V) |
No | Yes | Changing elements |
for (const auto &X : V) |
No | No | Large elements, read-only |
for (auto *I : Ptrs) |
Copies the pointer | The pointee | Lists of pointers |
LLVM's rule for auto: use it when the type is obvious from the right-hand side (auto *LI = dyn_cast<LoadInst>(V)) or very long; write the type when it helps the reader. Always write * and & explicitly with auto.
Sources: cppreference: Range-based for loop, cppreference: auto
The IR containers are all ranges, nested like this:
flowchart LR
M["for (Function &F : M)"] --> F["for (BasicBlock &BB : F)"]
F --> B["for (Instruction &I : BB)"]
B --> U["for (User *U : I.users())"]
B --> O["for (Use &Op : I.operands())"]
// illustrative
for (Function &F : M) {
if (F.isDeclaration()) continue; // no body
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (auto *CI = dyn_cast<CallInst>(&I))
errs() << F.getName() << " calls " << *CI->getCalledOperand() << "\n";
}
// instructions(F) flattens the two inner loops; successors(&BB), predecessors(&BB) walk the CFGFunctions, blocks and instructions are iterated by reference (Function &), never by value: they can't be copied.
| Helper | Does |
|---|---|
any_of, all_of, none_of
|
Test a predicate over a whole range |
find_if, count_if, is_contained
|
Search |
enumerate(R) |
Gives (index, element) pairs |
zip(A, B) |
Walks two ranges together |
reverse(R) |
Backwards |
erase_if(C, Pred) |
Removes matching elements from a container |
make_early_inc_range(R) |
Lets you erase the current element while looping |
All of them take the whole range instead of begin()/end() pairs.
Sources: llvm/include/llvm/ADT/STLExtras.h:1739-1746, llvm/include/llvm/ADT/STLExtras.h:2554
// illustrative: BUG
for (Instruction &I : BB)
if (isInstructionTriviallyDead(&I))
I.eraseFromParent(); // the loop's iterator pointed at I: now danglingsequenceDiagram
participant L as Loop iterator
participant I as Current instruction
L->>I: points at I
I->>I: eraseFromParent(): I is deleted
L->>L: ++It reads I's "next" pointer: use after free
The fix is to advance before the body runs:
// illustrative: correct
for (Instruction &I : make_early_inc_range(BB))
if (isInstructionTriviallyDead(&I))
I.eraseFromParent(); // iterator already moved on to the next instructionThe same invalidation rules apply to containers: push_back on a SmallVector or std::vector may reallocate and invalidate all iterators, pointers and references into it; inserting into a DenseMap may move every entry. Collect changes in a separate list first, then apply them after the loop, when in doubt.
Sources: llvm/include/llvm/ADT/STLExtras.h:633, cppreference: std::vector
-
for (auto X : BigThings)copies each element; useconst auto &. - Erasing inside a plain range-for: use
make_early_inc_range. - Holding
&V[0]across apush_back. - Modifying users while iterating
V->users(): copy them into aSmallVectorfirst.
- Range-for with
auto &/const auto &is the normal loop; IR objects are iterated by reference. -
STLExtrasgives whole-range helpers likeany_of,enumerate,erase_if. - Erasing invalidates iterators: use
make_early_inc_range, or collect first and change after.
- 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