Skip to content

Cpp 09 ranges

Mugundan edited this page Nov 27, 2026 · 1 revision

Iterators and 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.

Purpose and Scope

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.

The Bookmark Analogy

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

Range-based for and auto

// 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

Walking the IR

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())"]
Loading
// 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 CFG

Functions, blocks and instructions are iterated by reference (Function &), never by value: they can't be copied.

STLExtras Helpers

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

Deleting While Iterating

// illustrative: BUG
for (Instruction &I : BB)
  if (isInstructionTriviallyDead(&I))
    I.eraseFromParent();       // the loop's iterator pointed at I: now dangling
sequenceDiagram
    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
Loading

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 instruction

The 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

Common Traps

  • for (auto X : BigThings) copies each element; use const auto &.
  • Erasing inside a plain range-for: use make_early_inc_range.
  • Holding &V[0] across a push_back.
  • Modifying users while iterating V->users(): copy them into a SmallVector first.

Key Points

  • Range-for with auto & / const auto & is the normal loop; IR objects are iterated by reference.
  • STLExtras gives whole-range helpers like any_of, enumerate, erase_if.
  • Erasing invalidates iterators: use make_early_inc_range, or collect first and change after.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally