Profile-Guided Optimization, From First Principles

47 minutes read •


This write-up was distilled from an LLVM talk about making Profile-Guided Optimization (PGO) useful for mobile apps. The talk starts from a very practical problem: mobile startup is sensitive to page faults, but traditional PGO often improves speed by increasing code size through inlining. That trade-off is awkward on mobile, where smaller code can launch faster.

The interesting idea in the talk is temporal profiling: record when functions first execute, merge many startup traces, then let the linker reorder functions so startup code sits together in the final binary. The reported results were the kind worth remembering: up to 40% fewer startup page faults, almost 1-3% compressed-size reduction, and in one Firefox iOS experiment, over 6% compressed-size reduction for the client binary from function reordering alone.

Reddit’s iOS optimization write-up is the production-scale case study that made the idea click for me. Using PGO, temporal profiling, and function reordering, Reddit reduced the main iOS binary from 198.6 MiB to 157.1 MiB and the compressed IPA from 280.6 MiB to 239.6 MiB. The numbers are impressive, but the core idea is more important: instead of asking the compiler and linker to guess what matters, you run the app, record what actually happened, and feed that evidence back into the next build.

This document builds that idea from scratch. Prerequisites: you know an app eventually becomes a binary and that a compiler turns source code into machine code. Nothing more.

Part 1 — What the compiler normally guesses

A compiler has to make performance decisions before your app has ever run. Should this function be inlined? Which branch is likely? Which loop deserves more aggressive optimization? Which code should be kept close together in the final binary?

Static guess vs. profile-guided build

Static buildSource code shape
→
HeuristicsCompiler guesses hot paths
→
RiskBudget goes to the wrong code
PGO buildInstrumented app run
→
Profile dataReal hot paths recorded
→
Optimized buildBudget follows evidence

The difference is not that PGO has a smarter compiler. It gives the compiler a measured workload to believe.

Without profiles, the compiler uses static heuristics: educated guesses based on the shape of the code. Those guesses are often reasonable, but they are still guesses. A function that looks small may be irrelevant. A branch that looks unlikely may be the branch every user hits during startup. A generic utility may be cold in most of the app but hot on the first screen.

Static optimization

The compiler looks only at source/IR. It optimizes based on general rules: small functions are inline candidates, loops get transformed, branches get predicted from code shape.

Profile-guided optimization

You first build an instrumented app, run representative flows, merge the generated profile files, then rebuild using those profiles. The compiler now has evidence.

Switch the compiler's view

Source shapeSmall function, branch, loop
→
Heuristic"This probably matters"
→
RiskWrong path gets budget

Without profiles, the compiler only sees the code's shape. It cannot know which path users actually hit.

Runtime datastartup called this 1,000x
→
OptimizerSpend budget here
→
Cold pathKeep small, move later

PGO replaces "probably" with measured behavior from the workload you chose.

PGO is a feedback loop: build with instrumentation → run realistic behavior → collect profiles → rebuild using those profiles.

The profile does not change what your program means. It changes how aggressively and where the toolchain spends optimization budget.

The rule to remember: coverage PGO tells the compiler what code is hot. Temporal PGO tells the linker what code runs together. On mobile, both matter because code size and code layout affect startup.

Part 2 — Why mobile cares about hot code and size

Mobile startup is not only about how fast one function executes after it is already in memory. Before that function can run, its code has to be present in memory. If it is not, the kernel brings in the page that contains it, and that page fault costs time. A smaller and better-laid-out __TEXT section usually means fewer pages touched during startup.

This is why the hot/cold distinction matters. PGO is deciding where the toolchain should spend optimization budget. Some code deserves aggressive treatment because it runs during startup or a critical flow. Some code should mostly stay out of the way because making it bigger or placing it early can hurt the path users actually feel.

PGO starts with a simple split: some code is hot, some code is cold. Hot does not mean "important to the product" and cold does not mean "dead". Hot means "executed often, or executed during an important measured window". Cold means "rarely executed in the profile you collected".

CategoryMeaningOptimization implication
HotRuns frequently or during a critical flow such as cold startup.Worth inlining, branch tuning, layout priority, and sometimes more code size.
ColdRuns rarely or never in the collected workload.Avoid wasting binary size. Keep it out of the hot path and often optimize for size.
WarmRuns sometimes, but not in the first-order path.Optimize normally; do not let it disrupt startup layout.

The phrase "hot path" is only meaningful relative to the workload you profiled. If your profile comes from login and home-feed startup, then PGO learns about login and home-feed startup. It cannot magically optimize a checkout flow, editor flow, or obscure settings screen unless that behavior appears in the profile.

Why -Oz can beat "faster" optimization

On desktop/server code, "optimize for speed" often sounds like the obvious default. On mobile, size is part of speed. That is why mobile apps are often built with -Oz or other size-aware settings instead of blindly choosing speed-oriented optimization. More inlining can make a hot CPU loop faster, but it can also inflate code size enough to hurt cold startup.

Move the inlining dial

35%
CPU call overhead65%
Code size35%
Startup page risk42%

Inlining can reduce call overhead, but it also grows code. On mobile, too much growth can make startup worse even if individual calls are faster.

Part 3 — The PGO feedback loop

At a high level, PGO has two builds and one run in the middle.

1. Instrumented build
Compile with flags such as -fprofile-generate. The produced app includes counters or probes that write execution data.
→
2. Representative run
Exercise the app through realistic flows: startup, logged-out, logged-in, notifications, critical screens, experiments.
→
3. Merge profiles
Combine raw outputs with llvm-profdata merge into a stable .profdata file.
→
4. Optimized build
Rebuild with -fprofile-use=/path/profile.profdata. The compiler and linker now optimize with evidence.

The profiles are build inputs. Treat them like generated artifacts with a freshness policy, not like magic constants checked in forever.

Step through the feedback loop

InstrumentAdd counters/timestamps
→
ExerciseRun representative flows
→
MergeTurn raw runs into profile input
→
OptimizeCompiler/linker use the profile

The first build is deliberately instrumented; it is not the final app you ship.

clang -fprofile-generate ...       # build an instrumented binary
./run-representative-workload      # emits one or more .profraw files
llvm-profdata merge *.profraw -o app.profdata
clang -fprofile-use=app.profdata ...

Part 4 — Coverage profiling

Coverage profiling answers: what ran, and how much? It records function counts, branch behavior, and other execution-frequency signals. When you feed that profile into a later compile, the compiler can make better local decisions.

Inlining

Inlining removes a function call by copying the callee into the caller. It can expose further optimization, but it can also grow the binary. PGO helps spend inlining budget on hot calls instead of cold ones.

Branch layout

If one branch is usually taken, the compiler can lay out the common path so the CPU does less jumping and prediction is easier.

Loop and codegen choices

Loops that actually run many iterations can justify heavier optimization. Cold loops should not receive the same attention by default.

Choose a coverage profile

bootstrap()950
decodeFeed()780
openSettings()40

The compiler sees startup and feed code as hot, so inlining and branch decisions bias toward that path.

bootstrap()350
decodeFeed()120
openSettings()920

A different workload teaches a different truth. This is why representative profiling matters.

Coverage PGO is mostly about compiler decisions inside and between functions.

It tells the optimizer where the execution weight is, so it can avoid treating every path as equally important. The mobile caveat: default IRPGO is often tuned toward inlining and speed, so without size-aware settings it can grow the binary.

That caveat matters. If PGO says "this call is hot", the compiler may inline it. Sometimes that is exactly right. Sometimes the extra code size creates more instruction-cache pressure and more pages to fault in. LLVM has size-oriented knobs such as profile-guided size optimization and inlining controls for this reason. PGO is evidence; policy still matters.

Part 5 — Temporal profiling

Coverage answers "how often?". Temporal profiling answers "when, and in what order?" That distinction matters for startup. During a cold launch, the device does not load your entire binary into memory at once. It faults in pages as code is touched. If startup functions are scattered across the file, the system touches more pages earlier.

Temporal profiling records an execution trace: function A happened, then B, then C. For mobile startup, that sequence is gold. It lets the linker place functions that execute close together physically close together in the binary.

Coverage profile
FeedViewController.viewDidLoad: 1
JSONDecoder.decode: 340
SettingsScreen.open: 0
→
Compiler learns
Decode path is hot. Settings path is cold. Inline and branch decisions should reflect that.
Temporal profile
main → AppDelegate → bootstrap → feed → first cell
→
Linker learns
These functions belong near each other because startup touches them in this order.

Both profiles describe the same app, but they answer different optimization questions.

Record first-call timestamps

main
0
App
0
Feed
0
Cell
0
Settings
0

Before execution, every timestamp is zero. Zero means "not observed in this run."

In Reddit's write-up, temporal profiling used LLVM's -pgo-temporal-instrumentation. The LLVM talk explains the mechanism: every instrumented function gets a timestamp slot initialized to zero; on the first call, the runtime writes the current global timestamp and increments it. When the raw profile is dumped, functions can be sorted by timestamp to recover a trace. A zero timestamp means the function did not run in that profile.

A key detail: temporal instrumentation has much lower binary-size overhead than traditional IR PGO instrumentation, which helps the profiled app behave more like the real release app. If the profiled build is wildly different from release, its function order is less trustworthy.

Part 6 — Function layout and page faults

A binary is not just a bag of functions. It is an ordered file. That order affects cold startup because the kernel brings code into memory in pages. Reddit's article calls out 16 KiB pages on iOS. The exact page size matters less than the invariant: touching code from many far-apart regions causes more page faults than touching code from nearby regions.

Before layout
After layout

Compare page touches

Pages touched11
Startup waithigh

Startup functions are spread apart, so the launch path jumps across many pages.

Pages touched5
Startup waitlower

Startup functions are adjacent, so the launch path reuses nearby pages.

Function reordering does not make a function faster in isolation. It makes the startup walk through the binary cheaper: fewer scattered pages, fewer cold misses, less waiting before the app becomes interactive.

For cold startup, where code lives can matter almost as much as what the code does.

That is the part of PGO I want to remember: profiles can guide not only compiler transforms, but also physical binary layout.

Also keep two goals separate: the compressed IPA should be small so install/update is fast, while the installed binary should be laid out so launch is fast. The app is not decompressing the IPA during startup; compression helps distribution, page-fault reduction helps launch.

Part 7 — Balanced partitioning

The hard part is that layout has two goals that can pull in different directions.

Startup locality

Functions that run near each other in time should sit near each other in the file. This reduces page faults during cold startup and critical flows.

Compression locality

Functions with similar instruction patterns often compress better when placed near each other, because LZ-style compression benefits from repeated nearby patterns.

Pick the layout objective

Amain
Bbootstrap
Cfeed
Xsettings

Prioritize functions that execute close together in the startup trace.

X1similar bytes
X2similar bytes
Y1similar bytes
Y2similar bytes

Prioritize functions with similar instruction patterns so compression sees repeated nearby sequences.

Hot traceA · B · C
Warm similarY1 · Y2
Cold similarX1 · X2

Balanced partitioning searches for a useful compromise: startup locality first where it matters, compression locality elsewhere.

Balanced partitioning treats layout like a graph problem. Functions are nodes. Relationships between functions are utilities: "these two run near each other" or "these two look similar for compression". The algorithm recursively partitions the graph so strongly related functions tend to stay together. With an option such as --compression-sort=both, the linker can balance temporal locality and compression locality instead of choosing only one.

Temporal utility
A → B → C appeared in the startup trace, so A, B, and C should be close.
Compression utility
X and Y have similar machine-code patterns, so placing them close may shrink the compressed IPA.
Partitioning decision
Keep high-utility relationships inside the same partition when possible; split weaker relationships first.

This is why the same optimization can improve startup and reduce size. The layout is optimized using real execution traces plus code-similarity signals.

The LLVM talk gives a concrete compression model: LZ-style compression benefits from repeated instruction sequences appearing within a sliding window. Function contents can be represented by stable hashes of instructions; functions sharing many utility vertices are good candidates to place near each other. For startup, the utility vertices come from temporal traces instead.

Part 8 — Reddit's iOS pipeline

Reddit's production story becomes much easier to read once the pieces are separated.

1. Representative workloads

They reused UI performance tests around important P0 use cases: fresh install, signed-out, logged-in, account switching, opening posts, and feed paths. HTTP stubbing reduced noise so the profiles reflected app behavior instead of network timing.

2. Two profile families

Coverage profiles fed compiler optimization through -profile-use. Temporal profiles fed linker function ordering through LLD.

3. Final optimized release build

The final App Store binary was built with profile inputs, a custom LLVM linker, and balanced partitioning for startup locality and compression.

instrumented app + UI tests
  ├─ coverage .profraw files  → llvm-profdata merge → coverage.profdata
  └─ temporal .profraw files  → llvm-profdata merge → temporal.profdata

release build
  ├─ swiftc / clang use coverage.profdata for compiler PGO
  └─ LLD uses temporal.profdata for function ordering

Follow one profile through the release pipeline

Testsrealistic app paths
→
Profilescoverage + temporal
→
swiftc/clanguse coverage data
→
LLDuses temporal layout

The profile starts as UI-test behavior, not as a hand-written order file.

They also tuned the inlining threshold upward. That is an important reminder: PGO is not just one flag. It is a build pipeline. Profiles make bolder optimization choices safer, but they do not remove trade-offs. More inlining can speed hot paths and expose optimization, but it can increase binary size. In Reddit's case, the layout/compression savings created room to be more aggressive.

Results Worth Remembering

Compressed IPA
280.6 → 239.6 MiB
14.6% reduction
Uncompressed payload
359.8 → 313.1 MiB
15.3% reduction
Main binary
198.6 → 157.1 MiB
20.8% reduction

Those are size wins. The startup win was subtler to measure because iOS performs background optimizations after installation. Reddit focused on first-day behavior after install/update, where cold-start layout matters most, and used a dual-release strategy: one standard release, then an identical-code optimized release.

Part 9 — Case study: reading a real profile

Everything above was theory plus other people's numbers. So I collected an IR PGO profile from the app I work on — a large marketplace iOS app, ~100 build modules — using a UI test that performs 6 cold launches and a feed browse pass. Then I actually read the profile. This section is what the theory looks like against production-scale code, and it changed how I think about two things: how extreme the hot/cold split really is, and whose code the hot set is made of.

Functions instrumented
383,676
the whole app + every dependency
Executions recorded
36.65M
sum of every branch-point counter
Never called
96.32%
369,574 functions had entry count 0

How skewed is "skewed"?

Before looking, I assumed hot/cold meant something like 20/80. The real distribution is not in that universe. llvm-profdata show --detailed-summary prints a cumulative table: how many counter blocks (branch points) does it take to cover each share of all recorded executions? Verbatim output:

$ xcrun llvm-profdata show --detailed-summary app.profdata
Total functions: 383676
Total number of blocks: 1073586
Total count: 36654739
Detailed summary:
26 blocks (0.00%) with count >= 197216 account for 50% of the total counts.
485 blocks (0.05%) with count >= 6384 account for 90% of the total counts.
1084 blocks (0.10%) with count >= 1505 account for 95% of the total counts.
4666 blocks (0.43%) with count >= 133 account for 99% of the total counts.

Blocks needed to cover each share of execution

50% of counts26
80%181
90%485
95%1,084
99%4,666
100%24,071

Bar length = share of execution covered; the number on the right = blocks needed, out of 1,073,586. Only 24,071 blocks (2.2%) executed at all.

If execution were uniform, covering 50% of the counts would take ~537,000 blocks. It took 26. That is a concentration factor of roughly 20,000×.

This is why PGO works at all: the compiler can lavish attention on a few hundred functions and treat literally everything else as cold, and that policy is correct for 97.8% of the binary.

Whose code is hot? Not mine.

My second wrong assumption: that the hot set would be my app's code. Bucketing all 21M function entries by what kind of code was entered:

Share of function entries by code kind

Swift runtime helpers43.5%
Compiler glue37.8%
Third-party SDKs16.0%
My app's code1.5%

"Compiler glue" = protocol/value witnesses, outlined copy/destroy helpers, thunks, metadata accessors — machinery the compiler generates around everyone's code.

The single most-called function in the entire app was __swift_memcpy1_1 — 2,920,324 calls. That is 2.9 million one-byte copies, almost all driven by one third-party experimentation SDK that round-trips its JSON payloads through type-erased Any boxes during launch. The hottest single branch point in the binary was the read loop of nanopb — the C protobuf parser inside the analytics SDK — at 3.31M executions, because analytics state is parsed and re-encoded on every cold start.

Hottest spots in the binaryWhat it isMax count
buf_read (nanopb)protobuf decode loop, analytics SDK3,312,715
__swift_memcpy1_1runtime helper: copy one byte2,920,324
__swift_noop_void_returnruntime helper: do nothing2,629,953
AnyEncodable destroy/copy witnessesCodable type-erasure glue, experiments SDK535,920 / 446,600

Three more things the profile revealed that no amount of code review would have surfaced:

The profile is a free product audit

17% of all function entries belonged to one experimentation SDK's Codable glue. The localization layer burned 250K entries in just 56 functions, copying a large enum payload on every string lookup. Neither showed up in any Instruments session we had run — they were spread across too many tiny calls.

Dead weight is measurable

A generated analytics-events package contributed 6.8% of all functions in the binary but ~0.05% of execution. That is exactly the code the cold-marking half of PGO shrinks — and the strongest argument for the layout techniques in Parts 5–7.

The hot set is glue, so PGO's wins are glue wins

Inlining a 3-line value witness into its hot caller eliminates call overhead on millions of one-byte copies. The classic C wins apply too: precise branch weights in nanopb's decode loops, the hottest code in the binary.

To do this on any app: build with -fprofile-generate (plus swiftc's IR-profile flags on iOS), run a launch workload, merge, then read the result before applying it:

xcrun llvm-profdata show --detailed-summary app.profdata   # the skew table
xcrun llvm-profdata show --topn=50 app.profdata | xcrun swift-demangle   # hottest functions
xcrun llvm-profdata show --all-functions --counts app.profdata | less    # everything

Read the profile before you feed it to the compiler. The same file that guides the optimizer is the most honest launch-behavior audit you will ever get for free.

Part 10 — Measurement and traps

PGO sounds mechanical, but the quality of the result depends on the quality of the profile and the measurement plan.

TrapWhy it mattersMitigation
Unrepresentative profileThe optimizer improves the behavior you showed it, not the behavior you hoped it would infer.Profile critical user flows, feature-flag combinations, and startup states.
Profile stalenessAs code changes, old profiles mention removed functions and miss new hot paths.Regenerate profiles automatically in CI, especially before release.
Instrumentation distortionIf the instrumented app is much larger or slower, temporal order may differ from release.Prefer low-overhead temporal instrumentation for layout profiles where available.
Speed-vs-size policyInlining-heavy PGO can improve CPU-bound paths while making mobile startup worse through code growth.Use size-aware optimization settings and measure both binary size and startup/page-fault behavior.
Toolchain mismatchProfiles and compilers/linkers need compatible formats and versions.Pin toolchain versions and treat profile corruption/version errors as infrastructure failures.
Confounded rolloutIf code changes and optimization changes ship together, impact is hard to isolate.Use a controlled release plan when measuring pure optimization impact.

Tap a trap

Pick a trap to see the failure mode.

The hard engineering is not "turn on PGO". The hard engineering is collecting profiles you trust and proving the optimized binary helped.

Part 11 — Diagnostic reference

Useful commands and flags to recognize when reading a PGO pipeline:

ThingRole
-fprofile-generateBuild an instrumented binary that emits raw profile data.
LLVM_PROFILE_FILECommon runtime environment variable used to control where profile files are written.
llvm-profdata mergeMerge one or more .profraw files into a .profdata file consumed by the compiler/linker.
-fprofile-use=path / -profile-use=pathUse a merged profile during the optimized build.
-pgo-temporal-instrumentationLLVM temporal profiling instrumentation for ordering-sensitive profile data.
--compression-sort=bothLLD layout mode that balances startup-oriented ordering and compression-oriented ordering.
-OzOptimize for size. Important on mobile because code size can affect page faults and startup.
PGSO / inlining controlsSize-aware policy knobs that can mitigate binary growth from PGO-guided inlining.
pgo-warn-missing-function=falseSuppress warnings/errors when profiles mention functions not present in the final binary. Useful when profiled and release builds are close but not identical.

Command map

Build an instrumented binary that emits raw profile data. This is the learning build, not the final release build.

Part 12 — FAQ

Is PGO the same as test coverage?

No. Both may use instrumentation, but the goal differs. Test coverage asks "did tests execute this code?" PGO asks "how should the optimizer spend effort based on execution behavior?" A profile can be useful for PGO even if it is not a complete coverage report.

Does PGO require production user data?

No. Production profiles can be more representative, but they are operationally harder. Reddit chose UI tests with stable stubs and many important use cases. That is a practical trade-off: less real-world diversity, more repeatability and lower complexity.

Can PGO make code slower?

Yes. A stale or biased profile can over-optimize the wrong paths, increase code size, or damage instruction-cache locality. That is why measurement and rollback matter.

Why does binary layout affect compressed size?

Compression algorithms such as LZ variants exploit repeated patterns within a window. If similar machine-code sequences are placed near each other, the compressed artifact can shrink.

Is the app decompressing its IPA during startup?

No. The compressed IPA matters for download and installation. Startup page faults come from touching installed binary pages that are not resident in memory yet. These are related optimization goals, but not the same mechanism.

Why not always use speed optimization with PGO?

Because mobile startup is sensitive to code size. A speed-oriented profile can encourage more inlining, which can increase the amount of code the app has to page in. For mobile, the best policy often balances speed, size, and layout.

Why is startup impact strongest after install or update?

Because the first launches touch cold filesystem and memory state. Over time, OS-level caching and background optimizations can reduce the visible difference, so first-day metrics are often the cleanest window.

Quick check

If the optimized app has a smaller compressed IPA but the same startup page faults, which half of the optimization probably helped?

Compression locality. Startup locality is measured through page faults and time-to-interactive behavior; compressed IPA size is a distribution/install win.

Part 13 — Glossary

Pick a term

A feedback loop: collect execution behavior from an instrumented run, then use it to optimize a later build.
PGO
Profile-Guided Optimization: optimizing a later build using profiles collected from an earlier instrumented run.
IRPGO
Instrumentation-based PGO at the LLVM IR level. The compiler inserts instrumentation into intermediate representation to collect execution data.
Coverage profile
A profile describing which functions, branches, and paths ran and how often.
Temporal profile
A profile describing execution order over time, useful for function layout.
Function reordering
Changing the order of functions in the final binary so related code is physically close.
Page fault
An event where the system must bring a memory page into the process because the app touched code or data not currently resident.
LLD
LLVM's linker. In this context, it consumes temporal profiles and performs function layout optimizations.
Profile staleness
The loss of profile usefulness as source code and behavior drift away from the workload that produced the profile.

Sources