Skip to content

Design debug versions follow a replaced value

Eric Stern edited this page Nov 16, 2026 · 4 revisions

A debug version follows a replaced value when its position survives: a folded block argument

STATUS: LANDED 2026-11-16 as 9e3352c REV: 2 BASE: 5b23b0c7e3ff6681d578ae128b852c2d96c9a35e, tree clean, 2026-11-16

Issue: maxon-lang/maxon#136. The design decisions recorded there bind this plan.

1. The problem

A local's debug record (DebugLocalDecl) holds a sequence of versions, each naming one ValueId. The parser writes them; nothing owns them afterwards. When a pass replaces value A by value B and A's definition goes away, a version naming A names a value that is located nowhere. The debug-range harvest then treats it as a later version with a different value, which ends the earlier version where the dead one was recorded.

function scanFor(limit Word, stride Word) returns Word
	var found = false
	var chunk = 0 as Word
	var run = 0 as Word

	while chunk < 64 'scan'
		if (chunk + stride) mod 3 == 0 'used'
			chunk = chunk + 1
			run = 0
			continue
		end 'used'

		run = run + 1
		chunk = chunk + 1

		if run >= limit 'enough'
			found = true
			break
		end 'enough'
	end 'scan'

	if found 'hit'
		return chunk
	end 'hit'

	return stride
end 'scanFor'

Actual: at a stop on run = run + 1, print found answers unavailable (not-live-here), although false sits in found's location for the whole loop. Expected: false.

Proof of the fix: a tests/debug case over this shape with found held in a frame slot reads false inside the loop; a removed dead store of a different value still reads unavailable after it; the emitted executable of every program is byte-identical.

2a. Source facts

All paths under maxon-bin/Compiler/. Line numbers are at BASE.

The roster (IR/IrFunction.maxon)

  • DebugLocalVersion (1002-1037): let value as ValueId, let def as DebugVersionDef. Both immutable, so a changed version is a new record. DebugVersionDef (874-879): merged, definedSomewhere, definedIn(block), definedAfter(block, anchor ValueId).
  • DebugLocalDecl (1064-1189): versions, foldedConstant, foldedRecord, inlineSite, scopeEnds.
  • IrFunction.debugLocals (2478), with its stated invariant (2473-2477): their ValueIds are this function's own all the way to the register allocator, and a pass that renumbers values without them leaves a name on another value's location.
  • Mutators: makePrivate(SharedColumn.debugLocals) (2816-2831; the copy is shallow, so a writer clones the decl first, as NoteFoldedRecords.maxon:234 does), replaceDebugLocal (2850-2853), recordSplicedLocal (2959-2962).
  • Writers of versions: the parser only (ParserOwnership.maxon 268-357 and the rebind sites in ParserControlFlow.maxon, e.g. the loop-header version at 732), plus InlineLeaves' splice, which carries a callee's versions through its value column (DebugLocalDecl.splicedCopy, 1096-1120). No Std pass and not the Maxon to Std lowering updates a version's value.
  • Readers: BackendUnit.maxon 254-285 (DebugValueRoster.of, after every Std pass), the harvest in Targets/Shared/RegisterAllocator.maxon, Debug/MxdbgEmit.maxon, IR/Std/NoteFoldedRecords.maxon.

The folded-constant location. Set by the parser (ParserOwnership.noteFoldedBinding, 333-339) for a single-version binding whose value is a known constant. FoldConstants, RefineValueRanges, RefineVersionedRanges and FoldEstablishedGuards turn an op into a const under the SAME value id, so no version is left behind by them.

The replacement primitive (IR/Std/StdDialect.maxon): recordValueSubstitution (6015-6024), compressValueSubstitutions (6033), remappedValue (5989-5991), substituteValuesInFunc(module, func, subst) (6410-6414), and its pieces substituteValuesInBlock (6419-6429), substituteOpUses (6433-6436), substituteEdgeArgsInBlock (6446-6459).

Who replaces a value by another value

Pass Through What
ElimTrivialBlockArgs (336) substituteValuesInFunc a block argument by the single value it carries
FoldConstOperands (467) same an identity op's result by its operand
CommonSubexpressionElimination (130-131) same a redundant result by the canonical value
ElideImageRetains (157-179) same a retain's result by its source
BorrowedParameterReturns (364-403) same a call result by the inserted retain; a leaf by the parameter
CancelRetainRelease (423) same a partner's result by its operand
ValueTupleReturn (2173-2175, 2883-2891) same a half-load's result by the pair half
IR/Maxon/LowerMaxonToStd.substituteHoldAliases (7129-7137) same a hold copy's result by its operand
UnswitchInvariantGuards.readHoistedInPlace (1403-1421) substituteValuesInBlock a hoisted op's result by the chain copy, the canonical duplicate or a preheader load
UnswitchInvariantGuards.substituteExitPhis (1825-1863) op and edge pieces readers OUTSIDE the loop move to a new exit phi; the original value stays defined
ThreadConstantBranches.substituteJoinArgs (564-578) by hand on new edges only, a join's argument by the predecessor's incoming value

Passes that delete or rewrite in place and replace nothing: PruneDeadBlockArgs, the four constant folders above, StrengthReduceDivision, LoopInvariantCodeMotion, InlineManagedPrimitives, PromoteStackRecords, InsertRangeChecks, DeadFunctionElimination.

The pool. The fan-out passes (both block-argument passes, the folders, CSE, unswitching) run on a pool worker's copy of the function made by StdUnit.fillUnitModule (IR/Std/StdUnit.maxon 100-122), which carries no debugLocals; spliceStdUnit (176-214) writes back blocks, ops and nextBlockId only. Per-function side data that already crosses the pool and is folded on the main thread: DerivedOrigins in StdUnitBody (StdUnit.maxon 45-51; folded at StdPassPool.maxon 331, 357-358, 408-411). The band schedule runs on the real function.

No value-id compaction. Std, Target lowering and the splitter keep value ids, so a stale id stays dead; it never comes to name another value.

The mechanism in the reproduction. found's loop-header version names the header's block argument (ParserControlFlow.maxon:732, definedIn(header)). Its incoming values are false from the preheader and itself from both back edges, so elimTrivialBlockArgs folds it into false (ElimTrivialBlockArgs.maxon 125-158, 327-336) and drops the argument. The roster version still names it. The harvest finds no definition, places it by the parse at the header, locates it nowhere, and as a rival with a different value cuts the entry version at the header (RegisterAllocator.maxon 2003-2028, 2190-2201, 2251-2286).

What the harvest does with two versions of one value. isARivalWorthCutting (2393-2399) answers false when the rival's value is the version's own, so a later version naming the same value cuts nothing; for a frame slot repeatsEarlier (2091-2107) gives the repeat no rows of its own. Forwarding the header version to false is therefore sufficient with no change to the harvest.

2b. Spec-surface facts

  • Owner. Debugger-visible availability of a local is tested in tests/debug/ (.maxtest cases, fixtures at tests/debug/fixtures/<name>/main.maxon.fixture, harness tests/debug/DebugHarness.maxon). specs/debug-info-locals.md holds three compile-only cases and asserts nothing about availability at a stop.
  • Existing cases that touch it. None pins the positive behaviour: no fixture has a var assigned only on a break path and printed inside or after the loop. The closest:
    • sidecar-a-slot-local-with-a-dead-trailing-store-is-not-shown-stale.maxtest (fixture deadstore): asserts only Expect.notEqual(display, "5"), so any other number passes it.
    • sidecar-a-slot-local-assigned-in-a-loop-is-not-shown-stale-after-it.maxtest (rivalloop), …-whose-merge-phi-was-pruned-… (deadphi), …-assigned-in-an-arm-… (rivalarm), …-dead-store-sits-beyond-a-split-block-… (deadsplit): each asserts not-equal to the stale value.
    • sidecar-a-slot-local-before-a-dead-store-in-a-split-block-reads-its-value.maxtest: asserts the value 8 where a version dropped by position would answer not-live-here.
    • values-optimized-out.maxtest and sidecar-a-sibling-arm-does-not-see-a-slot-local-of-the-other.maxtest assert unavailability; neither is loop-carried.
  • Neighbours' shape. The slot is forced by thirteen values p0..p12 = n * k + c live across bytes.containsWhere(urlIsDigit); the case first asserts a row of the local containing StackSlotMark; a stop is a break <anchor line> then run, repeated stops with ContinueCommand; the answer is read through ValueKey, DisplayKey and UnavailableKey. Each fixture has a name constant in DebugHarness.maxon (198-258) and each case an entry in tests/README.md's layout tree, gated by tests/docs/the-readme-layout-tree-lists-every-test-case.maxtest.

3. The approach

One owner for value replacement, in the replacement primitive. A pass that rewrites the readers of a value states which kind of rewrite it is:

  • A replacement: the old value's definition goes away and every reader moves to the survivor. replaceValuesInFunc (a pass running on the real function) and substituteValuesInFunc / substituteValuesInBlock (a pass running on a pool unit) are replacements.
  • A redirection: some readers move and the original value stays defined. redirectReadsInFunc, redirectReadsInBlock, redirectReadsInOp and redirectEdgeArgsInBlock are redirections and record nothing.

A version follows a replacement only when its position survives exactly. Today that means a folded block argument.

  • When a replacement maps a block's own argument, the primitive notes it with the block that held it. The name took the survivor's value at that block's entry, and that position still exists after the fold.
  • A forwarded version that was merged, or definedAfter anchored at its own (replaced) value, becomes definedIn(the argument's block). A definedIn version keeps its def, and so does a definedAfter version anchored at another value.
  • A version whose replaced value was defined by an op is not forwarded, with no exceptions: common-subexpression elimination, an identity fold, a retain elision, a hold alias, a tuple half, a hoisted op. The version keeps naming the dead value and reads unavailable, as it did before this change.

Why an op-defined position does not survive. The parser positions x = <expr> after the expression's own value. When a pass replaces that value, the op that was the position is gone. The debug-range harvest then infers a position from the nearest surviving value id, and that guess can sit before the assignment. Measured cases: a counter read its next value one statement early, a name read length - 1 while it was still length, and a loop-carried name lost rows it had. A position inferred from neighbouring ids is not a position. Carrying a rebind's position through an op replacement is maxon-lang/maxon#145.

Rules of the fold (IrFunction.forwardDebugVersions):

  • Notes are kept in the order they were made and applied in that order, because a value id can be minted again after its definition is deleted. A chain of folded arguments is followed to its end; a survivor that a later pass replaces as an op result is not followed further.
  • A binding that carries a folded record is not forwarded: its folded words stay its location, as a folded constant does.
  • A forwarded version is not kept when the version immediately before it in its binding names the same value and that earlier version stands at the value's own definition (an unforwarded merged version, or a definedAfter version anchored at its own value). [false@entry, false@header] drops the header version; [A, B, A'] keeps A'; [k@arm, k@join] keeps k@join.
  • A value deleted as dead is not a replacement: its version keeps naming it, is located nowhere, and still ends the earlier version.
  • A value folded to a constant keeps its id; nothing is recorded.
  • The fold rebuilds only the decls it changes and never mutates a shared one. A function with no debug locals, and a build without debug info, allocates no record.

Where the fold runs. Directly after a pass that ran on the real function, and on the main thread when a pool unit returns: the record travels in StdUnitBody beside DerivedOrigins. Each record touches only its own function, so the result does not depend on the order units return in.

The replacement sites

Site What replaces what Kind A version follows?
ElimTrivialBlockArgs a block argument by the one value every edge carries replacement yes: the survivor dominates the block and the name took it at the block's entry
FoldConstOperands an identity op's result by its operand replacement no: op result
CommonSubexpressionElimination a redundant result by the canonical one replacement no: op result
ElideImageRetains a retain's result by its source replacement no: op result
BorrowedParameterReturns, callee leaf retain(param) by the parameter replacement no: op result
CancelRetainRelease a fused retain's result by its operand replacement no: op result
ValueTupleReturn a half-load's result by the pair half replacement no: op result
UnswitchInvariantGuards.readHoistedInPlace a hoisted op's result by the chain's copy replacement no: op result
LowerMaxonToStd.substituteHoldAliases a hold copy's result by its operand replacement no: op result
BorrowedParameterReturns, call site readers of a call's result move to the retain inserted after it; the call still defines its result redirection nothing is recorded
UnswitchInvariantGuards.substituteExitPhis readers outside the loop move to the exit argument redirection nothing is recorded
ThreadConstantBranches a join's argument by the predecessor's value, on new edges only redirection nothing is recorded

NoteFoldedRecords resolves a version through arguments for itself and runs before the block-argument passes; after the lowering's fold it sees the survivor and resolves from there.

Alternatives rejected

  • Patch ElimTrivialBlockArgs alone: the roster would still have no owner, and the inliner's continuation argument is folded by the same pass.
  • Resolve stale versions in the harvest or at the roster snapshot: the replaced value has no definition left to resolve through.
  • Give the pool's unit copy the roster: the copies deliberately carry no column a pass does not read.
  • Forward a version through an op-result replacement, keeping or forwarding its anchor: the position is lost either way (above).
  • Drop every forwarded version that repeats the one before it: in [k@arm1, k@arm2, k@join] neither arm dominates the join, so the join version is what makes the name readable after it.

4. Blast radius

  • IR/Std/StdDialect.maxon: the replacement record, the rewrite-kind entry, substituteValuesInFunc's signature.
  • The eight callers: IR/Std/ElimTrivialBlockArgs.maxon, FoldConstOperands.maxon, CommonSubexpressionElimination.maxon, ElideImageRetains.maxon, BorrowedParameterReturns.maxon, CancelRetainRelease.maxon, ValueTupleReturn.maxon, and IR/Maxon/LowerMaxonToStd.maxon (substituteHoldAliases only).
  • IR/Std/UnswitchInvariantGuards.maxon, IR/Std/ThreadConstantBranches.maxon: state their rewrite kind.
  • IR/Std/StdUnit.maxon, IR/Std/StdPassPool.maxon: carry and fold the record.
  • IR/IrFunction.maxon: the fold.
  • tests/debug/: two cases, two fixtures, two name constants in DebugHarness.maxon; tests/README.md layout entries.
  • Not touched: Targets/Shared/RegisterAllocator.maxon, Debug/MxdbgEmit.maxon, InlineLeaves.maxon, any Parser* file, NoteFoldedRecords.maxon.

One implementer for the primitive, the fold and the pool; the caller edits are mechanical and follow it in the same tree.

5. Obligations

  • Plain compiler source: one build. No emitted runtime, no target-specific arm, no new diagnostic.
  • No field of DebugLocalVersion or DebugLocalDecl changes, so no codec regeneration; the codecs check still runs.
  • The change adds types and may add an export: the self-compile gate runs.
  • A pass and the IR change: the scale-test ladder is read and recorded in docs/optimization-log.md.
  • Emitted code must be byte-identical to a compiler built from BASE: the self-compile and the tests/debug fixtures are compared, and ir-specs/ moves no pin.
  • No docs/ source describes version forwarding; the debugger reference's sentence about a local's range stays true.

6. Acceptance

All in tests/debug/.

Case Fixture Claim
a loop-carried slot local whose header argument was folded reads its value inside the loop foldedheader false at every stop inside the loop; failed before the change
a loop-carried slot local an inner if leaves alone reads its folded header value after the if mergedheader a merged version over a folded header argument reads false; failed before the change
a loop-carried local reassigned from an inlined call reads its value while the call's argument is set up tickedtotal the old value stays readable up to the call
a slot local whose dead store of another value was removed reads unavailable after it deadstore a dead value is not forwarded
a local both arms assign one value shows it only after the if equalarms never the new value before the if
a local reassigned a sum computed earlier shows it only after the reassignment resummed never the sum at the zeroed stop
a local zeroed between two equal sums shows the sum only after the second zeroedsum the same, with nothing value-defining between the sums
a local merged after both arms assign a refolded value is not shown it before the if refolded never the refolded value early
a local incremented by a sum an inlined call computed is not shown its next value early nextround the current value or an unavailability
a local reassigned in one arm from a value computed before the if keeps its old value on the other path carriagereturn the old value at the test and on the path that skips the arm
a local bound to an identity of another value reads that value or unavailable identityfold an op-result fold forwards nothing

7. Staging

ONE /land.

8. Open questions

None.

9. Amendments

  • 2026-11-16, REV 2. Forwarding is limited to folded block arguments: measurement showed an op-result replacement loses the version's position (§3). Added: the folded-record rule, the narrow drop of a repeated version, notes applied in order, and BorrowedParameterReturns' call site as a redirection. The case "after the join the name reads the arms' value", for two arms that assign one value, belongs to the debug-range harvest and lands with maxon-lang/maxon#118.

Clone this wiki locally