Skip to content

[browser][CoreCLR] Collect ReadyToRun PGO with indexed schemas - #137502

Open
pavelsavara wants to merge 15 commits into
pavelsavara/browser-coreclr-r2r-pgo-corefrom
pavelsavara/browser-coreclr-r2r-pgo-schema-table
Open

pavelsavara wants to merge 15 commits into
pavelsavara/browser-coreclr-r2r-pgo-corefrom
pavelsavara/browser-coreclr-r2r-pgo-schema-table

Conversation

@pavelsavara

@pavelsavara pavelsavara commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR adds opt-in PGO collection for published Browser/CoreCLR ReadyToRun apps. You train the app in a browser, collect a trace, convert it to MIBC with dotnet-pgo, and pass the profile to the next ReadyToRun publish.

Instrumented ReadyToRun code collects the same data as JIT instrumentation elsewhere:

  • sparse edge counts, including inlinees
  • integer value histograms at Memmove and SequenceEqual
  • receiver type histograms at virtual and interface calls
  • input type histograms at casts
  • delegate target method histograms

On republish, crossgen2 uses this data the usual way: flow reconstruction, value specialization, and guarded devirtualization or delegate inlining.

To use it:

  1. Publish with PublishReadyToRunPgoInstrumentation=true.
  2. In the browser, call collectPgoTrace().
  3. Run dotnet-pgo create-mibc against the matching IL.
  4. Republish with PublishReadyToRunPgoFiles and instrumentation turned off.

The full workflow is documented in src/mono/wasm/features.md.

Stack

This change is split into a stack of PRs. Review each layer separately, bottom first. This PR is the integration layer on top.

Layer PR Areas below
1 #138612 JIT PGO instrumentation refactor C (refactor part)
2 #138613 PgoManager hardening K (platform-neutral part)
3 #138614 dotnet-pgo allocation merging L
4 #138615 Wasm R2R guarded devirtualization from profile data E, F, consumer part of H
5 #138616 R2R PGO producer core A, B, C, D, G, H, I, J, K
6 this PR M, N (end-to-end), O, plus the merged #138262 (P)

The lettered areas below describe the whole stack.

Areas of change

A) Feature gating. clrfeatures.cmake defines FEATURE_R2R_PGO only for single-threaded Browser/Wasm with FEATURE_PGO. The standalone Wasm JIT always defines it (jit/CMakeLists.txt), because crossgen2 hosts that JIT on desktop. Everything below depends on this switch.

B) R2R image format. readytorun.h bumps R2R to 34.2 and adds:

  • a new section, PgoInstrumentationSchemas (129);
  • a new fixup, PgoInstrumentationData (0x3C): a method signature followed by a schema index;
  • three helpers, ValueProfile64, ClassProfile64 and DelegateProfile64 (0x11A–0x11C).

The managed copies (ModuleHeaders.cs, ReadyToRunConstants.cs, NativeAOT ModuleHeaders.h) and the R2RDump signature parser are updated to match. The image stores no counters, only deduplicated schemas.

C) JIT counter addressing. In fgprofile.cpp, the new GetProfileAddress makes R2R probes load the counter base from an import cell (an invariant load) plus an offset, instead of a constant slab address. R2R instrumentation forces 64-bit counters and one slot per counter, with no interlocked or scalable updates. The scattered JitConfig reads move into new opts.compPgo* fields. Writing synthesized counts is disabled for R2R, because the profile address is only a symbol at compile time.

D) JIT probe kinds enabled for AOT. fgPrepareToInstrumentMethod and compClassifyGDVProbeType now turn on edge, class (type), value and delegate histograms, plus cast probes (fgR2RCastProfiling), when R2R PGO is active. Before this, they were JIT-only. VTable method profiling stays off.

E) JIT guarded devirtualization for Wasm R2R interface calls. A new flag, GTF_CALL_M_R2R_INTERFACE_LDVIRTFTN, marks non-generic interface calls that Wasm R2R imports through ldvirtftn. Those calls can then get class probes and guarded devirtualization. In indirectcalltransformer.cpp, SplitCall gains a fallbackUse parameter so the ldvirtftn control expression runs only on the fallback path.

F) JIT delegate guarded devirtualization in R2R. pickGDV allows method profiles for delegate calls on Wasm R2R. impTransformDevirtualizedCall uses getFunctionFixedEntryPoint for the guarded delegate target. Crossgen2 implements that call for Wasm only, restricted by CanReferenceDelegateProfileTarget.

G) Crossgen2 schema table and fixup nodes. The new PgoInstrumentationSchemaTableNode keys entries by content, sorts them so the output is deterministic, and owns Layout, the counter-offset layout the runtime re-derives identically. The new PgoInstrumentationDataSignature encodes the fixup. The node factory registers the section.

H) Crossgen2 JIT-EE interface glue. In CorInfoImpl.ReadyToRun.cs, allocPgoInstrumentationBySchema hands the JIT a pinned pointer-sized cell and attaches the import as a precode fixup. recordRelocation/findKnownBBCountBlock map that cell back to the import. Other pieces:

  • If the method has no token yet, crossgen2 requests one and recompiles the method (_pgoTokenMissing).
  • getJitFlags sets CORJIT_FLAG_PGO_INSTR.
  • When consuming a profile on Wasm, type and delegate-method entries are filtered to what R2R can reference.

I) Crossgen2 command line. The new --pgo-instrumentation option is rejected unless the target is single-threaded browser-wasm. Instrumented builds keep their original IL even when --strip-il-bodies is requested.

J) Runtime fixup resolution. In jitinterface.cpp, LoadDynamicInfoEntry decodes the method and schema index. It then calls the new PgoManager::allocPgoInstrumentationFromR2RSchema, which validates the section (offset table, record kinds and flags, histogram pairing, IL offset bounds, no duplicates) before allocating. Runtimes without FEATURE_R2R_PGO reject the fixup, so the method falls back to non-R2R execution.

K) PgoManager under FEATURE_R2R_PGO. In pgo.cpp:

  • Counter data is 8-byte aligned.
  • One method can own several allocations, chained through nextForMethod. An existing allocation is reused only if its schema matches exactly.
  • Returned pointers and offsets are relative to the counters, not the header.
  • GetStableHash moves before the lock, and overflow checks are added.
  • The schema reader becomes callback-based.

Counters are exported through the existing JitInstrumentationData EventPipe events when the PGO session stops.

L) dotnet-pgo. create-mibc now merges (sums) several completed allocations for one method, for example inlined copies in several ReadyToRun bodies, instead of dropping the method. It ignores allocations that never executed and strips empty handle-histogram slots. If a method has both block and edge counts (interpreter DOTNET_InterpPGO plus ReadyToRun), it warns and skips that method's counters. Instrumentation-data events alone can now put a method into the profile.

M) SDK targets. PublishReadyToRunPgoInstrumentation=true adds --pgo-instrumentation on publish only; a plain build ignores it. The publish fails if EnableDiagnostics isn't true or WasmEnableThreads is true. The flag is part of the R2R up-to-date state, so toggling it reruns crossgen2.

N) Tests.

  • Crossgen2 unit tests in WasmArgumentLayoutTests: schema deduplication and layout, inlinee probes, IL preservation, and receiver, delegate and cast probes.
  • End-to-end Wasm.Build.Tests in EventPipeDiagnosticsTests: train in the browser → MIBC → republish → assert codegen. The existing Browser diagnostics scenarios move into the DiagnosticsScenarios test asset so the producer and consumer publishes can be shared.
  • A publish-versus-build test in ReadyToRunTests.
  • A dotnet-pgo merge unit test.

O) Docs. src/mono/wasm/features.md documents the producer → dotnet-pgo → consumer workflow. The dotnet-pgo README describes how allocations are merged.

P) Merged-in #138262. ComputeCallTargetMethodWithToken, the MethodFixupSignature asserts, the ConstrainedCalls/* test cases, the R2RTestSuites tests and src/tests/readytorun/resolved-constrained-calls come from #138262 (Wasm R2R method-entry imports for resolved constrained calls, fixes #138199). It is a fork PR, so it can't join the stack. Its latest head is merged into this PR only, and those changes will drop out of this diff once it lands on main.

Out of scope

  • vtable method-target profiling (JitVTableProfiling)
  • full generic virtual dispatch coverage
  • 32-bit counters
  • same-process tiering or OSR

This is offline training followed by a republish.

See the Dynamic PGO comparison and its delegate profiling follow-up.

Follow-ups

Tracking: #130521 (broader interpreter and exception-profile work remains open).

Note

This PR description was updated with GitHub Copilot assistance.

@pavelsavara pavelsavara added this to the 12.0.0 milestone Nov 13, 2026
@pavelsavara pavelsavara added arch-wasm WebAssembly architecture area-ReadyToRun labels Nov 13, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to 'arch-wasm': @lewing, @pavelsavara
See info in area-owners.md if you want to be subscribed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging @dotnet/jit-contrib for JIT-EE GUID update

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/crossgen-contrib
See info in area-owners.md if you want to be subscribed.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 6 pipeline(s).
9 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@pavelsavara
pavelsavara marked this pull request as ready for review November 16, 2026 12:28
@davidwrighton

Copy link
Copy Markdown
Member

@pavelsavara, why do we only capture data subset of methods. I would expect it would be simpler to capture all the data and then filter in dotnet-pgo. Also, why do we do block counts instead of edge counts like other jitted platforms? They should be basically equivalent. I would hope to have instrumentation which is as similar as possible to our normal platforms.

@AndyAyersMS

Copy link
Copy Markdown
Member

I had more or less similar feedback. I am not sure why we need extra something beyond making our "normal" PGO work for R2R images.

  • I can sort of see why direct counter updates is ok, though it also seems harmless to just use the normal count helper methods.
  • I am not sure why we want invocation counts for intrinsics that get expanded by the JIT, since these are generally always expanded...?
  • As David says the edge counters are somewhat more efficient / sparse and what we use elsewhere, and one can deduce the invocation counts from them.

jtschuster and others added 3 commits November 25, 2026 15:43
Cover a shared target instantiated over an external reference type (the
constraint is omitted), and an unshared value-type instantiation and generic
method dictionary over external types (the exact instantiation is kept).
Also check that the shared body's exact instantiation is still supplied by
its TypeDictionary import.

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
The existing test supplies CoreLib only as a reference, so deferred Wasm direct
calls are disabled and its MethodEntry_ReadyToRun readiness fixups are never
emitted. Add a Wasm composite variant with CoreLib as an unrooted input that
requires a constraint-free MethodEntry_ReadyToRun import for Enumerator`1.Dispose
and an ordinary MethodEntry import for the NoInlining control.

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
@pavelsavara

Copy link
Copy Markdown
Member Author

Quick update to the Dynamic PGO comparison as of b0c96a956dd2:

  • Delegate targets now round-trip through EventPipe and MIBC. On republish, Crossgen2 can guard and inline an eligible closed instance target. Chrome verified the hot path and the cold, static, multicast, and null cases. This closes the main default-on collection gap noted above; vtable target profiling (off by default in Dynamic PGO) is still out of scope.
  • Direct MSBuild Publish now works, ordinary builds stay uninstrumented, schema offsets are validated once per image, and export keeps the observed profile when the other producer recorded nothing.

After merging main, all 159 Wasm compiler tests and the three focused SDK/Chrome cases passed locally. No runtime speedup was measured.

Note

This update was prepared with GitHub Copilot.

@pavelsavara

pavelsavara commented Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

@pavelsavara

pavelsavara commented Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

Browser ReadyToRun PGO vs. historical InterpPGO

I ran BlazorWasm and Havit Bootstrap locally in headless Chrome 158 on Windows, using the Debug Browser CoreCLR runtime from this PR at b0c96a956dd2. Both apps were published as trimmed, non-composite, instrumented ReadyToRun; InterpPGO was off. The Havit walkthrough visited 76 sidebar routes, Showcase, and Home.

The MIBCs combine measured R2R counters with metadata-backed interpreter rundown roots.

Havit Bootstrap: corrected platform-filtered MIBC (ZIP)

The Havit profile was regenerated from the same trace using the full SDK assembly allowlist plus the two browser-specific Blazor references. The previous merge used abbreviated names from the text dump and unintentionally dropped System.Private.CoreLib, System.Private.Uri, and method groups that depended on them. The corrected profile retains those platform assemblies and excludes Havit app/package assemblies. BlazorWasm remains unfiltered. The historical Havit run was also platform-filtered, but the assembly sets can vary with SDK versions.

Metric BlazorWasm Havit Bootstrap
Historical rows / unique displayed signatures 2,430 / 2,430 3,295 / 3,290
Combined R2R rows / unique displayed signatures 8,699 / 8,698 11,616 / 11,605
R2R rows in assemblies represented in the historical profile 8,156 11,063
Historical rows with a nonzero 32-bit block count 2,413 1,583
R2R rows with a nonzero 64-bit edge count 7,921 10,036
R2R rows with a nonzero edge count in historical assemblies 7,411 9,516
Nonzero historical block entries / R2R edge entries 2,595 / 12,990 1,722 / 17,432
Unique displayed signatures present in both profiles 2,161 3,135
Unique displayed signatures with a nonzero counter in both profiles 1,966 1,025
Additional rows from interpreter rundown 460 642
Additional rundown rows in historical assemblies 428 609

Converting each trace with and without --include-interpreted-rundown confirmed that the added rows carry no probe data and that the edge counts are unchanged. Rundown roots identify prepared interpreter methods, not execution counts. The new dumps contain type and method handle histograms and value histograms, but no block counts. The historical dumps contain BasicBlockIntCount records.

Note

This comparison was prepared with GitHub Copilot.

pavelsavara and others added 2 commits November 26, 2026 16:42
In a composite image containing CoreLib, deferred Wasm readiness imports for
Queue<Marker>.Enumerator.Dispose and KeyValuePair<Marker, int>.ToString must
name only the shared CoreLib body, not the app-type constrained owner.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Deferred Wasm call finalization can legitimately leave KeyValuePair.ToString
as an ordinary MethodEntry in the composite. Keep the strict
MethodEntry_ReadyToRun requirement for Queue.Enumerator.Dispose, while
requiring the KeyValuePair import to be constraint-free regardless of the
finalization choice.

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
@AndyAyersMS

Copy link
Copy Markdown
Member

Wanted to see if JIT changes lead to any diffs in native targets, but SPMI job didn't run. Not sure why...

jtschuster and others added 2 commits November 30, 2026 19:49
Resolved constrained calls whose target is an async variant (awaited call in
a runtime-async method) or an instantiating stub (constrained. ldftn on a
generic value type) previously fell back to encoding the constraint. Name the
async variant by its primary method's token, and allow instantiating stubs:
their target is exact, so the signature still encodes the exact owning type.

Add an R2R unit test for the async case and runtime tests in
src/tests/readytorun covering the existing cases, the async case, and an IL
constrained. ldftn test.

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Ran the tests on browser WASM R2R locally. ResolvedConstrainedCall passes as is.
ResolvedConstrainedAsyncCall passes once DisposeAsync completes synchronously, since
browser cannot block on a pending task. ConstrainedLdftn still fails because typeof(T)
reaches an interpreted CoreLib helper through an R2R-to-interpreter thunk crossgen2
does not register, so keep it excluded with an accurate comment.

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
pavelsavara and others added 2 commits December 1, 2026 22:22
Add PublishReadyToRunPgoInstrumentation to the Browser CoreCLR
ReadyToRun targets. It passes --pgo-instrumentation on publish, and
publish fails if threads are enabled or diagnostics are disabled.

Move the Browser EventPipe diagnostics scenarios into a reusable test
asset and add end-to-end producer and consumer tests: train in the
browser, collect a trace, create a .mibc with dotnet-pgo, and verify
that the consumer publish uses the measured counts and type profiles.
Document the workflow in features.md.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Comment thread src/mono/wasm/features.md Resolved
Comment thread src/mono/wasm/features.md Resolved
Comment thread src/mono/wasm/features.md Resolved
pavelsavara and others added 3 commits December 2, 2026 12:38
Co-authored-by: Jan Kotas <jkotas@microsoft.com>
Co-authored-by: Jan Kotas <jkotas@microsoft.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Comment thread src/mono/wasm/features.md
#### CoreCLR profile-guided ReadyToRun publishing

Set `PublishReadyToRunPgoInstrumentation=true` to instrument compiled CoreCLR ReadyToRun
methods, including inlined bodies. This setting is

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: reflow after edits

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch-wasm WebAssembly architecture area-ReadyToRun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[browser][CoreCLR] Key Wasm R2R method-entry imports by shared body

6 participants