Repository navigation
Cpp 04 ownership
Relevant source files
The following files were used as context for generating this wiki page:
- llvm/include/llvm/Support/Casting.h
- cppreference: std::unique_ptr
- cppreference: std::move
- cppreference: Move constructors
- cppreference: Value categories
- Book: Scott Meyers, Effective Modern C++, chapters 4-5
Every object must eventually be destroyed exactly once. Ownership answers "who destroys it?". Modern C++ makes the owner explicit with std::unique_ptr and transfers ownership cheaply with move semantics. LLVM adds its own rule on top: most IR objects are owned by their parent (a module owns its functions, a block owns its instructions), so you rarely delete anything yourself.
This page covers stack versus heap, raw pointers versus owning pointers, std::unique_ptr, std::move and rvalue references, moved-from objects, and how ownership works for LLVM IR objects. Containers are on LLVM Data Structures.
| Property | C++ |
|---|---|
| A house has exactly one deed | An object has exactly one owner (unique_ptr) |
| Visitors may know the address without owning it | Raw pointers and references are non-owning |
| Selling the house hands over the deed; the seller has none left |
Moving a unique_ptr
|
| When the owner leaves for good, the house is demolished | The owner's destructor deletes the object |
flowchart LR
subgraph Stack["Stack: automatic"]
S1["int X = 5;"]
S2["SmallVector<int, 8> V;"]
end
subgraph Heap["Heap: dynamic"]
H1["new Node / make_unique<Node>()"]
end
S1 -.->|"freed when scope ends"| E1["automatic"]
H1 -.->|"freed when the owner is destroyed"| E2["unique_ptr destructor"]
| Stack | Heap | |
|---|---|---|
| Lifetime | Ends at the closing }
|
Until someone deletes it |
| Speed | Very fast | Allocation costs time |
| Size | Must be known at compile time, keep it modest | Any |
Prefer the stack. When you need the heap, let a unique_ptr own the object. Avoid writing new and delete by hand.
// example: move
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
struct Node {
std::string Name;
explicit Node(std::string N) : Name(std::move(N)) { outs() << "make " << Name << "\n"; }
~Node() { outs() << "free " << Name << "\n"; }
};
std::unique_ptr<Node> build(const char *N) { return std::make_unique<Node>(N); }
int main() {
std::unique_ptr<Node> A = build("a");
std::unique_ptr<Node> B = std::move(A); // ownership moves to B
outs() << "A is " << (A ? "set" : "empty") << ", B owns " << B->Name << "\n";
std::vector<std::unique_ptr<Node>> List;
List.push_back(std::move(B)); // now the vector owns it
List.push_back(build("b"));
outs() << "list size " << List.size() << "\n";
} // vector destroyed: frees bothmake a
A is empty, B owns a
make b
list size 2
free a
free b
sequenceDiagram
participant A as A
participant B as B
participant L as List
A->>B: std::move(A): B owns "a", A is null
B->>L: push_back(std::move(B)): List owns "a"
L->>L: end of main: List destroys its elements
| Operation | Allowed? | Why |
|---|---|---|
auto B = A; (copy a unique_ptr) |
No, compile error | Two owners would delete twice |
auto B = std::move(A); |
Yes | Ownership transfers; A becomes null |
Node *Raw = B.get(); |
Yes | A non-owning pointer for looking |
B.release() |
Yes, but rarely | Gives up ownership without deleting: now you must delete |
Sources: cppreference: std::unique_ptr
std::move(X) does not move anything by itself. It only casts X to an rvalue reference (T &&), meaning "you may steal from this". The type's move constructor then steals the contents, for example a std::string's heap buffer, instead of copying them.
| Expression | Category | Meaning |
|---|---|---|
X (a named variable) |
lvalue | Has a name; still used later, so copy it |
std::move(X), a returned temporary |
rvalue | About to disappear, so its insides can be taken |
After a move, the source is in a "valid but unspecified" state: you may assign to it or destroy it, but don't read its value. (unique_ptr is a special case: a moved-from one is guaranteed to be null.)
Returning a local by value (return Result;) moves or elides the copy automatically; don't write return std::move(Result);.
Sources: cppreference: std::move, cppreference: Value categories
flowchart TD
C["LLVMContext<br/>owns types and constants"] --- M["Module<br/>(often held in std::unique_ptr<Module>)"]
M -->|"owns"| F["Function"]
F -->|"owns"| BB["BasicBlock"]
BB -->|"owns"| I["Instruction"]
| Task | Call | Effect |
|---|---|---|
| Create and insert an instruction |
IRBuilder or X::Create(..., InsertBefore)
|
The parent block owns it |
| Unlink and destroy | I->eraseFromParent() |
Removes from the block and deletes |
| Unlink but keep | I->removeFromParent() |
Now you own it and must insert or delete it |
| Load a module |
parseIRFile(...) returns std::unique_ptr<Module>
|
You own the module |
So in a pass you hold plain Instruction * pointers that don't own anything, and you never delete an instruction directly. Before erasing, make sure nothing still uses it: call I->replaceAllUsesWith(New) first. Keeping a pointer to an erased instruction is a dangling pointer, the most common crash in new passes.
LLVM's casting functions even have a unique_ptr overload, cast<To>(std::unique_ptr<From> &&), which moves ownership while it casts.
Sources: llvm/include/llvm/Support/Casting.h:577
- Using a variable after
std::movefrom it. - Keeping
Instruction *pointers in a container and then erasing those instructions. -
std::shared_ptr"to be safe": LLVM code almost never needs shared ownership, and it costs reference counting. - Taking a
StringReforArrayRefto a temporary that dies at the end of the statement (see LLVM Data Structures).
- Every object has one owner;
unique_ptrmakes that explicit and deletes automatically. -
std::movecasts to an rvalue so the contents can be taken; don't read a moved-from object. - IR objects are owned by their parent; use
eraseFromParent, notdelete, and replace uses first.
- 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